text
stringlengths
54
60.6k
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ParallelAlgoBinding.h" #include "GafferBindings/SignalBinding.h" #include "Gaffer/BackgroundTask.h" #include "Gaffer/ParallelAlgo.h" #include "Gaffer/Plug.h" #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILRelease.h" using namespace Gaffer; using namespace GafferBindings; using namespace boost::python; namespace { BackgroundTask *backgroundTaskConstructor( const Plug *subject, object f ) { auto fPtr = std::make_shared<boost::python::object>( f ); return new BackgroundTask( subject, [fPtr]( const IECore::Canceller &canceller ) mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)( boost::ref( canceller ) ); // We are likely to be the last owner of the python // function object. Make sure we release it while we // still hold the GIL. fPtr.reset(); } catch( boost::python::error_already_set &e ) { fPtr.reset(); IECorePython::ExceptionAlgo::translatePythonException(); } } ); } void backgroundTaskCancel( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.cancel(); } void backgroundTaskWait( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.wait(); } bool backgroundTaskWaitFor( BackgroundTask &b, float seconds ) { IECorePython::ScopedGILRelease gilRelease; return b.waitFor( seconds ); } void backgroundTaskCancelAndWait( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.cancelAndWait(); } BackgroundTask::Status backgroundTaskStatus( const BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; return b.status(); } struct GILReleaseUIThreadFunction { GILReleaseUIThreadFunction( ParallelAlgo::UIThreadFunction function ) : m_function( function ) { } void operator()() { IECorePython::ScopedGILRelease gilRelease; m_function(); } private : ParallelAlgo::UIThreadFunction m_function; }; void callOnUIThread( boost::python::object f ) { auto fPtr = std::make_shared<boost::python::object>( f ); IECorePython::ScopedGILRelease gilRelease; Gaffer::ParallelAlgo::callOnUIThread( [fPtr]() mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)(); // We are likely to be the last owner of the python // function object. Make sure we release it while we // still hold the GIL. fPtr.reset(); } catch( boost::python::error_already_set &e ) { fPtr.reset(); IECorePython::ExceptionAlgo::translatePythonException(); } } ); } void pushUIThreadCallHandler( boost::python::object handler ) { // The lambda below needs to own a reference to `handler`, // and in turn will be owned by the ParallelAlgo C++ API. // Wrap `handler` so we acquire the GIL when the lambda is // destroyed from C++. auto handlerPtr = std::shared_ptr<boost::python::object>( new boost::python::object( handler ), []( boost::python::object *o ) { IECorePython::ScopedGILLock gilLock; delete o; } ); IECorePython::ScopedGILRelease gilRelease; Gaffer::ParallelAlgo::pushUIThreadCallHandler( [handlerPtr] ( const ParallelAlgo::UIThreadFunction &function ) { IECorePython::ScopedGILLock gilLock; boost::python::object pythonFunction = make_function( GILReleaseUIThreadFunction( function ), boost::python::default_call_policies(), boost::mpl::vector<void>() ); (*handlerPtr)( pythonFunction ); } ); } std::shared_ptr<BackgroundTask> callOnBackgroundThread( const Plug *subject, boost::python::object f ) { // The BackgroundTask we return will own the python function we // pass to it. Wrap the function so that the GIL is acquired // before the python object is destroyed. auto fPtr = std::shared_ptr<boost::python::object>( new boost::python::object( f ), []( boost::python::object *o ) { IECorePython::ScopedGILLock gilLock; delete o; } ); auto backgroundTask = ParallelAlgo::callOnBackgroundThread( subject, [fPtr]() mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)(); } catch( boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } ); return std::shared_ptr<BackgroundTask>( backgroundTask.release(), // Custom deleter. We need to release // the GIL when deleting, because the destructor // waits on the background task, and the background // task might need the GIL in order to complete. []( BackgroundTask *t ) { IECorePython::ScopedGILRelease gilRelease; delete t; } ); } } // namespace void GafferModule::bindParallelAlgo() { { scope s = class_<BackgroundTask, boost::noncopyable>( "BackgroundTask", no_init ) .def( "__init__", make_constructor( &backgroundTaskConstructor, default_call_policies() ) ) .def( "cancel", &backgroundTaskCancel ) .def( "wait", &backgroundTaskWait ) .def( "waitFor", &backgroundTaskWaitFor ) .def( "cancelAndWait", &backgroundTaskCancelAndWait ) .def( "status", &backgroundTaskStatus ) ; enum_<BackgroundTask::Status>( "Status" ) .value( "Pending", BackgroundTask::Pending ) .value( "Running", BackgroundTask::Running ) .value( "Completed", BackgroundTask::Completed ) .value( "Cancelled", BackgroundTask::Cancelled ) .value( "Errored", BackgroundTask::Errored ) ; } register_ptr_to_python<std::shared_ptr<BackgroundTask>>(); object module( borrowed( PyImport_AddModule( "Gaffer.ParallelAlgo" ) ) ); scope().attr( "ParallelAlgo" ) = module; scope moduleScope( module ); def( "callOnUIThread", &callOnUIThread ); def( "pushUIThreadCallHandler", &pushUIThreadCallHandler ); def( "popUIThreadCallHandler", &ParallelAlgo::popUIThreadCallHandler ); def( "callOnBackgroundThread", &callOnBackgroundThread ); } <commit_msg>ParallelAlgoBinding : Release GIL in `popUIThreadCallHandler()`<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ParallelAlgoBinding.h" #include "GafferBindings/SignalBinding.h" #include "Gaffer/BackgroundTask.h" #include "Gaffer/ParallelAlgo.h" #include "Gaffer/Plug.h" #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILRelease.h" using namespace Gaffer; using namespace GafferBindings; using namespace boost::python; namespace { BackgroundTask *backgroundTaskConstructor( const Plug *subject, object f ) { auto fPtr = std::make_shared<boost::python::object>( f ); return new BackgroundTask( subject, [fPtr]( const IECore::Canceller &canceller ) mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)( boost::ref( canceller ) ); // We are likely to be the last owner of the python // function object. Make sure we release it while we // still hold the GIL. fPtr.reset(); } catch( boost::python::error_already_set &e ) { fPtr.reset(); IECorePython::ExceptionAlgo::translatePythonException(); } } ); } void backgroundTaskCancel( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.cancel(); } void backgroundTaskWait( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.wait(); } bool backgroundTaskWaitFor( BackgroundTask &b, float seconds ) { IECorePython::ScopedGILRelease gilRelease; return b.waitFor( seconds ); } void backgroundTaskCancelAndWait( BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; b.cancelAndWait(); } BackgroundTask::Status backgroundTaskStatus( const BackgroundTask &b ) { IECorePython::ScopedGILRelease gilRelease; return b.status(); } struct GILReleaseUIThreadFunction { GILReleaseUIThreadFunction( ParallelAlgo::UIThreadFunction function ) : m_function( function ) { } void operator()() { IECorePython::ScopedGILRelease gilRelease; m_function(); } private : ParallelAlgo::UIThreadFunction m_function; }; void callOnUIThread( boost::python::object f ) { auto fPtr = std::make_shared<boost::python::object>( f ); IECorePython::ScopedGILRelease gilRelease; Gaffer::ParallelAlgo::callOnUIThread( [fPtr]() mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)(); // We are likely to be the last owner of the python // function object. Make sure we release it while we // still hold the GIL. fPtr.reset(); } catch( boost::python::error_already_set &e ) { fPtr.reset(); IECorePython::ExceptionAlgo::translatePythonException(); } } ); } void pushUIThreadCallHandler( boost::python::object handler ) { // The lambda below needs to own a reference to `handler`, // and in turn will be owned by the ParallelAlgo C++ API. // Wrap `handler` so we acquire the GIL when the lambda is // destroyed from C++. auto handlerPtr = std::shared_ptr<boost::python::object>( new boost::python::object( handler ), []( boost::python::object *o ) { IECorePython::ScopedGILLock gilLock; delete o; } ); IECorePython::ScopedGILRelease gilRelease; Gaffer::ParallelAlgo::pushUIThreadCallHandler( [handlerPtr] ( const ParallelAlgo::UIThreadFunction &function ) { IECorePython::ScopedGILLock gilLock; boost::python::object pythonFunction = make_function( GILReleaseUIThreadFunction( function ), boost::python::default_call_policies(), boost::mpl::vector<void>() ); (*handlerPtr)( pythonFunction ); } ); } void popUIThreadCallHandler() { IECorePython::ScopedGILRelease gilRelease; ParallelAlgo::popUIThreadCallHandler(); } std::shared_ptr<BackgroundTask> callOnBackgroundThread( const Plug *subject, boost::python::object f ) { // The BackgroundTask we return will own the python function we // pass to it. Wrap the function so that the GIL is acquired // before the python object is destroyed. auto fPtr = std::shared_ptr<boost::python::object>( new boost::python::object( f ), []( boost::python::object *o ) { IECorePython::ScopedGILLock gilLock; delete o; } ); auto backgroundTask = ParallelAlgo::callOnBackgroundThread( subject, [fPtr]() mutable { IECorePython::ScopedGILLock gilLock; try { (*fPtr)(); } catch( boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } ); return std::shared_ptr<BackgroundTask>( backgroundTask.release(), // Custom deleter. We need to release // the GIL when deleting, because the destructor // waits on the background task, and the background // task might need the GIL in order to complete. []( BackgroundTask *t ) { IECorePython::ScopedGILRelease gilRelease; delete t; } ); } } // namespace void GafferModule::bindParallelAlgo() { { scope s = class_<BackgroundTask, boost::noncopyable>( "BackgroundTask", no_init ) .def( "__init__", make_constructor( &backgroundTaskConstructor, default_call_policies() ) ) .def( "cancel", &backgroundTaskCancel ) .def( "wait", &backgroundTaskWait ) .def( "waitFor", &backgroundTaskWaitFor ) .def( "cancelAndWait", &backgroundTaskCancelAndWait ) .def( "status", &backgroundTaskStatus ) ; enum_<BackgroundTask::Status>( "Status" ) .value( "Pending", BackgroundTask::Pending ) .value( "Running", BackgroundTask::Running ) .value( "Completed", BackgroundTask::Completed ) .value( "Cancelled", BackgroundTask::Cancelled ) .value( "Errored", BackgroundTask::Errored ) ; } register_ptr_to_python<std::shared_ptr<BackgroundTask>>(); object module( borrowed( PyImport_AddModule( "Gaffer.ParallelAlgo" ) ) ); scope().attr( "ParallelAlgo" ) = module; scope moduleScope( module ); def( "callOnUIThread", &callOnUIThread ); def( "pushUIThreadCallHandler", &pushUIThreadCallHandler ); def( "popUIThreadCallHandler", &popUIThreadCallHandler ); def( "callOnBackgroundThread", &callOnBackgroundThread ); } <|endoftext|>
<commit_before>// =============================== // PC-BSD REST API Server // Available under the 3-clause BSD License // Written by: Ken Moore <[email protected]> 2015-2016 // ================================= #include "EventWatcher.h" #include "globals.h" // === PUBLIC === EventWatcher::EventWatcher(){ qRegisterMetaType<EventWatcher::EVENT_TYPE>("EventWatcher::EVENT_TYPE"); starting = true; LPlog_pos = LPrep_pos = LPerr_pos = 0; //no pos yet watcher = new QFileSystemWatcher(this); filechecktimer = new QTimer(this); filechecktimer->setSingleShot(false); filechecktimer->setInterval(3600000); //1-hour checks (also run on new event notices) connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(WatcherUpdate(const QString&)) ); connect(watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(WatcherUpdate(const QString&)) ); connect(filechecktimer, SIGNAL(timeout()), this, SLOT( CheckLogFiles()) ); } EventWatcher::~EventWatcher(){ } void EventWatcher::start(){ // - DISPATCH Events starting = true; //if(!QFile::exists(DISPATCHWORKING)){ QProcess::execute("touch "+DISPATCHWORKING); } //qDebug() << " Dispatcher Events:" << DISPATCHWORKING; //WatcherUpdate(DISPATCHWORKING); //load it initially (will also add it to the watcher) // - Life Preserver Events WatcherUpdate(LPLOG); //load it initially (will also add it to the watcher); WatcherUpdate(LPERRLOG); //load it initially (will also add it to the watcher); filechecktimer->start(); starting = false; } EventWatcher::EVENT_TYPE EventWatcher::typeFromString(QString typ){ if(typ=="dispatcher"){ return DISPATCHER; } else if(typ=="life-preserver"){ return LIFEPRESERVER; } else{ return BADEVENT; } } QJsonValue EventWatcher::lastEvent(EVENT_TYPE type){ if(HASH.contains(type)){ return HASH.value(type); } else{ qDebug() << "No saved event:" << type; return QJsonValue(); } } // === PRIVATE === void EventWatcher::sendLPEvent(QString system, int priority, QString msg){ QJsonObject obj; obj.insert("message",msg); obj.insert("priority", DisplayPriority(priority) ); obj.insert("class" , system); HASH.insert(LIFEPRESERVER, obj); //qDebug() << "New LP Event Object:" << obj; LogManager::log(LogManager::EV_LP, obj); if(!starting){ emit NewEvent(LIFEPRESERVER, obj); } } // === General Purpose Functions QString EventWatcher::readFile(QString path){ QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ return ""; } QTextStream in(&file); QString contents = in.readAll(); file.close(); if(contents.endsWith("\n")){ contents.chop(1); } return contents; } double EventWatcher::displayToDoubleK(QString displayNumber){ QStringList labels; labels << "K" << "M" << "G" << "T" << "P" << "E"; QString clab = displayNumber.right(1); //last character is the size label displayNumber.chop(1); //remove the label from the number double num = displayNumber.toDouble(); //Now format the number properly bool ok = false; clab = clab.toUpper(); for(int i=0; i<labels.length(); i++){ if(labels[i] == clab){ ok = true; break; } else{ num = num*1024; } //get ready for the next size } if(!ok){ num = -1; } //could not determine the size return num; } // === PUBLIC SLOTS === //Slots for the global Dispatcher to connect to void EventWatcher::DispatchStarting(QString ID){ QJsonObject obj; obj.insert("process_id", ID); obj.insert("state", "running"); LogManager::log(LogManager::EV_DISPATCH, obj); emit NewEvent(DISPATCHER, obj); } void EventWatcher::DispatchFinished(QJsonObject obj){ LogManager::log(LogManager::EV_DISPATCH, obj); emit NewEvent(DISPATCHER, obj); } // === PRIVATE SLOTS === void EventWatcher::WatcherUpdate(const QString &path){ if(!starting){ qDebug() << "Event Watcher Update:" << path; } if(path==LPLOG){ //Main Life Preserver Log File ReadLPLogFile(); }else if(path==LPERRLOG){ //Life Preserver Error log ReadLPErrFile(); }else if(path==tmpLPRepFile){ //Life Preserver Replication Log (currently-running replication) ReadLPRepFile(); }else{ //This file should no longer be watched (old replication file?) if(watcher->files().contains(path) || watcher->directories().contains(path)){ watcher->removePath(path); } } CheckLogFiles(); //check for any other missing files } void EventWatcher::CheckLogFiles(){ //Make sure all the proper files are being watched QStringList watched; watched << watcher->files() << watcher->directories(); if(!watched.contains(LPLOG) && QFile::exists(LPLOG)){ watcher->addPath(LPLOG); } if(!watched.contains(LPERRLOG) && QFile::exists(LPERRLOG)){ watcher->addPath(LPERRLOG); } if(!watched.contains(tmpLPRepFile) && QFile::exists(tmpLPRepFile)){ watcher->addPath(tmpLPRepFile); } //qDebug() << "watched:" << watcher->files() << watcher->directories(); } // == Life Preserver Event Functions void EventWatcher::ReadLPLogFile(){ //Open/Read any new info in the file QFile LPlogfile(LPLOG); if( !LPlogfile.open(QIODevice::ReadOnly) ){ return; } //could not open file QTextStream STREAM(&LPlogfile); if(LPlog_pos>0){ STREAM.seek(LPlog_pos); } QStringList info = STREAM.readAll().split("\n"); LPlog_pos = STREAM.pos(); LPlogfile.close(); //Now parse the new info line-by-line for(int i=0; i<info.length(); i++){ if(info[i].isEmpty()){ continue; } QString log = info[i]; if(!starting){ qDebug() << "Read LP Log File Line:" << log; } //Divide up the log into it's sections QString timestamp = log.section(":",0,2).simplified(); QString time = timestamp.section(" ",3,3).simplified(); QString message = log.section(":",3,3).toLower().simplified(); QString dev = log.section(":",4,4).simplified(); //dataset/snapshot/nothing //Now decide what to do/show because of the log message if(message.contains("creating snapshot", Qt::CaseInsensitive)){ dev = message.section(" ",-1).simplified(); QString msg = QString(tr("New snapshot of %1")).arg(dev); //Setup the status of the message HASH.insert(110,"SNAPCREATED"); HASH.insert(111,dev); //dataset HASH.insert(112, msg ); //summary HASH.insert(113, QString(tr("Creating snapshot for %1")).arg(dev) ); HASH.insert(114, timestamp); //full timestamp HASH.insert(115, time); // time only sendLPEvent("snapshot", 1, timestamp+": "+msg); }else if(message.contains("Starting replication", Qt::CaseInsensitive)){ //Setup the file watcher for this new log file //qDebug() << " - Found Rep Start:" << dev << message; tmpLPRepFile = dev; LPrep_pos = 0; //reset file position dev = message.section(" on ",1,1,QString::SectionSkipEmpty); //qDebug() << " - New Dev:" << dev << "Valid Pools:" << reppools; //Make sure the device is currently setup for replication //if( !reppools.contains(dev) ){ FILE_REPLICATION.clear(); continue; } QString msg = QString(tr("Starting replication for %1")).arg(dev); //Set the appropriate status variables HASH.insert(120,"STARTED"); HASH.insert(121, dev); //zpool HASH.insert(122, tr("Replication Starting") ); //summary HASH.insert(123, msg ); //Full message HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126,tr("Replication Log")+" <"+tmpLPRepFile+">"); //log file sendLPEvent("replication", 1, timestamp+": "+msg); }else if(message.contains("finished replication task", Qt::CaseInsensitive)){ //Done with this replication - close down the rep file watcher tmpLPRepFile.clear(); LPrep_pos = 0; //reset file position dev = message.section(" -> ",0,0).section(" ",-1).simplified(); //Make sure the device is currently setup for replication //if( reppools.contains(dev) ){ QString msg = QString(tr("Finished replication for %1")).arg(dev); //Now set the status of the process HASH.insert(120,"FINISHED"); HASH.insert(121,dev); //dataset HASH.insert(122, tr("Finished Replication") ); //summary HASH.insert(123, msg ); HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126, ""); //clear the log file entry sendLPEvent("replication", 1, timestamp+": "+msg); }else if( message.contains("FAILED replication", Qt::CaseInsensitive) ){ tmpLPRepFile.clear(); LPrep_pos = 0; //reset file position //Now set the status of the process dev = message.section(" -> ",0,0).section(" ",-1).simplified(); //Make sure the device is currently setup for replication //Update the HASH QString file = log.section("LOGFILE:",1,1).simplified(); QString tt = QString(tr("Replication Failed for %1")).arg(dev) +"\n"+ QString(tr("Logfile available at: %1")).arg(file); HASH.insert(120,"ERROR"); HASH.insert(121,dev); //dataset HASH.insert(122, tr("Replication Failed") ); //summary HASH.insert(123, tt ); HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126, tr("Replication Error Log")+" <"+file+">" ); sendLPEvent("replication", 7, timestamp+": "+tt); } } } void EventWatcher::ReadLPErrFile(){ } void EventWatcher::ReadLPRepFile(){ static QString stat = ""; static QString repTotK = ""; static QString lastSize = ""; //Open/Read any new info in the file QFile LPlogfile(LPLOG); if( !LPlogfile.open(QIODevice::ReadOnly) ){ return; } //could not open file QTextStream STREAM(&LPlogfile); if(LPrep_pos<=0 || !STREAM.seek(LPrep_pos) ){ //New file location stat.clear(); repTotK.clear(); lastSize.clear(); } QStringList info = STREAM.readAll().split("\n"); LPrep_pos = STREAM.pos(); LPlogfile.close(); //Now parse the new info line-by-line for(int i=0; i<info.length(); i++){ QString line = info[i]; if(line.contains("estimated size is")){ repTotK = line.section("size is ",1,1,QString::SectionSkipEmpty).simplified(); } //save the total size to replicate else if(line.startsWith("send from ")){} else if(line.startsWith("TIME ")){} else if(line.startsWith("warning: ")){} //start of an error else{ stat = line; } //only save the relevant/latest status line } if(!stat.isEmpty()){ //qDebug() << "New Status Message:" << stat; //Divide up the status message into sections stat.replace("\t"," "); QString dataset = stat.section(" ",2,2,QString::SectionSkipEmpty).section("/",0,0).simplified(); QString cSize = stat.section(" ",1,1,QString::SectionSkipEmpty); //Now Setup the tooltip if(cSize != lastSize){ //don't update the info if the same size info QString percent; if(!repTotK.isEmpty() && repTotK!="??"){ //calculate the percentage double tot = displayToDoubleK(repTotK); double c = displayToDoubleK(cSize); if( tot!=-1 & c!=-1){ double p = (c*100)/tot; p = int(p*10)/10.0; //round to 1 decimel places percent = QString::number(p) + "%"; } } if(repTotK.isEmpty()){ repTotK = "??"; } //Format the info string QString status = cSize+"/"+repTotK; if(!percent.isEmpty()){ status.append(" ("+percent+")"); } QString txt = QString(tr("Replicating %1: %2")).arg(dataset, status); lastSize = cSize; //save the current size for later //Now set the current process status HASH.insert(120,"RUNNING"); HASH.insert(121,dataset); HASH.insert(122,txt); HASH.insert(123,txt); emit sendLPEvent("replication", 0, txt); } } } <commit_msg>Make sure the event file watcher checks for new watched files on a more regular basis. This will check every time a client asks for the latest logs, and will automatically load/parse any new file which appears.<commit_after>// =============================== // PC-BSD REST API Server // Available under the 3-clause BSD License // Written by: Ken Moore <[email protected]> 2015-2016 // ================================= #include "EventWatcher.h" #include "globals.h" // === PUBLIC === EventWatcher::EventWatcher(){ qRegisterMetaType<EventWatcher::EVENT_TYPE>("EventWatcher::EVENT_TYPE"); starting = true; LPlog_pos = LPrep_pos = LPerr_pos = 0; //no pos yet watcher = new QFileSystemWatcher(this); filechecktimer = new QTimer(this); filechecktimer->setSingleShot(false); filechecktimer->setInterval(3600000); //1-hour checks (also run on new event notices) connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(WatcherUpdate(const QString&)) ); connect(watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(WatcherUpdate(const QString&)) ); connect(filechecktimer, SIGNAL(timeout()), this, SLOT( CheckLogFiles()) ); } EventWatcher::~EventWatcher(){ } void EventWatcher::start(){ // - DISPATCH Events starting = true; //if(!QFile::exists(DISPATCHWORKING)){ QProcess::execute("touch "+DISPATCHWORKING); } //qDebug() << " Dispatcher Events:" << DISPATCHWORKING; //WatcherUpdate(DISPATCHWORKING); //load it initially (will also add it to the watcher) // - Life Preserver Events WatcherUpdate(LPLOG); //load it initially (will also add it to the watcher); WatcherUpdate(LPERRLOG); //load it initially (will also add it to the watcher); filechecktimer->start(); starting = false; } EventWatcher::EVENT_TYPE EventWatcher::typeFromString(QString typ){ if(typ=="dispatcher"){ return DISPATCHER; } else if(typ=="life-preserver"){ return LIFEPRESERVER; } else{ return BADEVENT; } } QJsonValue EventWatcher::lastEvent(EVENT_TYPE type){ CheckLogFiles(); if(HASH.contains(type)){ return HASH.value(type); } else{ qDebug() << "No saved event:" << type; return QJsonValue(); } } // === PRIVATE === void EventWatcher::sendLPEvent(QString system, int priority, QString msg){ QJsonObject obj; obj.insert("message",msg); obj.insert("priority", DisplayPriority(priority) ); obj.insert("class" , system); HASH.insert(LIFEPRESERVER, obj); //qDebug() << "New LP Event Object:" << obj; LogManager::log(LogManager::EV_LP, obj); if(!starting){ emit NewEvent(LIFEPRESERVER, obj); } } // === General Purpose Functions QString EventWatcher::readFile(QString path){ QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ return ""; } QTextStream in(&file); QString contents = in.readAll(); file.close(); if(contents.endsWith("\n")){ contents.chop(1); } return contents; } double EventWatcher::displayToDoubleK(QString displayNumber){ QStringList labels; labels << "K" << "M" << "G" << "T" << "P" << "E"; QString clab = displayNumber.right(1); //last character is the size label displayNumber.chop(1); //remove the label from the number double num = displayNumber.toDouble(); //Now format the number properly bool ok = false; clab = clab.toUpper(); for(int i=0; i<labels.length(); i++){ if(labels[i] == clab){ ok = true; break; } else{ num = num*1024; } //get ready for the next size } if(!ok){ num = -1; } //could not determine the size return num; } // === PUBLIC SLOTS === //Slots for the global Dispatcher to connect to void EventWatcher::DispatchStarting(QString ID){ QJsonObject obj; obj.insert("process_id", ID); obj.insert("state", "running"); LogManager::log(LogManager::EV_DISPATCH, obj); emit NewEvent(DISPATCHER, obj); } void EventWatcher::DispatchFinished(QJsonObject obj){ LogManager::log(LogManager::EV_DISPATCH, obj); emit NewEvent(DISPATCHER, obj); } // === PRIVATE SLOTS === void EventWatcher::WatcherUpdate(const QString &path){ if(!starting){ qDebug() << "Event Watcher Update:" << path; } if(path==LPLOG){ //Main Life Preserver Log File ReadLPLogFile(); }else if(path==LPERRLOG){ //Life Preserver Error log ReadLPErrFile(); }else if(path==tmpLPRepFile){ //Life Preserver Replication Log (currently-running replication) ReadLPRepFile(); }else{ //This file should no longer be watched (old replication file?) if(watcher->files().contains(path) || watcher->directories().contains(path)){ watcher->removePath(path); } } QTimer::singleShot(10,this, SLOT(CheckLogFiles()) ); //check for any other missing files } void EventWatcher::CheckLogFiles(){ //Make sure all the proper files are being watched QStringList watched; watched << watcher->files() << watcher->directories(); if(!watched.contains(LPLOG) && QFile::exists(LPLOG)){ watcher->addPath(LPLOG); WatcherUpdate(LPLOG); } if(!watched.contains(LPERRLOG) && QFile::exists(LPERRLOG)){ watcher->addPath(LPERRLOG); WatcherUpdate(LPERRLOG); } if(!watched.contains(tmpLPRepFile) && QFile::exists(tmpLPRepFile)){ watcher->addPath(tmpLPRepFile); WatcherUpdate(tmpLPRepFile); } //qDebug() << "watched:" << watcher->files() << watcher->directories(); } // == Life Preserver Event Functions void EventWatcher::ReadLPLogFile(){ //Open/Read any new info in the file QFile LPlogfile(LPLOG); if( !LPlogfile.open(QIODevice::ReadOnly) ){ return; } //could not open file QTextStream STREAM(&LPlogfile); if(LPlog_pos>0){ STREAM.seek(LPlog_pos); } QStringList info = STREAM.readAll().split("\n"); LPlog_pos = STREAM.pos(); LPlogfile.close(); //Now parse the new info line-by-line for(int i=0; i<info.length(); i++){ if(info[i].isEmpty()){ continue; } QString log = info[i]; if(!starting){ qDebug() << "Read LP Log File Line:" << log; } //Divide up the log into it's sections QString timestamp = log.section(":",0,2).simplified(); QString time = timestamp.section(" ",3,3).simplified(); QString message = log.section(":",3,3).toLower().simplified(); QString dev = log.section(":",4,4).simplified(); //dataset/snapshot/nothing //Now decide what to do/show because of the log message if(message.contains("creating snapshot", Qt::CaseInsensitive)){ dev = message.section(" ",-1).simplified(); QString msg = QString(tr("New snapshot of %1")).arg(dev); //Setup the status of the message HASH.insert(110,"SNAPCREATED"); HASH.insert(111,dev); //dataset HASH.insert(112, msg ); //summary HASH.insert(113, QString(tr("Creating snapshot for %1")).arg(dev) ); HASH.insert(114, timestamp); //full timestamp HASH.insert(115, time); // time only sendLPEvent("snapshot", 1, timestamp+": "+msg); }else if(message.contains("Starting replication", Qt::CaseInsensitive)){ //Setup the file watcher for this new log file //qDebug() << " - Found Rep Start:" << dev << message; tmpLPRepFile = dev; LPrep_pos = 0; //reset file position dev = message.section(" on ",1,1,QString::SectionSkipEmpty); //qDebug() << " - New Dev:" << dev << "Valid Pools:" << reppools; //Make sure the device is currently setup for replication //if( !reppools.contains(dev) ){ FILE_REPLICATION.clear(); continue; } QString msg = QString(tr("Starting replication for %1")).arg(dev); //Set the appropriate status variables HASH.insert(120,"STARTED"); HASH.insert(121, dev); //zpool HASH.insert(122, tr("Replication Starting") ); //summary HASH.insert(123, msg ); //Full message HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126,tr("Replication Log")+" <"+tmpLPRepFile+">"); //log file sendLPEvent("replication", 1, timestamp+": "+msg); }else if(message.contains("finished replication task", Qt::CaseInsensitive)){ //Done with this replication - close down the rep file watcher tmpLPRepFile.clear(); LPrep_pos = 0; //reset file position dev = message.section(" -> ",0,0).section(" ",-1).simplified(); //Make sure the device is currently setup for replication //if( reppools.contains(dev) ){ QString msg = QString(tr("Finished replication for %1")).arg(dev); //Now set the status of the process HASH.insert(120,"FINISHED"); HASH.insert(121,dev); //dataset HASH.insert(122, tr("Finished Replication") ); //summary HASH.insert(123, msg ); HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126, ""); //clear the log file entry sendLPEvent("replication", 1, timestamp+": "+msg); }else if( message.contains("FAILED replication", Qt::CaseInsensitive) ){ tmpLPRepFile.clear(); LPrep_pos = 0; //reset file position //Now set the status of the process dev = message.section(" -> ",0,0).section(" ",-1).simplified(); //Make sure the device is currently setup for replication //Update the HASH QString file = log.section("LOGFILE:",1,1).simplified(); QString tt = QString(tr("Replication Failed for %1")).arg(dev) +"\n"+ QString(tr("Logfile available at: %1")).arg(file); HASH.insert(120,"ERROR"); HASH.insert(121,dev); //dataset HASH.insert(122, tr("Replication Failed") ); //summary HASH.insert(123, tt ); HASH.insert(124, timestamp); //full timestamp HASH.insert(125, time); // time only HASH.insert(126, tr("Replication Error Log")+" <"+file+">" ); sendLPEvent("replication", 7, timestamp+": "+tt); } } } void EventWatcher::ReadLPErrFile(){ } void EventWatcher::ReadLPRepFile(){ static QString stat = ""; static QString repTotK = ""; static QString lastSize = ""; //Open/Read any new info in the file QFile LPlogfile(LPLOG); if( !LPlogfile.open(QIODevice::ReadOnly) ){ return; } //could not open file QTextStream STREAM(&LPlogfile); if(LPrep_pos<=0 || !STREAM.seek(LPrep_pos) ){ //New file location stat.clear(); repTotK.clear(); lastSize.clear(); } QStringList info = STREAM.readAll().split("\n"); LPrep_pos = STREAM.pos(); LPlogfile.close(); //Now parse the new info line-by-line for(int i=0; i<info.length(); i++){ QString line = info[i]; if(line.contains("estimated size is")){ repTotK = line.section("size is ",1,1,QString::SectionSkipEmpty).simplified(); } //save the total size to replicate else if(line.startsWith("send from ")){} else if(line.startsWith("TIME ")){} else if(line.startsWith("warning: ")){} //start of an error else{ stat = line; } //only save the relevant/latest status line } if(!stat.isEmpty()){ //qDebug() << "New Status Message:" << stat; //Divide up the status message into sections stat.replace("\t"," "); QString dataset = stat.section(" ",2,2,QString::SectionSkipEmpty).section("/",0,0).simplified(); QString cSize = stat.section(" ",1,1,QString::SectionSkipEmpty); //Now Setup the tooltip if(cSize != lastSize){ //don't update the info if the same size info QString percent; if(!repTotK.isEmpty() && repTotK!="??"){ //calculate the percentage double tot = displayToDoubleK(repTotK); double c = displayToDoubleK(cSize); if( tot!=-1 & c!=-1){ double p = (c*100)/tot; p = int(p*10)/10.0; //round to 1 decimel places percent = QString::number(p) + "%"; } } if(repTotK.isEmpty()){ repTotK = "??"; } //Format the info string QString status = cSize+"/"+repTotK; if(!percent.isEmpty()){ status.append(" ("+percent+")"); } QString txt = QString(tr("Replicating %1: %2")).arg(dataset, status); lastSize = cSize; //save the current size for later //Now set the current process status HASH.insert(120,"RUNNING"); HASH.insert(121,dataset); HASH.insert(122,txt); HASH.insert(123,txt); emit sendLPEvent("replication", 0, txt); } } } <|endoftext|>
<commit_before>/* * PoolConn.cpp * * Created on: Apr 7, 2009 * Author: rasmussn */ #include "PoolConn.hpp" #include <assert.h> #include <string.h> namespace PV { PoolConn::PoolConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) { this->connId = hc->numberOfConnections(); this->name = strdup(name); this->parent = hc; this->numAxonalArborLists = 1; initialize(NULL, pre, post, channel); hc->addConnection(this); } int PoolConn::initializeWeights(const char * filename) { if (filename == NULL) { PVParams * params = parent->parameters(); const float strength = params->value(name, "strength"); const int xScale = pre->clayer->xScale; const int yScale = pre->clayer->yScale; int nfPre = pre->clayer->numFeatures; const int arbor = 0; const int numPatches = numberOfWeightPatches(arbor); for (int i = 0; i < numPatches; i++) { int fPre = i % nfPre; poolWeights(wPatches[arbor][i], fPre, xScale, yScale, strength); } } else { fprintf(stderr, "Initializing weights from a file not implemented for RuleConn\n"); exit(1); } // end if for filename return 0; } int PoolConn::poolWeights(PVPatch * wp, int fPre, int xScale, int yScale, float strength) { pvdata_t * w = wp->data; const int nx = (int) wp->nx; const int ny = (int) wp->ny; const int nf = (int) wp->nf; // strides const int sx = (int) wp->sx; assert(sx == nf); const int sy = (int) wp->sy; assert(sy == nf*nx); const int sf = (int) wp->sf; assert(sf == 1); assert(fPre >= 0 && fPre <= 15); assert(nx == 1); assert(ny == 1); assert(nf == 2); // initialize connections of OFF and ON cells to 0 for (int f = 0; f < nf; f++) { for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { w[i*sx + j*sy + f*sf] = 0; } } } // connect an OFF cells to all OFF cells (and vice versa) for (int f = (fPre % 2); f < nf; f += 2) { w[0*sx + 0*sy + f*sf] = 1; } for (int f = 0; f < nf; f++) { float factor = strength; for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor; } return 0; } } // namespace PV <commit_msg>Simplified constructors and unified initialization.<commit_after>/* * PoolConn.cpp * * Created on: Apr 7, 2009 * Author: rasmussn */ #include "PoolConn.hpp" #include <assert.h> #include <string.h> namespace PV { PoolConn::PoolConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) : HyPerConn(name, hc, pre, post, channel, PROTECTED_NUMBER) { this->numAxonalArborLists = 1; initialize(); hc->addConnection(this); } int PoolConn::initializeWeights(const char * filename) { if (filename == NULL) { PVParams * params = parent->parameters(); const float strength = params->value(name, "strength"); const int xScale = pre->clayer->xScale; const int yScale = pre->clayer->yScale; int nfPre = pre->clayer->numFeatures; const int arbor = 0; const int numPatches = numberOfWeightPatches(arbor); for (int i = 0; i < numPatches; i++) { int fPre = i % nfPre; poolWeights(wPatches[arbor][i], fPre, xScale, yScale, strength); } } else { fprintf(stderr, "Initializing weights from a file not implemented for RuleConn\n"); exit(1); } // end if for filename return 0; } int PoolConn::poolWeights(PVPatch * wp, int fPre, int xScale, int yScale, float strength) { pvdata_t * w = wp->data; const int nx = (int) wp->nx; const int ny = (int) wp->ny; const int nf = (int) wp->nf; // strides const int sx = (int) wp->sx; assert(sx == nf); const int sy = (int) wp->sy; assert(sy == nf*nx); const int sf = (int) wp->sf; assert(sf == 1); assert(fPre >= 0 && fPre <= 15); assert(nx == 1); assert(ny == 1); assert(nf == 2); // initialize connections of OFF and ON cells to 0 for (int f = 0; f < nf; f++) { for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { w[i*sx + j*sy + f*sf] = 0; } } } // connect an OFF cells to all OFF cells (and vice versa) for (int f = (fPre % 2); f < nf; f += 2) { w[0*sx + 0*sy + f*sf] = 1; } for (int f = 0; f < nf; f++) { float factor = strength; for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor; } return 0; } } // namespace PV <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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. */ /// \author James Hughes /// \date September 2012 /// \brief Not sure this file should go in Modules/Render. But it is an /// auxiliary file to the ViewScene render module. #include <Interface/Modules/Render/GLWidget.h> #include <iostream> #include <QMouseEvent> #include <QWheelEvent> #include <QTimer> #include <QtDebug> #include <Core/Application/Application.h> namespace SCIRun { namespace Gui { const int RendererUpdateInMS = 35; const double updateTime = RendererUpdateInMS / 1000.0; //------------------------------------------------------------------------------ GLWidget::GLWidget(QtGLContext* context, QWidget* parent) : QGLWidget(context, parent), mContext(new GLContext(this)), mCurrentTime(0.0) { /// \todo Implement this intelligently. This function is called everytime /// there is a new graphics context. std::vector<std::string> shaderSearchDirs; mContext->makeCurrent(); spire::glPlatformInit(); auto frameInitLimitFromCommandLine = Core::Application::Instance().parameters()->developerParameters()->frameInitLimit(); if (frameInitLimitFromCommandLine) { std::cout << "Renderer frame init limit changed to " << *frameInitLimitFromCommandLine << std::endl; } const int frameInitLimit = frameInitLimitFromCommandLine.get_value_or(100); mGraphics.reset(new Render::SRInterface(mContext, frameInitLimit)); mTimer = new QTimer(this); connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer())); mTimer->start(RendererUpdateInMS); // We must disable auto buffer swap on the 'paintEvent'. setAutoBufferSwap(false); } //------------------------------------------------------------------------------ GLWidget::~GLWidget() { // Need to inform module that the context is being destroyed. if (mGraphics != nullptr) { //std::cout << "Terminating spire." << std::endl; mGraphics.reset(); } } //------------------------------------------------------------------------------ void GLWidget::initializeGL() { } //------------------------------------------------------------------------------ SCIRun::Render::SRInterface::MouseButton GLWidget::getSpireButton(QMouseEvent* event) { auto btn = SCIRun::Render::SRInterface::MOUSE_NONE; if (event->buttons() & Qt::LeftButton) btn = Render::SRInterface::MOUSE_LEFT; else if (event->buttons() & Qt::RightButton) btn = Render::SRInterface::MOUSE_RIGHT; else if (event->buttons() & Qt::MidButton) btn = Render::SRInterface::MOUSE_MIDDLE; return btn; } //------------------------------------------------------------------------------ void GLWidget::mouseMoveEvent(QMouseEvent* event) { // Extract appropriate key. auto btn = getSpireButton(event); mGraphics->inputMouseMove(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::mousePressEvent(QMouseEvent* event) { auto btn = getSpireButton(event); mGraphics->inputMouseDown(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::mouseReleaseEvent(QMouseEvent* event) { auto btn = getSpireButton(event); mGraphics->inputMouseUp(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::wheelEvent(QWheelEvent * event) { mGraphics->inputMouseWheel(event->delta()); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::keyPressEvent(QKeyEvent* event) { mGraphics->inputShiftKeyDown(event->key() == Qt::Key_Shift); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::keyReleaseEvent(QKeyEvent* event) { mGraphics->inputShiftKeyDown(false); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::resizeGL(int width, int height) { mGraphics->eventResize(static_cast<size_t>(width), static_cast<size_t>(height)); } //------------------------------------------------------------------------------ void GLWidget::closeEvent(QCloseEvent *evt) { if (mGraphics != nullptr) { mGraphics.reset(); } QGLWidget::closeEvent(evt); } //------------------------------------------------------------------------------ void GLWidget::makeCurrent() { mContext->makeCurrent(); } //------------------------------------------------------------------------------ void GLWidget::updateRenderer() { mCurrentTime += updateTime; #ifdef QT5_BUILD if (!isExposed()) return; #endif try { mGraphics->doFrame(mCurrentTime, updateTime); mContext->swapBuffers(); } catch (const SCIRun::Render::SRInterfaceFailure& e) { Q_EMIT fatalError(e.what()); mTimer->stop(); } } } // namespace Gui } // namespace SCIRun <commit_msg>No good<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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. */ /// \author James Hughes /// \date September 2012 /// \brief Not sure this file should go in Modules/Render. But it is an /// auxiliary file to the ViewScene render module. #include <Interface/Modules/Render/GLWidget.h> #include <iostream> #include <QMouseEvent> #include <QWheelEvent> #include <QTimer> #include <QtDebug> #include <Core/Application/Application.h> namespace SCIRun { namespace Gui { const int RendererUpdateInMS = 35; const double updateTime = RendererUpdateInMS / 1000.0; //------------------------------------------------------------------------------ GLWidget::GLWidget(QtGLContext* context, QWidget* parent) : QGLWidget(context, parent), mContext(new GLContext(this)), mCurrentTime(0.0) { /// \todo Implement this intelligently. This function is called everytime /// there is a new graphics context. std::vector<std::string> shaderSearchDirs; mContext->makeCurrent(); spire::glPlatformInit(); auto frameInitLimitFromCommandLine = Core::Application::Instance().parameters()->developerParameters()->frameInitLimit(); if (frameInitLimitFromCommandLine) { std::cout << "Renderer frame init limit changed to " << *frameInitLimitFromCommandLine << std::endl; } const int frameInitLimit = frameInitLimitFromCommandLine.get_value_or(100); mGraphics.reset(new Render::SRInterface(mContext, frameInitLimit)); mTimer = new QTimer(this); connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer())); mTimer->start(RendererUpdateInMS); // We must disable auto buffer swap on the 'paintEvent'. setAutoBufferSwap(false); } //------------------------------------------------------------------------------ GLWidget::~GLWidget() { // Need to inform module that the context is being destroyed. if (mGraphics != nullptr) { //std::cout << "Terminating spire." << std::endl; mGraphics.reset(); } } //------------------------------------------------------------------------------ void GLWidget::initializeGL() { } //------------------------------------------------------------------------------ SCIRun::Render::SRInterface::MouseButton GLWidget::getSpireButton(QMouseEvent* event) { auto btn = SCIRun::Render::SRInterface::MOUSE_NONE; if (event->buttons() & Qt::LeftButton) btn = Render::SRInterface::MOUSE_LEFT; else if (event->buttons() & Qt::RightButton) btn = Render::SRInterface::MOUSE_RIGHT; else if (event->buttons() & Qt::MidButton) btn = Render::SRInterface::MOUSE_MIDDLE; return btn; } //------------------------------------------------------------------------------ void GLWidget::mouseMoveEvent(QMouseEvent* event) { // Extract appropriate key. auto btn = getSpireButton(event); mGraphics->inputMouseMove(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::mousePressEvent(QMouseEvent* event) { auto btn = getSpireButton(event); mGraphics->inputMouseDown(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::mouseReleaseEvent(QMouseEvent* event) { auto btn = getSpireButton(event); mGraphics->inputMouseUp(glm::ivec2(event->x(), event->y()), btn); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::wheelEvent(QWheelEvent * event) { mGraphics->inputMouseWheel(event->delta()); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::keyPressEvent(QKeyEvent* event) { mGraphics->inputShiftKeyDown(event->key() == Qt::Key_Shift); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::keyReleaseEvent(QKeyEvent* event) { mGraphics->inputShiftKeyDown(false); event->ignore(); } //------------------------------------------------------------------------------ void GLWidget::resizeGL(int width, int height) { mGraphics->eventResize(static_cast<size_t>(width), static_cast<size_t>(height)); } //------------------------------------------------------------------------------ void GLWidget::closeEvent(QCloseEvent *evt) { if (mGraphics != nullptr) { mGraphics.reset(); } QGLWidget::closeEvent(evt); } //------------------------------------------------------------------------------ void GLWidget::makeCurrent() { mContext->makeCurrent(); } //------------------------------------------------------------------------------ void GLWidget::updateRenderer() { mCurrentTime += updateTime; #if 0 #ifdef QT5_BUILD //idea--needs QWindow wrapper if (!isExposed()) return; #endif #endif try { mGraphics->doFrame(mCurrentTime, updateTime); mContext->swapBuffers(); } catch (const SCIRun::Render::SRInterfaceFailure& e) { Q_EMIT fatalError(e.what()); mTimer->stop(); } } } // namespace Gui } // namespace SCIRun <|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 "chrome/browser/debugger/devtools_http_protocol_handler.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_number_conversions.h" #include "base/thread.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/listen_socket.h" #include "net/server/http_server_request_info.h" #include "net/url_request/url_request_context.h" const int kBufferSize = 16 * 1024; namespace { // An internal implementation of DevToolsClientHost that delegates // messages sent for DevToolsClient to a DebuggerShell instance. class DevToolsClientHostImpl : public DevToolsClientHost { public: explicit DevToolsClientHostImpl(HttpListenSocket* socket) : socket_(socket) {} ~DevToolsClientHostImpl() {} // DevToolsClientHost interface virtual void InspectedTabClosing() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket_, &HttpListenSocket::Close)); } virtual void SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void NotifyCloseListener() { DevToolsClientHost::NotifyCloseListener(); } private: // Message handling routines void OnDispatchOnInspectorFrontend(const std::string& data) { socket_->SendOverWebSocket(data); } HttpListenSocket* socket_; }; } DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() { // Stop() must be called prior to this being called DCHECK(server_.get() == NULL); } void DevToolsHttpProtocolHandler::Start() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init)); } void DevToolsHttpProtocolHandler::Stop() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown)); } void DevToolsHttpProtocolHandler::OnHttpRequest( HttpListenSocket* socket, const HttpServerRequestInfo& info) { if (info.path == "" || info.path == "/") { // Pages discovery request. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::OnHttpRequestUI, make_scoped_refptr(socket), info)); return; } size_t pos = info.path.find("/devtools/"); if (pos != 0) { socket->Send404(); return; } // Proxy static files from chrome://devtools/*. net::URLRequest* request = new net::URLRequest( GURL("chrome:/" + info.path), this); Bind(request, socket); request->set_context( Profile::GetDefaultRequestContext()->GetURLRequestContext()); request->Start(); } void DevToolsHttpProtocolHandler::OnWebSocketRequest( HttpListenSocket* socket, const HttpServerRequestInfo& request) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketRequestUI, make_scoped_refptr(socket), request)); } void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket, const std::string& data) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketMessageUI, make_scoped_refptr(socket), data)); } void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) { SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it != socket_to_requests_io_.end()) { // Dispose delegating socket. for (std::set<net::URLRequest*>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { net::URLRequest* request = *it2; request->Cancel(); request_to_socket_io_.erase(request); request_to_buffer_io_.erase(request); delete request; } socket_to_requests_io_.erase(socket); } // This can't use make_scoped_refptr because |socket| is already deleted // when this runs -- http://crbug.com/59930 BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnCloseUI, socket)); } void DevToolsHttpProtocolHandler::OnHttpRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& info) { std::string response = "<html><body>"; for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { TabContentsWrapper* tab_contents = model->GetTabContentsAt(i); NavigationController& controller = tab_contents->controller(); NavigationEntry* entry = controller.GetActiveEntry(); if (entry == NULL) continue; if (!entry->url().is_valid()) continue; DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(tab_contents->tab_contents()-> render_view_host()); if (!client_host) { response += StringPrintf( "<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>", controller.session_id().id(), UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } else { response += StringPrintf( "%s (%s)<br>", UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } } } response += "</body></html>"; Send200(socket, response, "text/html; charset=UTF-8"); } void DevToolsHttpProtocolHandler::OnWebSocketRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& request) { std::string prefix = "/devtools/page/"; size_t pos = request.path.find(prefix); if (pos != 0) { Send404(socket); return; } std::string page_id = request.path.substr(prefix.length()); int id = 0; if (!base::StringToInt(page_id, &id)) { Send500(socket, "Invalid page id: " + page_id); return; } TabContents* tab_contents = GetTabContents(id); if (tab_contents == NULL) { Send500(socket, "No such page id: " + page_id); return; } DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) { Send500(socket, "Page with given id is being inspected: " + page_id); return; } DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket); socket_to_client_host_ui_[socket] = client_host; manager->RegisterDevToolsClientHostFor( tab_contents->render_view_host(), client_host); AcceptWebSocket(socket, request); } void DevToolsHttpProtocolHandler::OnWebSocketMessageUI( HttpListenSocket* socket, const std::string& data) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsManager* manager = DevToolsManager::GetInstance(); if (data == "loaded") { manager->ForwardToDevToolsAgent( it->second, DevToolsAgentMsg_FrontendLoaded()); return; } manager->ForwardToDevToolsAgent( it->second, DevToolsAgentMsg_DispatchOnInspectorBackend(data)); } void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsClientHostImpl* client_host = static_cast<DevToolsClientHostImpl*>(it->second); client_host->NotifyCloseListener(); delete client_host; socket_to_client_host_ui_.erase(socket); } void DevToolsHttpProtocolHandler::OnResponseStarted(net::URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; int expected_size = static_cast<int>(request->GetExpectedContentSize()); std::string content_type; request->GetMimeType(&content_type); if (request->status().is_success()) { socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n" "Content-Type:%s\r\n" "Content-Length:%d\r\n" "\r\n", content_type.c_str(), expected_size)); } else { socket->Send404(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). net::IOBuffer* buffer = request_to_buffer_io_[request].get(); if (request->status().is_success()) request->Read(buffer, kBufferSize, &bytes_read); OnReadCompleted(request, bytes_read); } void DevToolsHttpProtocolHandler::OnReadCompleted(net::URLRequest* request, int bytes_read) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; net::IOBuffer* buffer = request_to_buffer_io_[request].get(); do { if (!request->status().is_success() || bytes_read <= 0) break; socket->Send(buffer->data(), bytes_read); } while (request->Read(buffer, kBufferSize, &bytes_read)); // See comments re: HEAD requests in OnResponseStarted(). if (!request->status().is_io_pending()) RequestCompleted(request); } DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port) : port_(port), server_(NULL) { } void DevToolsHttpProtocolHandler::Init() { server_ = HttpListenSocket::Listen("127.0.0.1", port_, this); } // Run on I/O thread void DevToolsHttpProtocolHandler::Teardown() { server_ = NULL; } void DevToolsHttpProtocolHandler::Bind(net::URLRequest* request, HttpListenSocket* socket) { request_to_socket_io_[request] = socket; SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it == socket_to_requests_io_.end()) { std::pair<HttpListenSocket*, std::set<net::URLRequest*> > value( socket, std::set<net::URLRequest*>()); it = socket_to_requests_io_.insert(value).first; } it->second.insert(request); request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize); } void DevToolsHttpProtocolHandler::RequestCompleted(net::URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; request_to_socket_io_.erase(request); SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket); it2->second.erase(request); request_to_buffer_io_.erase(request); delete request; } void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket, const std::string& data, const std::string& mime_type) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send200, data, mime_type)); } void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send404)); } void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket, const std::string& message) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send500, message)); } void DevToolsHttpProtocolHandler::AcceptWebSocket( HttpListenSocket* socket, const HttpServerRequestInfo& request) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::AcceptWebSocket, request)); } TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) { for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { NavigationController& controller = model->GetTabContentsAt(i)->controller(); if (controller.session_id().id() == session_id) return controller.tab_contents(); } } return NULL; } <commit_msg>Use make_scoped_refptr for RefCounted parameter to NewRunnableMethod().<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 "chrome/browser/debugger/devtools_http_protocol_handler.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_number_conversions.h" #include "base/thread.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/listen_socket.h" #include "net/server/http_server_request_info.h" #include "net/url_request/url_request_context.h" const int kBufferSize = 16 * 1024; namespace { // An internal implementation of DevToolsClientHost that delegates // messages sent for DevToolsClient to a DebuggerShell instance. class DevToolsClientHostImpl : public DevToolsClientHost { public: explicit DevToolsClientHostImpl(HttpListenSocket* socket) : socket_(socket) {} ~DevToolsClientHostImpl() {} // DevToolsClientHost interface virtual void InspectedTabClosing() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket_, &HttpListenSocket::Close)); } virtual void SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void NotifyCloseListener() { DevToolsClientHost::NotifyCloseListener(); } private: // Message handling routines void OnDispatchOnInspectorFrontend(const std::string& data) { socket_->SendOverWebSocket(data); } HttpListenSocket* socket_; }; } DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() { // Stop() must be called prior to this being called DCHECK(server_.get() == NULL); } void DevToolsHttpProtocolHandler::Start() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init)); } void DevToolsHttpProtocolHandler::Stop() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown)); } void DevToolsHttpProtocolHandler::OnHttpRequest( HttpListenSocket* socket, const HttpServerRequestInfo& info) { if (info.path == "" || info.path == "/") { // Pages discovery request. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::OnHttpRequestUI, make_scoped_refptr(socket), info)); return; } size_t pos = info.path.find("/devtools/"); if (pos != 0) { socket->Send404(); return; } // Proxy static files from chrome://devtools/*. net::URLRequest* request = new net::URLRequest( GURL("chrome:/" + info.path), this); Bind(request, socket); request->set_context( Profile::GetDefaultRequestContext()->GetURLRequestContext()); request->Start(); } void DevToolsHttpProtocolHandler::OnWebSocketRequest( HttpListenSocket* socket, const HttpServerRequestInfo& request) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketRequestUI, make_scoped_refptr(socket), request)); } void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket, const std::string& data) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketMessageUI, make_scoped_refptr(socket), data)); } void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) { SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it != socket_to_requests_io_.end()) { // Dispose delegating socket. for (std::set<net::URLRequest*>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { net::URLRequest* request = *it2; request->Cancel(); request_to_socket_io_.erase(request); request_to_buffer_io_.erase(request); delete request; } socket_to_requests_io_.erase(socket); } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnCloseUI, make_scoped_refptr(socket))); } void DevToolsHttpProtocolHandler::OnHttpRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& info) { std::string response = "<html><body>"; for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { TabContentsWrapper* tab_contents = model->GetTabContentsAt(i); NavigationController& controller = tab_contents->controller(); NavigationEntry* entry = controller.GetActiveEntry(); if (entry == NULL) continue; if (!entry->url().is_valid()) continue; DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(tab_contents->tab_contents()-> render_view_host()); if (!client_host) { response += StringPrintf( "<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>", controller.session_id().id(), UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } else { response += StringPrintf( "%s (%s)<br>", UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } } } response += "</body></html>"; Send200(socket, response, "text/html; charset=UTF-8"); } void DevToolsHttpProtocolHandler::OnWebSocketRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& request) { std::string prefix = "/devtools/page/"; size_t pos = request.path.find(prefix); if (pos != 0) { Send404(socket); return; } std::string page_id = request.path.substr(prefix.length()); int id = 0; if (!base::StringToInt(page_id, &id)) { Send500(socket, "Invalid page id: " + page_id); return; } TabContents* tab_contents = GetTabContents(id); if (tab_contents == NULL) { Send500(socket, "No such page id: " + page_id); return; } DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) { Send500(socket, "Page with given id is being inspected: " + page_id); return; } DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket); socket_to_client_host_ui_[socket] = client_host; manager->RegisterDevToolsClientHostFor( tab_contents->render_view_host(), client_host); AcceptWebSocket(socket, request); } void DevToolsHttpProtocolHandler::OnWebSocketMessageUI( HttpListenSocket* socket, const std::string& data) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsManager* manager = DevToolsManager::GetInstance(); if (data == "loaded") { manager->ForwardToDevToolsAgent( it->second, DevToolsAgentMsg_FrontendLoaded()); return; } manager->ForwardToDevToolsAgent( it->second, DevToolsAgentMsg_DispatchOnInspectorBackend(data)); } void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsClientHostImpl* client_host = static_cast<DevToolsClientHostImpl*>(it->second); client_host->NotifyCloseListener(); delete client_host; socket_to_client_host_ui_.erase(socket); } void DevToolsHttpProtocolHandler::OnResponseStarted(net::URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; int expected_size = static_cast<int>(request->GetExpectedContentSize()); std::string content_type; request->GetMimeType(&content_type); if (request->status().is_success()) { socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n" "Content-Type:%s\r\n" "Content-Length:%d\r\n" "\r\n", content_type.c_str(), expected_size)); } else { socket->Send404(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). net::IOBuffer* buffer = request_to_buffer_io_[request].get(); if (request->status().is_success()) request->Read(buffer, kBufferSize, &bytes_read); OnReadCompleted(request, bytes_read); } void DevToolsHttpProtocolHandler::OnReadCompleted(net::URLRequest* request, int bytes_read) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; net::IOBuffer* buffer = request_to_buffer_io_[request].get(); do { if (!request->status().is_success() || bytes_read <= 0) break; socket->Send(buffer->data(), bytes_read); } while (request->Read(buffer, kBufferSize, &bytes_read)); // See comments re: HEAD requests in OnResponseStarted(). if (!request->status().is_io_pending()) RequestCompleted(request); } DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port) : port_(port), server_(NULL) { } void DevToolsHttpProtocolHandler::Init() { server_ = HttpListenSocket::Listen("127.0.0.1", port_, this); } // Run on I/O thread void DevToolsHttpProtocolHandler::Teardown() { server_ = NULL; } void DevToolsHttpProtocolHandler::Bind(net::URLRequest* request, HttpListenSocket* socket) { request_to_socket_io_[request] = socket; SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it == socket_to_requests_io_.end()) { std::pair<HttpListenSocket*, std::set<net::URLRequest*> > value( socket, std::set<net::URLRequest*>()); it = socket_to_requests_io_.insert(value).first; } it->second.insert(request); request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize); } void DevToolsHttpProtocolHandler::RequestCompleted(net::URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; request_to_socket_io_.erase(request); SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket); it2->second.erase(request); request_to_buffer_io_.erase(request); delete request; } void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket, const std::string& data, const std::string& mime_type) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send200, data, mime_type)); } void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send404)); } void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket, const std::string& message) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send500, message)); } void DevToolsHttpProtocolHandler::AcceptWebSocket( HttpListenSocket* socket, const HttpServerRequestInfo& request) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::AcceptWebSocket, request)); } TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) { for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { NavigationController& controller = model->GetTabContentsAt(i)->controller(); if (controller.session_id().id() == session_id) return controller.tab_contents(); } } return NULL; } <|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 "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <commit_msg>Added check when unpacking extensions for a null key.<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 "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } if (header.key_size == 0) { ReportFailure("Key length is zero"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <|endoftext|>
<commit_before>#include <vw/Plate/ToastDem.h> #include <vw/Plate/PlateManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Core.h> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> using namespace std; using namespace vw; using namespace vw::platefile; // There isn't much abstraction here. A Filter takes a platefile and writes a // new platefile. This rules out lazy filters for the moment. The // col/row/level/transaction_id is for the input value, the output can feel // free to write things elsewhere. // The function will be called for every input tile, including all transaction // ids. The output function should feel no obligation to write a tile for every // input. template <typename ImplT> struct FilterBase { inline ImplT& impl() { return static_cast<ImplT&>(*this); } inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().init(output, input, transaction_id); } inline void fini(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().fini(output, input, transaction_id); } # define lookup(name, type) type name(type data) const { return impl().name(data); } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { impl()(output, input, col, row, level, transaction_id); } }; struct Identity : public FilterBase<Identity> { # define lookup(name, type) type name(type data) const { return data; } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { ImageView<PixelRGBA<double> > tile; TileHeader hdr = input.read(tile, col, row, level, transaction_id); output.write_update(tile, col, row, level, transaction_id); } }; struct ToastDem : public FilterBase<ToastDem> { string mode(string) const { return "toast_dem"; } int tile_size(int) const { return 32; } string filetype(string) const { return "toast_dem_v1"; } PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; } ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { output.write_request(); // Write null tiles for the levels we don't have data for int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5; vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl; uint64 bytes; boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes); for (int level = 0; level < level_difference; ++level) { int region_size = 1 << level; for (int col = 0; col < region_size; ++col) for (int row = 0; row < region_size; ++row) output.write_update(null_tile, bytes, col, row, level, transaction_id); } } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } struct DemWriter : public ToastDemWriter { PlateFile& platefile; DemWriter(PlateFile& output) : platefile(output) { } inline void operator()(const boost::shared_array<uint8> data, uint64 data_size, int32 dem_col, int32 dem_row, int32 dem_level, int32 transaction_id) const { platefile.write_update(data, data_size, dem_col, dem_row, dem_level, transaction_id); } }; inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { DemWriter writer(output); make_toast_dem_tile(writer, input, col, row, level, transaction_id); } }; struct Options { string input_name; string output_name; string mode; string description; int tile_size; string filetype; PixelFormatEnum pixel_format; ChannelTypeEnum channel_type; string filter; Options() : tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {} }; VW_DEFINE_EXCEPTION(Usage, Exception); void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description options("Options"); options.add_options() ("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.") ("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.") ("file-type", po::value(&opt.filetype), "Output file type") ("mode", po::value(&opt.mode), "Output mode [toast, kml]") ("tile-size", po::value(&opt.tile_size), "Output size, in pixels") ("filter", po::value(&opt.filter), "Filters to run") ("help,h", "Display this help message."); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(options).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options ); } if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty()) vw_throw(Usage() << options); } template <typename FilterT> void run(Options& opt, FilterBase<FilterT>& filter) { PlateFile input(opt.input_name); // Use given option first, then use filter recommendation (it will probably // just recommend the value from the input platefile) if (opt.mode.empty()) opt.mode = filter.mode(input.index_header().type()); if (opt.tile_size == 0) opt.tile_size = filter.tile_size(input.default_tile_size()); if (opt.filetype.empty()) opt.filetype = filter.filetype(input.default_file_type()); if (opt.pixel_format == VW_PIXEL_UNKNOWN) opt.pixel_format = filter.pixel_format(input.pixel_format()); if (opt.channel_type == VW_CHANNEL_UNKNOWN) opt.channel_type = filter.channel_type(input.channel_type()); PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type); int transaction_id = output.transaction_request("plate2plate, reporting for duty", -1); filter.init(output, input, transaction_id); for (int level = 0; level < input.num_levels(); ++level) { std::cout << "Processing level " << level << " of " << input.num_levels()-1 << std::endl; // The entire region contains 2^level tiles. int region_size = 1 << level; int subdivided_region_size = region_size / 16; if (subdivided_region_size < 1024) subdivided_region_size = 1024; BBox2i full_region(0,0,region_size,region_size); std::list<BBox2i> boxes1 = bbox_tiles(full_region, subdivided_region_size, subdivided_region_size); BOOST_FOREACH( const BBox2i& region1, boxes1 ) { std::list<TileHeader> tiles = input.search_by_region(level, region1, 0, std::numeric_limits<int>::max(), 1); BOOST_FOREACH( const TileHeader& tile, tiles ) { filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); } } output.sync(); } filter.fini(output, input, transaction_id); output.transaction_complete(transaction_id, true); } // Blah blah boilerplate int main(int argc, char *argv[]) { Options opt; try { handle_arguments(argc, argv, opt); boost::to_lower(opt.filter); if (opt.filter == "identity") { Identity f; run(opt, f); } else if (opt.filter == "toast_dem") { ToastDem f; run(opt, f); } } catch (const Usage& e) { std::cout << e.what() << std::endl; return 1; } catch (const Exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } <commit_msg>speed up plate2plate a bit (and add progress bars)<commit_after>#include <vw/Plate/ToastDem.h> #include <vw/Plate/PlateManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Core.h> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> using namespace std; using namespace vw; using namespace vw::platefile; // There isn't much abstraction here. A Filter takes a platefile and writes a // new platefile. This rules out lazy filters for the moment. The // col/row/level/transaction_id is for the input value, the output can feel // free to write things elsewhere. // The function will be called for every input tile, including all transaction // ids. The output function should feel no obligation to write a tile for every // input. template <typename ImplT> struct FilterBase { inline ImplT& impl() { return static_cast<ImplT&>(*this); } inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().init(output, input, transaction_id); } inline void fini(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().fini(output, input, transaction_id); } # define lookup(name, type) type name(type data) const { return impl().name(data); } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { impl()(output, input, col, row, level, transaction_id); } }; struct Identity : public FilterBase<Identity> { # define lookup(name, type) type name(type data) const { return data; } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { ImageView<PixelRGBA<double> > tile; TileHeader hdr = input.read(tile, col, row, level, transaction_id); output.write_update(tile, col, row, level, transaction_id); } }; struct ToastDem : public FilterBase<ToastDem> { string mode(string) const { return "toast_dem"; } int tile_size(int) const { return 32; } string filetype(string) const { return "toast_dem_v1"; } PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; } ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { output.write_request(); // Write null tiles for the levels we don't have data for int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5; vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl; uint64 bytes; boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes); for (int level = 0; level < level_difference; ++level) { int region_size = 1 << level; for (int col = 0; col < region_size; ++col) for (int row = 0; row < region_size; ++row) output.write_update(null_tile, bytes, col, row, level, transaction_id); } } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } struct DemWriter : public ToastDemWriter { PlateFile& platefile; DemWriter(PlateFile& output) : platefile(output) { } inline void operator()(const boost::shared_array<uint8> data, uint64 data_size, int32 dem_col, int32 dem_row, int32 dem_level, int32 transaction_id) const { platefile.write_update(data, data_size, dem_col, dem_row, dem_level, transaction_id); } }; inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { DemWriter writer(output); make_toast_dem_tile(writer, input, col, row, level, transaction_id); } }; struct Options { string input_name; string output_name; string mode; string description; int tile_size; string filetype; PixelFormatEnum pixel_format; ChannelTypeEnum channel_type; string filter; Options() : tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {} }; VW_DEFINE_EXCEPTION(Usage, Exception); void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description options("Options"); options.add_options() ("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.") ("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.") ("file-type", po::value(&opt.filetype), "Output file type") ("mode", po::value(&opt.mode), "Output mode [toast, kml]") ("tile-size", po::value(&opt.tile_size), "Output size, in pixels") ("filter", po::value(&opt.filter), "Filters to run") ("help,h", "Display this help message."); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(options).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options ); } if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty()) vw_throw(Usage() << options); } template <typename FilterT> void run(Options& opt, FilterBase<FilterT>& filter) { PlateFile input(opt.input_name); // Use given option first, then use filter recommendation (it will probably // just recommend the value from the input platefile) if (opt.mode.empty()) opt.mode = filter.mode(input.index_header().type()); if (opt.tile_size == 0) opt.tile_size = filter.tile_size(input.default_tile_size()); if (opt.filetype.empty()) opt.filetype = filter.filetype(input.default_file_type()); if (opt.pixel_format == VW_PIXEL_UNKNOWN) opt.pixel_format = filter.pixel_format(input.pixel_format()); if (opt.channel_type == VW_CHANNEL_UNKNOWN) opt.channel_type = filter.channel_type(input.channel_type()); PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type); int transaction_id = output.transaction_request("plate2plate, reporting for duty", -1); filter.init(output, input, transaction_id); VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels"); for (int level = 0; level < input.num_levels(); ++level) { vw_out(InfoMessage) << "Processing level " << level << " of " << input.num_levels()-1 << std::endl; TerminalProgressCallback tpc("plate.plate2plate.progress", ""); vw::Timer::Timer( "Processed in" ); // The entire region contains 2^level tiles. int32 region_size = 1 << level; double step = 1./(region_size*region_size); tpc.print_progress(); for (int32 i = 0; i < region_size; ++i) { for (int32 j = 0; j < region_size; ++j) { std::list<TileHeader> tiles; try { tiles = input.search_by_location(i, j, level, 0, std::numeric_limits<int>::max()); } catch (const TileNotFoundErr&) { continue; } BOOST_FOREACH(const TileHeader& tile, tiles) filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); tpc.report_incremental_progress(step); } } tpc.report_finished(); output.sync(); } filter.fini(output, input, transaction_id); output.transaction_complete(transaction_id, true); } // Blah blah boilerplate int main(int argc, char *argv[]) { Options opt; try { handle_arguments(argc, argv, opt); boost::to_lower(opt.filter); if (opt.filter == "identity") { Identity f; run(opt, f); } else if (opt.filter == "toast_dem") { ToastDem f; run(opt, f); } } catch (const Usage& e) { std::cout << e.what() << std::endl; return 1; } catch (const Exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } <|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 <gtk/gtk.h> #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/view_id_util.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; const wchar_t kSimplePage[] = L"404_is_enough_for_us.html"; void OnClicked(GtkWidget* widget, bool* clicked_bit) { *clicked_bit = true; } } // namespace class BookmarkBarGtkBrowserTest : public InProcessBrowserTest { }; // Makes sure that when you switch back to an NTP with an active findbar, // the findbar is above the floating bookmark bar. IN_PROC_BROWSER_TEST_F(BookmarkBarGtkBrowserTest, FindBarTest) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); // Create new tab; open findbar. browser()->NewTab(); browser()->Find(); // Create new tab with an arbitrary URL. GURL url = server->TestServerPageW(kSimplePage); browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, -1, false, NULL); // Switch back to the NTP with the active findbar. browser()->SelectTabContentsAt(1, false); // Wait for the findbar to show. MessageLoop::current()->RunAllPending(); // Set focus somewhere else, so that we can test clicking on the findbar // works. browser()->FocusLocationBar(); ui_test_utils::ClickOnView(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD); ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD); } // Makes sure that you can click on the floating bookmark bar. IN_PROC_BROWSER_TEST_F(BookmarkBarGtkBrowserTest, ClickOnFloatingTest) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); GtkWidget* other_bookmarks = ViewIDUtil::GetWidget(GTK_WIDGET(browser()->window()->GetNativeHandle()), VIEW_ID_OTHER_BOOKMARKS); bool has_been_clicked = false; g_signal_connect(other_bookmarks, "clicked", G_CALLBACK(OnClicked), &has_been_clicked); // Create new tab. browser()->NewTab(); // Wait for the floating bar to appear. MessageLoop::current()->RunAllPending(); // This is kind of a hack. Calling this just once doesn't seem to send a click // event, but doing it twice works. // http://crbug.com/35581 ui_test_utils::ClickOnView(browser(), VIEW_ID_OTHER_BOOKMARKS); ui_test_utils::ClickOnView(browser(), VIEW_ID_OTHER_BOOKMARKS); EXPECT_TRUE(has_been_clicked); } <commit_msg>Disable broken test: BookmarkBarGtkBrowserTest.ClickOnFloatingTest<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 <gtk/gtk.h> #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/view_id_util.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; const wchar_t kSimplePage[] = L"404_is_enough_for_us.html"; void OnClicked(GtkWidget* widget, bool* clicked_bit) { *clicked_bit = true; } } // namespace class BookmarkBarGtkBrowserTest : public InProcessBrowserTest { }; // Makes sure that when you switch back to an NTP with an active findbar, // the findbar is above the floating bookmark bar. IN_PROC_BROWSER_TEST_F(BookmarkBarGtkBrowserTest, FindBarTest) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); // Create new tab; open findbar. browser()->NewTab(); browser()->Find(); // Create new tab with an arbitrary URL. GURL url = server->TestServerPageW(kSimplePage); browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, -1, false, NULL); // Switch back to the NTP with the active findbar. browser()->SelectTabContentsAt(1, false); // Wait for the findbar to show. MessageLoop::current()->RunAllPending(); // Set focus somewhere else, so that we can test clicking on the findbar // works. browser()->FocusLocationBar(); ui_test_utils::ClickOnView(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD); ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD); } // Makes sure that you can click on the floating bookmark bar. IN_PROC_BROWSER_TEST_F(BookmarkBarGtkBrowserTest, DISABLED_ClickOnFloatingTest) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); GtkWidget* other_bookmarks = ViewIDUtil::GetWidget(GTK_WIDGET(browser()->window()->GetNativeHandle()), VIEW_ID_OTHER_BOOKMARKS); bool has_been_clicked = false; g_signal_connect(other_bookmarks, "clicked", G_CALLBACK(OnClicked), &has_been_clicked); // Create new tab. browser()->NewTab(); // Wait for the floating bar to appear. MessageLoop::current()->RunAllPending(); // This is kind of a hack. Calling this just once doesn't seem to send a click // event, but doing it twice works. // http://crbug.com/35581 ui_test_utils::ClickOnView(browser(), VIEW_ID_OTHER_BOOKMARKS); ui_test_utils::ClickOnView(browser(), VIEW_ID_OTHER_BOOKMARKS); EXPECT_TRUE(has_been_clicked); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtWeb module of the Qt eXTension library ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of th Common Public License, version 1.0, as published by ** IBM. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL along with this file. ** See the LICENSE file and the cpl1.0.txt file included with the source ** distribution for more information. If you did not receive a copy of the ** license, contact the Qxt Foundation. ** ** <http://libqxt.org> <[email protected]> ** ****************************************************************************/ /*! \class QxtHtmlTemplate QxtHtmlTemplate \ingroup web \brief Basic Html Template Engine open a file containing html code and php style variables. use the square bracket operators to assign content for a variable \code QxtHtmlTemplate index; if(!index.open) return 404; index["content"]="hello world"; echo()<<index.render(); \endcode the realatet html code would look like: \code <html> <head> <title>Test Page</title> </head> <?=content?> </html> \endcode */ /*! \fn QxtHtmlTemplate::open(const QString& filename) Returns true on sucess and false on failure. note that it will also return false for an empty html file. \fn QString QxtHtmlTemplate::render() const Uses the variables you set and renders the opened file. returns an empty string on failure. Does NOT take care of not assigned variables, they will remain in the returned string */ #include "qxthtmltemplate.h" #include <QFile> #include <QStringList> QxtHtmlTemplate::QxtHtmlTemplate() : QMap<QString,QString>() {} void QxtHtmlTemplate::load(const QString& d) { data=d; } bool QxtHtmlTemplate::open(const QString& filename) { QFile f(filename); f.open(QIODevice::ReadOnly); data = QString::fromLocal8Bit(f.readAll()); f.close(); if (data.isEmpty()) { qWarning("QxtHtmlTemplate::open(\"%s\") empty or non existant",qPrintable(filename)); return false; } return true; } QString QxtHtmlTemplate::render() const { ///try to preserve indention by parsing char by char and saving the last non-space character QString output = data; int lastnewline=0; for (int i=0;i<output.count();i++) { if (output.at(i)=='\n') { lastnewline=i; } if (output.at(i)=='<' && output.at(i+1)=='?' && output.at(i+2)=='=') { int j=i+3; QString var; for (int jj=j;jj<output.count();jj++) { if (output.at(jj)=='?' && output.at(jj+1)=='>') { j=jj; break; } var+=output.at(jj); } if (j==i) { qWarning("QxtHtmlTemplate::render() unterminated <?= "); continue; } if(!contains(var)) { qWarning("QxtHtmlTemplate::render() unused variable \"%s\"",qPrintable(var)); continue; } output.replace(i,j-i+2,QString(value(var)).replace("\n","\n"+QString(i-lastnewline-1,QChar(' ')))); } } return output; } <commit_msg>warning about recursion<commit_after>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtWeb module of the Qt eXTension library ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of th Common Public License, version 1.0, as published by ** IBM. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL along with this file. ** See the LICENSE file and the cpl1.0.txt file included with the source ** distribution for more information. If you did not receive a copy of the ** license, contact the Qxt Foundation. ** ** <http://libqxt.org> <[email protected]> ** ****************************************************************************/ /*! \class QxtHtmlTemplate QxtHtmlTemplate \ingroup web \brief Basic Html Template Engine open a file containing html code and php style variables. use the square bracket operators to assign content for a variable \code QxtHtmlTemplate index; if(!index.open) return 404; index["content"]="hello world"; echo()<<index.render(); \endcode the realatet html code would look like: \code <html> <head> <title>Test Page</title> </head> <?=content?> </html> \endcode funny storry: whe are using this class to make our documentation (eat your own dogfood, you know ;). but when we where parsing exactly this file you read right now the first time, QxtHtmlTemplate got stuck in an infinite loop. guess why. becouse of that example above :D So be warned: when you assign content to a variable that contains the variable name itself, render() will never return. */ /*! \fn QxtHtmlTemplate::open(const QString& filename) Returns true on sucess and false on failure. note that it will also return false for an empty html file. \fn QString QxtHtmlTemplate::render() const Uses the variables you set and renders the opened file. returns an empty string on failure. Does NOT take care of not assigned variables, they will remain in the returned string */ #include "qxthtmltemplate.h" #include <QFile> #include <QStringList> QxtHtmlTemplate::QxtHtmlTemplate() : QMap<QString,QString>() {} void QxtHtmlTemplate::load(const QString& d) { data=d; } bool QxtHtmlTemplate::open(const QString& filename) { QFile f(filename); f.open(QIODevice::ReadOnly); data = QString::fromLocal8Bit(f.readAll()); f.close(); if (data.isEmpty()) { qWarning("QxtHtmlTemplate::open(\"%s\") empty or non existant",qPrintable(filename)); return false; } return true; } QString QxtHtmlTemplate::render() const { ///try to preserve indention by parsing char by char and saving the last non-space character QString output = data; int lastnewline=0; for (int i=0;i<output.count();i++) { if (output.at(i)=='\n') { lastnewline=i; } if (output.at(i)=='<' && output.at(i+1)=='?' && output.at(i+2)=='=') { int j=i+3; QString var; for (int jj=j;jj<output.count();jj++) { if (output.at(jj)=='?' && output.at(jj+1)=='>') { j=jj; break; } var+=output.at(jj); } if (j==i) { qWarning("QxtHtmlTemplate::render() unterminated <?= "); continue; } if(!contains(var)) { qWarning("QxtHtmlTemplate::render() unused variable \"%s\"",qPrintable(var)); continue; } output.replace(i,j-i+2,QString(value(var)).replace("\n","\n"+QString(i-lastnewline-1,QChar(' ')))); } } return output; } <|endoftext|>
<commit_before><commit_msg>[Sketcher] Solver message updated when toggling driving in datum dialog<commit_after><|endoftext|>
<commit_before>#pragma once #include "TextureAtlas.hpp" #include <vector> #include <string> #include <memory> #include "ft2build.h" #include FT_FREETYPE_H #include "vec.hpp" namespace rffalcon { struct GlyphKerning { wchar_t charCode; float kerning; }; struct TextureGlyph { wchar_t charCode; int outlineType; float outlineThickness; int width; int height; int offsetX; int offsetY; float s0; float t0; float s1; float t1; float advanceX; float advanceY; std::vector<GlyphKerning> kerning; float getKerning(char kerningCharCode) { int result = 0; for (int index = 0; index < kerning.size(); ++index) { GlyphKerning k = kerning[index]; if (k.charCode == kerningCharCode) { result = k.kerning; } } return result; } }; class TextureFont { public: TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename); ~TextureFont(); float getHeight() const; int loadGlyphs(const std::wstring &text); std::shared_ptr<TextureGlyph> getGlyph(const wchar_t charCode); private: void _initialize(); void _loadFace(FT_Library *library, FT_Face *face); void _loadFace(FT_Library *library, FT_Face *face, float pointSize); bool _shouldLoadGlyph(const wchar_t charCode); FT_Int32 _getFlags(); void _setFiltering(FT_Library library); GlyphData _getGlyphData(FT_Library library, FT_Face face); void _addTextureGlyph(wchar_t charCode, GlyphData glyphData, s1::ivec4 region, FT_Face face, FT_UInt glyphIndex); s1::ivec4 _renderToAtlas(GlyphData glyphData, const wchar_t charCode, FT_Face face, FT_UInt glyphIndex); void _generateKerning(); std::shared_ptr<TextureGlyph> _tryGetGlyph(const wchar_t charCode); std::shared_ptr<TextureAtlas> _atlas; float _pointSize; std::vector<std::shared_ptr<TextureGlyph>> _glyphs; float _height = 0; float _ascender = 0; float _descender = 0; float _linegap = 0; int _outlineType = 0; float _outlineThickness = 0.0; std::string _filename; bool _hinting = true; bool _filtering = true; unsigned char _lcdWeights[5]; }; }<commit_msg>Fix to getKerning API, takes wchar_t and returns float, not char and int.<commit_after>#pragma once #include "TextureAtlas.hpp" #include <vector> #include <string> #include <memory> #include "ft2build.h" #include FT_FREETYPE_H #include "vec.hpp" namespace rffalcon { struct GlyphKerning { wchar_t charCode; float kerning; }; struct TextureGlyph { wchar_t charCode; int outlineType; float outlineThickness; int width; int height; int offsetX; int offsetY; float s0; float t0; float s1; float t1; float advanceX; float advanceY; std::vector<GlyphKerning> kerning; float getKerning(wchar_t kerningCharCode) { float result = 0.0f; for (int index = 0; index < static_cast<int>(kerning.size()); ++index) { GlyphKerning k = kerning[index]; if (k.charCode == kerningCharCode) { result = k.kerning; } } return result; } }; class TextureFont { public: TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename); ~TextureFont(); float getHeight() const; int loadGlyphs(const std::wstring &text); std::shared_ptr<TextureGlyph> getGlyph(const wchar_t charCode); private: void _initialize(); void _loadFace(FT_Library *library, FT_Face *face); void _loadFace(FT_Library *library, FT_Face *face, float pointSize); bool _shouldLoadGlyph(const wchar_t charCode); FT_Int32 _getFlags(); void _setFiltering(FT_Library library); GlyphData _getGlyphData(FT_Library library, FT_Face face); void _addTextureGlyph(wchar_t charCode, GlyphData glyphData, s1::ivec4 region, FT_Face face, FT_UInt glyphIndex); s1::ivec4 _renderToAtlas(GlyphData glyphData, const wchar_t charCode, FT_Face face, FT_UInt glyphIndex); void _generateKerning(); std::shared_ptr<TextureGlyph> _tryGetGlyph(const wchar_t charCode); std::shared_ptr<TextureAtlas> _atlas; float _pointSize; std::vector<std::shared_ptr<TextureGlyph>> _glyphs; float _height = 0; float _ascender = 0; float _descender = 0; float _linegap = 0; int _outlineType = 0; float _outlineThickness = 0.0; std::string _filename; bool _hinting = true; bool _filtering = true; unsigned char _lcdWeights[5]; }; }<|endoftext|>
<commit_before>/// HEADER #include <csapex/msg/input.h> /// COMPONENT #include <csapex/msg/output.h> #include <csapex/command/delete_connection.h> #include <csapex/command/command.h> #include <csapex/utility/assert.h> /// SYSTEM #include <iostream> using namespace csapex; Input::Input(Settings& settings, const UUID &uuid) : Connectable(settings, uuid), target(NULL), buffer_(new Buffer), optional_(false) { QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection); } Input::Input(Settings &settings, Unique* parent, int sub_id) : Connectable(settings, parent, sub_id, TYPE_IN), target(NULL), buffer_(new Buffer), optional_(false) { QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection); } Input::~Input() { if(target != NULL) { target->removeConnection(this); } free(); } void Input::reset() { free(); setSequenceNumber(0); } bool Input::tryConnect(Connectable* other_side) { if(!other_side->canOutput()) { std::cerr << "cannot connect, other side can't output" << std::endl; return false; } return other_side->tryConnect(this); } bool Input::acknowledgeConnection(Connectable* other_side) { target = dynamic_cast<Output*>(other_side); connect(other_side, SIGNAL(destroyed(QObject*)), this, SLOT(removeConnection(QObject*))); connect(other_side, SIGNAL(enabled(bool)), this, SIGNAL(connectionEnabled(bool))); return true; } void Input::removeConnection(Connectable* other_side) { if(target != NULL) { apex_assert_hard(other_side == target); target = NULL; Q_EMIT connectionRemoved(this); } } Command::Ptr Input::removeAllConnectionsCmd() { Command::Ptr cmd(new command::DeleteConnection(target, this)); return cmd; } void Input::setOptional(bool optional) { optional_ = optional; } bool Input::isOptional() const { return optional_; } bool Input::hasMessage() const { return isConnected() && buffer_->isFilled() && !buffer_->isType<connection_types::NoMessage>(); } void Input::stop() { buffer_->disable(); Connectable::stop(); } void Input::free() { buffer_->free(); setBlocked(false); } void Input::enable() { Connectable::enable(); // if(isConnected() && !getSource()->isEnabled()) { // getSource()->enable(); // } } void Input::disable() { Connectable::disable(); // if(isBlocked()) { free(); notifyMessageProcessed(); // } // if(isConnected() && getSource()->isEnabled()) { // getSource()->disable(); // } } void Input::removeAllConnectionsNotUndoable() { if(target != NULL) { target->removeConnection(this); target = NULL; setError(false); Q_EMIT disconnected(this); } } bool Input::canConnectTo(Connectable* other_side, bool move) const { return Connectable::canConnectTo(other_side, move) && (move || !isConnected()); } bool Input::targetsCanBeMovedTo(Connectable* other_side) const { return target->canConnectTo(other_side, true) /*&& canConnectTo(getConnected())*/; } bool Input::isConnected() const { return target != NULL; } void Input::connectionMovePreview(Connectable *other_side) { Q_EMIT(connectionInProgress(getSource(), other_side)); } void Input::validateConnections() { bool e = false; if(isConnected()) { if(!target->getType()->canConnectTo(getType().get())) { e = true; } } setError(e); } Connectable *Input::getSource() const { return target; } void Input::inputMessage(ConnectionType::Ptr message) { Q_EMIT gotMessage(message); } void Input::handleMessage(ConnectionType::Ptr message) { if(!isEnabled()) { return; } int s = message->sequenceNumber(); if(s < sequenceNumber()) { std::cerr << "connector @" << getUUID().getFullName() << ": dropping old message @ with #" << s << " < #" << sequenceNumber() << std::endl; return; } setSequenceNumber(s); setBlocked(true); buffer_->write(message); count_++; Q_EMIT messageArrived(this); } void Input::notifyMessageProcessed() { Connectable::notifyMessageProcessed(); if(target) { target->notifyMessageProcessed(); } } <commit_msg>errors<commit_after>/// HEADER #include <csapex/msg/input.h> /// COMPONENT #include <csapex/msg/output.h> #include <csapex/command/delete_connection.h> #include <csapex/command/command.h> #include <csapex/utility/assert.h> /// SYSTEM #include <iostream> using namespace csapex; Input::Input(Settings& settings, const UUID &uuid) : Connectable(settings, uuid), target(NULL), buffer_(new Buffer), optional_(false) { QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection); } Input::Input(Settings &settings, Unique* parent, int sub_id) : Connectable(settings, parent, sub_id, TYPE_IN), target(NULL), buffer_(new Buffer), optional_(false) { QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection); } Input::~Input() { if(target != NULL) { target->removeConnection(this); } free(); } void Input::reset() { free(); setSequenceNumber(0); } bool Input::tryConnect(Connectable* other_side) { if(!other_side->canOutput()) { std::cerr << "cannot connect, other side can't output" << std::endl; return false; } return other_side->tryConnect(this); } bool Input::acknowledgeConnection(Connectable* other_side) { target = dynamic_cast<Output*>(other_side); connect(other_side, SIGNAL(destroyed(QObject*)), this, SLOT(removeConnection(QObject*))); connect(other_side, SIGNAL(enabled(bool)), this, SIGNAL(connectionEnabled(bool))); return true; } void Input::removeConnection(Connectable* other_side) { if(target != NULL) { apex_assert_hard(other_side == target); target = NULL; Q_EMIT connectionRemoved(this); } } Command::Ptr Input::removeAllConnectionsCmd() { Command::Ptr cmd(new command::DeleteConnection(target, this)); return cmd; } void Input::setOptional(bool optional) { optional_ = optional; } bool Input::isOptional() const { return optional_; } bool Input::hasMessage() const { return isConnected() && buffer_->isFilled() && !buffer_->isType<connection_types::NoMessage>(); } void Input::stop() { buffer_->disable(); Connectable::stop(); } void Input::free() { buffer_->free(); setBlocked(false); } void Input::enable() { Connectable::enable(); // if(isConnected() && !getSource()->isEnabled()) { // getSource()->enable(); // } } void Input::disable() { Connectable::disable(); // if(isBlocked()) { free(); notifyMessageProcessed(); // } // if(isConnected() && getSource()->isEnabled()) { // getSource()->disable(); // } } void Input::removeAllConnectionsNotUndoable() { if(target != NULL) { target->removeConnection(this); target = NULL; setError(false); Q_EMIT disconnected(this); } } bool Input::canConnectTo(Connectable* other_side, bool move) const { return Connectable::canConnectTo(other_side, move) && (move || !isConnected()); } bool Input::targetsCanBeMovedTo(Connectable* other_side) const { return target->canConnectTo(other_side, true) /*&& canConnectTo(getConnected())*/; } bool Input::isConnected() const { return target != NULL; } void Input::connectionMovePreview(Connectable *other_side) { Q_EMIT(connectionInProgress(getSource(), other_side)); } void Input::validateConnections() { bool e = false; if(isConnected()) { if(!target->getType()->canConnectTo(getType().get())) { e = true; } } setError(e); } Connectable *Input::getSource() const { return target; } void Input::inputMessage(ConnectionType::Ptr message) { Q_EMIT gotMessage(message); } void Input::handleMessage(ConnectionType::Ptr message) { if(!isEnabled()) { return; } int s = message->sequenceNumber(); if(s < sequenceNumber()) { std::cerr << "connector @" << getUUID().getFullName() << ": dropping old message @ with #" << s << " < #" << sequenceNumber() << std::endl; return; } setSequenceNumber(s); setBlocked(true); try { buffer_->write(message); } catch(const std::exception& e) { std::cerr << getUUID() << ": writing message failed: " << e.what() << std::endl; throw e; } count_++; Q_EMIT messageArrived(this); } void Input::notifyMessageProcessed() { Connectable::notifyMessageProcessed(); if(target) { target->notifyMessageProcessed(); } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013, PAL Robotics S.L. // // 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 hiDOF, 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. ////////////////////////////////////////////////////////////////////////////// /// \author Adolfo Rodriguez Tsouroukdissian #include <stdexcept> #include <gtest/gtest.h> #include <ros/console.h> #include <joint_trajectory_controller/joint_trajectory_segment.h> using namespace trajectory_interface; using namespace trajectory_msgs; typedef JointTrajectorySegment<double> Segment; class JointTrajectorySegmentTest : public ::testing::Test { public: JointTrajectorySegmentTest() : traj_start_time(0.5) { p_start.positions.resize(1, 2.0); p_start.velocities.resize(1, -1.0); p_start.time_from_start = ros::Duration(1.0); p_end.positions.resize(1, 4.0); p_end.velocities.resize(1, -2.0); p_end.time_from_start = ros::Duration(2.0); } protected: ros::Time traj_start_time; JointTrajectoryPoint p_start; JointTrajectoryPoint p_end; }; TEST_F(JointTrajectorySegmentTest, InvalidSegmentConstruction) { // Empty start point { JointTrajectoryPoint p_start_bad; EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, JointTrajectoryPoint(), p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Start/end data size mismatch { JointTrajectoryPoint p_start_bad = p_start; p_start_bad.positions.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, p_start_bad, p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Invalid start state { JointTrajectoryPoint p_start_bad = p_start; p_start_bad.velocities.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, p_start_bad, p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Invalid end state { JointTrajectoryPoint p_end_bad = p_end; p_end_bad.velocities.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start, p_end_bad), std::invalid_argument); try {Segment(traj_start_time, p_start, p_end_bad);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } } TEST_F(JointTrajectorySegmentTest, ValidSegmentConstruction) { // Construct segment EXPECT_NO_THROW(Segment(traj_start_time, p_start, p_end)); Segment segment(traj_start_time, p_start, p_end); // Check start/end times { const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec(); const typename Segment::Time end_time = (traj_start_time + p_end.time_from_start).toSec(); EXPECT_EQ(start_time, segment.startTime()); EXPECT_EQ(end_time, segment.endTime()); } // Check start state { typename Segment::State state; segment.sample(segment.startTime(), state); EXPECT_EQ(p_start.positions.front(), state.front().position); EXPECT_EQ(p_start.velocities.front(), state.front().velocity); } // Check end state { typename Segment::State state; segment.sample(segment.endTime(), state); EXPECT_EQ(p_end.positions.front(), state.front().position); EXPECT_EQ(p_end.velocities.front(), state.front().velocity); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add tests for non-ros segment constructor.<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013, PAL Robotics S.L. // // 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 hiDOF, 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. ////////////////////////////////////////////////////////////////////////////// /// \author Adolfo Rodriguez Tsouroukdissian #include <stdexcept> #include <gtest/gtest.h> #include <ros/console.h> #include <joint_trajectory_controller/joint_trajectory_segment.h> using namespace trajectory_interface; using namespace trajectory_msgs; typedef JointTrajectorySegment<double> Segment; class JointTrajectorySegmentTest : public ::testing::Test { public: JointTrajectorySegmentTest() : traj_start_time(0.5) { p_start.positions.resize(1, 2.0); p_start.velocities.resize(1, -1.0); p_start.time_from_start = ros::Duration(1.0); p_end.positions.resize(1, 4.0); p_end.velocities.resize(1, -2.0); p_end.time_from_start = ros::Duration(2.0); start_time = (traj_start_time + p_start.time_from_start).toSec(); start_state.resize(1); start_state.front().position = p_start.positions.front(); start_state.front().velocity = p_start.velocities.front(); end_time = (traj_start_time + p_end.time_from_start).toSec(); end_state.resize(1); end_state.front().position = p_end.positions.front(); end_state.front().velocity = p_end.velocities.front(); } protected: ros::Time traj_start_time; JointTrajectoryPoint p_start; JointTrajectoryPoint p_end; typename Segment::Time start_time, end_time; typename Segment::State start_state, end_state; }; TEST_F(JointTrajectorySegmentTest, InvalidSegmentConstruction) { // Empty start point { JointTrajectoryPoint p_start_bad; EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, JointTrajectoryPoint(), p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Start/end data size mismatch { JointTrajectoryPoint p_start_bad = p_start; p_start_bad.positions.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, p_start_bad, p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Invalid start state { JointTrajectoryPoint p_start_bad = p_start; p_start_bad.velocities.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument); try {Segment(traj_start_time, p_start_bad, p_end);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } // Invalid end state { JointTrajectoryPoint p_end_bad = p_end; p_end_bad.velocities.push_back(0.0); EXPECT_THROW(Segment(traj_start_time, p_start, p_end_bad), std::invalid_argument); try {Segment(traj_start_time, p_start, p_end_bad);} catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());} } } TEST_F(JointTrajectorySegmentTest, ValidSegmentConstructionRos) { // Construct segment from ROS message EXPECT_NO_THROW(Segment(traj_start_time, p_start, p_end)); Segment segment(traj_start_time, p_start, p_end); // Check start/end times { const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec(); const typename Segment::Time end_time = (traj_start_time + p_end.time_from_start).toSec(); EXPECT_EQ(start_time, segment.startTime()); EXPECT_EQ(end_time, segment.endTime()); } // Check start state { typename Segment::State state; segment.sample(segment.startTime(), state); EXPECT_EQ(p_start.positions.front(), state.front().position); EXPECT_EQ(p_start.velocities.front(), state.front().velocity); } // Check end state { typename Segment::State state; segment.sample(segment.endTime(), state); EXPECT_EQ(p_end.positions.front(), state.front().position); EXPECT_EQ(p_end.velocities.front(), state.front().velocity); } } TEST_F(JointTrajectorySegmentTest, ValidSegmentConstruction) { // Construct segment from ROS message EXPECT_NO_THROW(Segment(start_time,start_state, end_time, end_state)); Segment segment(start_time,start_state, end_time, end_state); // Check start/end times { const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec(); const typename Segment::Time end_time = (traj_start_time + p_end.time_from_start).toSec(); EXPECT_EQ(start_time, segment.startTime()); EXPECT_EQ(end_time, segment.endTime()); } // Check start state { typename Segment::State state; segment.sample(segment.startTime(), state); EXPECT_EQ(p_start.positions.front(), state.front().position); EXPECT_EQ(p_start.velocities.front(), state.front().velocity); } // Check end state { typename Segment::State state; segment.sample(segment.endTime(), state); EXPECT_EQ(p_end.positions.front(), state.front().position); EXPECT_EQ(p_end.velocities.front(), state.front().velocity); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// // Copyright 2016 Francisco Jerez // // 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. // /// /// \file /// Some thin wrappers around the Clang/LLVM API used to preserve /// compatibility with older API versions while keeping the ifdef clutter low /// in the rest of the clover::llvm subtree. In case of an API break please /// consider whether it's possible to preserve backwards compatibility by /// introducing a new one-liner inline function or typedef here under the /// compat namespace in order to keep the running code free from preprocessor /// conditionals. /// #ifndef CLOVER_LLVM_COMPAT_HPP #define CLOVER_LLVM_COMPAT_HPP #include "util/algorithm.hpp" #include <llvm/Linker/Linker.h> #include <llvm/Transforms/IPO.h> #include <llvm/Target/TargetMachine.h> #if HAVE_LLVM >= 0x0400 #include <llvm/Support/Error.h> #else #include <llvm/Support/ErrorOr.h> #endif #if HAVE_LLVM >= 0x0307 #include <llvm/IR/LegacyPassManager.h> #include <llvm/Analysis/TargetLibraryInfo.h> #else #include <llvm/PassManager.h> #include <llvm/Target/TargetLibraryInfo.h> #include <llvm/Target/TargetSubtargetInfo.h> #include <llvm/Support/FormattedStream.h> #endif #include <clang/Frontend/CodeGenOptions.h> #include <clang/Frontend/CompilerInstance.h> namespace clover { namespace llvm { namespace compat { #if HAVE_LLVM >= 0x0307 typedef ::llvm::TargetLibraryInfoImpl target_library_info; #else typedef ::llvm::TargetLibraryInfo target_library_info; #endif inline void set_lang_defaults(clang::CompilerInvocation &inv, clang::LangOptions &lopts, clang::InputKind ik, const ::llvm::Triple &t, clang::PreprocessorOptions &ppopts, clang::LangStandard::Kind std) { #if HAVE_LLVM >= 0x0309 inv.setLangDefaults(lopts, ik, t, ppopts, std); #else inv.setLangDefaults(lopts, ik, std); #endif } inline void add_link_bitcode_file(clang::CodeGenOptions &opts, const std::string &path) { #if HAVE_LLVM >= 0x0308 opts.LinkBitcodeFiles.emplace_back(::llvm::Linker::Flags::None, path); #else opts.LinkBitcodeFile = path; #endif } #if HAVE_LLVM >= 0x0307 typedef ::llvm::legacy::PassManager pass_manager; #else typedef ::llvm::PassManager pass_manager; #endif inline void add_data_layout_pass(pass_manager &pm) { #if HAVE_LLVM < 0x0307 pm.add(new ::llvm::DataLayoutPass()); #endif } inline void add_internalize_pass(pass_manager &pm, const std::vector<std::string> &names) { #if HAVE_LLVM >= 0x0309 pm.add(::llvm::createInternalizePass( [=](const ::llvm::GlobalValue &gv) { return std::find(names.begin(), names.end(), gv.getName()) != names.end(); })); #else pm.add(::llvm::createInternalizePass(std::vector<const char *>( map(std::mem_fn(&std::string::data), names)))); #endif } inline std::unique_ptr<::llvm::Linker> create_linker(::llvm::Module &mod) { #if HAVE_LLVM >= 0x0308 return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(mod)); #else return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(&mod)); #endif } inline bool link_in_module(::llvm::Linker &linker, std::unique_ptr<::llvm::Module> mod) { #if HAVE_LLVM >= 0x0308 return linker.linkInModule(std::move(mod)); #else return linker.linkInModule(mod.get()); #endif } #if HAVE_LLVM >= 0x0307 typedef ::llvm::raw_svector_ostream &raw_ostream_to_emit_file; #else typedef ::llvm::formatted_raw_ostream raw_ostream_to_emit_file; #endif #if HAVE_LLVM >= 0x0307 typedef ::llvm::DataLayout data_layout; #else typedef const ::llvm::DataLayout *data_layout; #endif inline data_layout get_data_layout(::llvm::TargetMachine &tm) { #if HAVE_LLVM >= 0x0307 return tm.createDataLayout(); #else return tm.getSubtargetImpl()->getDataLayout(); #endif } #if HAVE_LLVM >= 0x0309 const auto default_reloc_model = ::llvm::None; #else const auto default_reloc_model = ::llvm::Reloc::Default; #endif template<typename M, typename F> void handle_module_error(M &mod, const F &f) { #if HAVE_LLVM >= 0x0400 if (::llvm::Error err = mod.takeError()) ::llvm::handleAllErrors(std::move(err), [&](::llvm::ErrorInfoBase &eib) { f(eib.message()); }); #else if (!mod) f(mod.getError().message()); #endif } } } } #endif <commit_msg>clover: Fix build against clang SVN >= r293097<commit_after>// // Copyright 2016 Francisco Jerez // // 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. // /// /// \file /// Some thin wrappers around the Clang/LLVM API used to preserve /// compatibility with older API versions while keeping the ifdef clutter low /// in the rest of the clover::llvm subtree. In case of an API break please /// consider whether it's possible to preserve backwards compatibility by /// introducing a new one-liner inline function or typedef here under the /// compat namespace in order to keep the running code free from preprocessor /// conditionals. /// #ifndef CLOVER_LLVM_COMPAT_HPP #define CLOVER_LLVM_COMPAT_HPP #include "util/algorithm.hpp" #include <llvm/Linker/Linker.h> #include <llvm/Transforms/IPO.h> #include <llvm/Target/TargetMachine.h> #if HAVE_LLVM >= 0x0400 #include <llvm/Support/Error.h> #else #include <llvm/Support/ErrorOr.h> #endif #if HAVE_LLVM >= 0x0307 #include <llvm/IR/LegacyPassManager.h> #include <llvm/Analysis/TargetLibraryInfo.h> #else #include <llvm/PassManager.h> #include <llvm/Target/TargetLibraryInfo.h> #include <llvm/Target/TargetSubtargetInfo.h> #include <llvm/Support/FormattedStream.h> #endif #include <clang/Frontend/CodeGenOptions.h> #include <clang/Frontend/CompilerInstance.h> namespace clover { namespace llvm { namespace compat { #if HAVE_LLVM >= 0x0307 typedef ::llvm::TargetLibraryInfoImpl target_library_info; #else typedef ::llvm::TargetLibraryInfo target_library_info; #endif inline void set_lang_defaults(clang::CompilerInvocation &inv, clang::LangOptions &lopts, clang::InputKind ik, const ::llvm::Triple &t, clang::PreprocessorOptions &ppopts, clang::LangStandard::Kind std) { #if HAVE_LLVM >= 0x0309 inv.setLangDefaults(lopts, ik, t, ppopts, std); #else inv.setLangDefaults(lopts, ik, std); #endif } inline void add_link_bitcode_file(clang::CodeGenOptions &opts, const std::string &path) { #if HAVE_LLVM >= 0x0500 clang::CodeGenOptions::BitcodeFileToLink F; F.Filename = path; F.PropagateAttrs = true; F.LinkFlags = ::llvm::Linker::Flags::None; opts.LinkBitcodeFiles.emplace_back(F); #elif HAVE_LLVM >= 0x0308 opts.LinkBitcodeFiles.emplace_back(::llvm::Linker::Flags::None, path); #else opts.LinkBitcodeFile = path; #endif } #if HAVE_LLVM >= 0x0307 typedef ::llvm::legacy::PassManager pass_manager; #else typedef ::llvm::PassManager pass_manager; #endif inline void add_data_layout_pass(pass_manager &pm) { #if HAVE_LLVM < 0x0307 pm.add(new ::llvm::DataLayoutPass()); #endif } inline void add_internalize_pass(pass_manager &pm, const std::vector<std::string> &names) { #if HAVE_LLVM >= 0x0309 pm.add(::llvm::createInternalizePass( [=](const ::llvm::GlobalValue &gv) { return std::find(names.begin(), names.end(), gv.getName()) != names.end(); })); #else pm.add(::llvm::createInternalizePass(std::vector<const char *>( map(std::mem_fn(&std::string::data), names)))); #endif } inline std::unique_ptr<::llvm::Linker> create_linker(::llvm::Module &mod) { #if HAVE_LLVM >= 0x0308 return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(mod)); #else return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(&mod)); #endif } inline bool link_in_module(::llvm::Linker &linker, std::unique_ptr<::llvm::Module> mod) { #if HAVE_LLVM >= 0x0308 return linker.linkInModule(std::move(mod)); #else return linker.linkInModule(mod.get()); #endif } #if HAVE_LLVM >= 0x0307 typedef ::llvm::raw_svector_ostream &raw_ostream_to_emit_file; #else typedef ::llvm::formatted_raw_ostream raw_ostream_to_emit_file; #endif #if HAVE_LLVM >= 0x0307 typedef ::llvm::DataLayout data_layout; #else typedef const ::llvm::DataLayout *data_layout; #endif inline data_layout get_data_layout(::llvm::TargetMachine &tm) { #if HAVE_LLVM >= 0x0307 return tm.createDataLayout(); #else return tm.getSubtargetImpl()->getDataLayout(); #endif } #if HAVE_LLVM >= 0x0309 const auto default_reloc_model = ::llvm::None; #else const auto default_reloc_model = ::llvm::Reloc::Default; #endif template<typename M, typename F> void handle_module_error(M &mod, const F &f) { #if HAVE_LLVM >= 0x0400 if (::llvm::Error err = mod.takeError()) ::llvm::handleAllErrors(std::move(err), [&](::llvm::ErrorInfoBase &eib) { f(eib.message()); }); #else if (!mod) f(mod.getError().message()); #endif } } } } #endif <|endoftext|>
<commit_before>//#define _GRIBCXX_DEBUG #include <algorithm> #include <cctype> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <iomanip> #include <list> #include <map> #include <memory> #include <numeric> #include <queue> #include <set> #include <string> #include <utility> #include <vector> using namespace std; // 基本テンプレート #pragma region MACRO #define P(x) cout << (x) << endl #define p(x) cout << (x) #define PED cout << "\n" #define rep(i,n) for(int i=0; i<(int)n; ++i) #define REP(i,x,n) for(int i=x; i<(int)n; ++i) #define repi(i,n) for(int i=0; i<=(int)n; ++i) #define REPI(i,x,n) for(int i=x; i<=(int)n; ++i) #define ILP while(true) #define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i) #define ALL(c) (c).begin(), (c).end() #define mp make_pair #pragma endregion #pragma region TYPE_DEF typedef long long ll; typedef pair<int, int> pii; typedef pair<string, string> pss; typedef pair<string, int> psi; typedef pair<int, string> pis; typedef vector<int> vi; typedef vector<double> vd; typedef vector<long> vl; typedef vector<long long> vll; typedef vector<string> vs; #pragma endregion // Effective std #pragma region ESTD template<typename C, typename T> constexpr int count(C& c, T t) { return count(ALL(c), t); } template<typename C, typename F> constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); } template<typename C, typename T, typename U> constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); } template<typename C, typename F, typename U> constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); } template<typename C> constexpr void sort(C& c) { sort(ALL(c)); } template<typename C, typename Pred> constexpr void sort(C& c, Pred p) { sort(ALL(c), p); } template<typename C> constexpr void reverse(C& c) { reverse(ALL(c)); } #pragma endregion // グラフテンプレート #pragma region GRAPH typedef int Weight; struct Edge { int src, dst; Weight weight; Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) {} }; bool operator < (const Edge &e, const Edge &f) { return e.weight != f.weight ? e.weight > f.weight : e.src != f.src ? e.src < f.src : e.dst < f.dst; } typedef vector<Edge> Edges; typedef vector<Edges> Graph; typedef vector<Weight> Array; typedef vector<Array> Matrix; #pragma endregion // 素数 #pragma region PRIME bool is_prime(unsigned n) { switch(n) { case 0: case 1: return false; case 2: return true; } if (n%2==0) return false; for (unsigned i=3; i*i<=n; i+=2) if (n%i==0) return false; return true; } #pragma endregion // 大文字/小文字変換 void mutal_tr(string &s) { for(int i=s.size(); i--;) { if(islower(s[i])) s[i] = toupper(s[i]); else if (isupper(s[i])) s[i] = tolower(s[i]); } } void to_upper(string &s) { for(int i=s.size(); i--;) s[i] = toupper(s[i]); } void to_lower(string &s) { for(int i=s.size(); i--;) s[i] = tolower(s[i]); } // 集合 template<class T> set<T> intersection(const set<T>& sa, const set<T>& sb) { set<T> ret; for(T a : sa) if(sb.find(a) != sb.end()) ret.insert(a); return ret; } // 定数 #pragma region CONST_VAL #define PI (2*acos(0.0)) #define EPS (1e-9) #define MOD (int)(1e9+7) #pragma endregion int main() { return 0; } <commit_msg>template.cpp<commit_after>//#define _GRIBCXX_DEBUG #include <algorithm> #include <cctype> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <iomanip> #include <list> #include <map> #include <memory> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; // 基本テンプレート #pragma region MACRO #define P(x) cout << (x) << endl #define p(x) cout << (x) #define PED cout << "\n" #define rep(i,n) for(int i=0; i<(int)n; ++i) #define REP(i,x,n) for(int i=x; i<(int)n; ++i) #define repi(i,n) for(int i=0; i<=(int)n; ++i) #define REPI(i,x,n) for(int i=x; i<=(int)n; ++i) #define ILP while(true) #define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i) #define ALL(c) (c).begin(), (c).end() #define mp make_pair #pragma endregion #pragma region TYPE_DEF typedef long long ll; typedef pair<int, int> pii; typedef pair<string, string> pss; typedef pair<string, int> psi; typedef pair<int, string> pis; typedef vector<int> vi; typedef vector<double> vd; typedef vector<long> vl; typedef vector<long long> vll; typedef vector<string> vs; #pragma endregion // Effective std #pragma region ESTD template<typename C, typename T> constexpr int count(C& c, T t) { return count(ALL(c), t); } template<typename C, typename F> constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); } template<typename C, typename T, typename U> constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); } template<typename C, typename F, typename U> constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); } template<typename C> constexpr void sort(C& c) { sort(ALL(c)); } template<typename C, typename Pred> constexpr void sort(C& c, Pred p) { sort(ALL(c), p); } template<typename C> constexpr void reverse(C& c) { reverse(ALL(c)); } #pragma endregion // グラフテンプレート #pragma region GRAPH typedef int Weight; struct Edge { int src, dst; Weight weight; Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) {} }; bool operator < (const Edge &e, const Edge &f) { return e.weight != f.weight ? e.weight > f.weight : e.src != f.src ? e.src < f.src : e.dst < f.dst; } typedef vector<Edge> Edges; typedef vector<Edges> Graph; typedef vector<Weight> Array; typedef vector<Array> Matrix; #pragma endregion // 素数 #pragma region PRIME bool is_prime(unsigned n) { switch(n) { case 0: case 1: return false; case 2: return true; } if (n%2==0) return false; for (unsigned i=3; i*i<=n; i+=2) if (n%i==0) return false; return true; } #pragma endregion // 大文字/小文字変換 void mutal_tr(string &s) { for(int i=s.size(); i--;) { if(islower(s[i])) s[i] = toupper(s[i]); else if (isupper(s[i])) s[i] = tolower(s[i]); } } void to_upper(string &s) { for(int i=s.size(); i--;) s[i] = toupper(s[i]); } void to_lower(string &s) { for(int i=s.size(); i--;) s[i] = tolower(s[i]); } // 集合 template<class T> set<T> intersection(const set<T>& sa, const set<T>& sb) { set<T> ret; for(T a : sa) if(sb.find(a) != sb.end()) ret.insert(a); return ret; } // 定数 #pragma region CONST_VAL #define PI (2*acos(0.0)) #define EPS (1e-9) #define MOD (int)(1e9+7) #pragma endregion int main() { return 0; } <|endoftext|>
<commit_before>#include "interpreterTest.h" #include <src/interpreter/interpreter.h> #include <src/textLanguage/robotsBlockParser.h> using namespace qrTest::robotsTests::interpreterCoreTests; using namespace interpreterCore::interpreter; using namespace ::testing; void InterpreterTest::SetUp() { mQrguiFacade.reset(new QrguiFacade("./unittests/basicTest.qrs")); qDebug() << "loading" << QFileInfo("unittests/basicTest.qrs").absoluteFilePath(); mQrguiFacade->setActiveTab(qReal::Id::loadFromString( "qrm:/RobotsMetamodel/RobotsDiagram/RobotsDiagramNode/{f08fa823-e187-4755-87ba-e4269ae4e798}")); mFakeConnectToRobotAction.reset(new QAction(nullptr)); ON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault( Return(QList<interpreterBase::robotModel::robotParts::Device *>()) ); EXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1)); /// @todo: Do we need this code in some common place? Why do we need to write /// it every time when we are going to use RobotModelManager mock? ON_CALL(mModel, name()).WillByDefault(Return("mockRobot")); EXPECT_CALL(mModel, name()).Times(AtLeast(1)); ON_CALL(mModel, needsConnection()).WillByDefault(Return(false)); EXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0)); ON_CALL(mModel, init()).WillByDefault(Return()); EXPECT_CALL(mModel, init()).Times(AtLeast(0)); ON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock)); EXPECT_CALL(mModel, configuration()).Times(AtLeast(0)); ON_CALL(mModel, connectToRobot()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected) ); EXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0)); ON_CALL(mModel, disconnectFromRobot()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected) ); EXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0)); ON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>())); EXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0)); ON_CALL(mModel, availablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>())); EXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0)); ON_CALL(mModel, applyConfiguration()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured) ); EXPECT_CALL(mModel, applyConfiguration()).Times(1); ON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState)); EXPECT_CALL(mModel, connectionState()).Times(2); ON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline)); EXPECT_CALL(mModel, timeline()).Times(AtLeast(1)); ON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel)); EXPECT_CALL(mModelManager, model()).Times(AtLeast(1)); ON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return()); EXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0); /// @todo Don't like it. interpreterCore::textLanguage::RobotsBlockParser parser( mQrguiFacade->mainWindowInterpretersInterface().errorReporter() , mModelManager , []() { return 0; } ); DummyBlockFactory *blocksFactory = new DummyBlockFactory; blocksFactory->configure( mQrguiFacade->graphicalModelAssistInterface() , mQrguiFacade->logicalModelAssistInterface() , mModelManager , *mQrguiFacade->mainWindowInterpretersInterface().errorReporter() , &parser ); ON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault( Invoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) { Q_UNUSED(robotModel) return blocksFactory->block(id); } ) ); EXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0)); ON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault( Invoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) { Q_UNUSED(robotModel) return blocksFactory->providedBlocks().toSet(); } ) ); EXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0); mInterpreter.reset(new Interpreter( mQrguiFacade->graphicalModelAssistInterface() , mQrguiFacade->logicalModelAssistInterface() , mQrguiFacade->mainWindowInterpretersInterface() , mQrguiFacade->projectManagementInterface() , mBlocksFactoryManager , mModelManager , parser , *mFakeConnectToRobotAction )); } TEST_F(InterpreterTest, interpret) { EXPECT_CALL(mModel, stopRobot()).Times(1); mInterpreter->interpret(); } TEST_F(InterpreterTest, stopRobot) { // It shall be called directly here and in destructor of a model. EXPECT_CALL(mModel, stopRobot()).Times(2); mInterpreter->interpret(); mInterpreter->stopRobot(); } <commit_msg>More build info requested<commit_after>#include "interpreterTest.h" #include <src/interpreter/interpreter.h> #include <src/textLanguage/robotsBlockParser.h> using namespace qrTest::robotsTests::interpreterCoreTests; using namespace interpreterCore::interpreter; using namespace ::testing; #include<QApplication> void InterpreterTest::SetUp() { qDebug() << "app" << QApplication::applicationFilePath(); qDebug() << "loading" << QFileInfo("unittests/basicTest.qrs").absoluteFilePath(); mQrguiFacade.reset(new QrguiFacade("/home/travis/qreal/qreal/bin/unittests/basicTest.qrs")); mQrguiFacade->setActiveTab(qReal::Id::loadFromString( "qrm:/RobotsMetamodel/RobotsDiagram/RobotsDiagramNode/{f08fa823-e187-4755-87ba-e4269ae4e798}")); mFakeConnectToRobotAction.reset(new QAction(nullptr)); ON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault( Return(QList<interpreterBase::robotModel::robotParts::Device *>()) ); EXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1)); /// @todo: Do we need this code in some common place? Why do we need to write /// it every time when we are going to use RobotModelManager mock? ON_CALL(mModel, name()).WillByDefault(Return("mockRobot")); EXPECT_CALL(mModel, name()).Times(AtLeast(1)); ON_CALL(mModel, needsConnection()).WillByDefault(Return(false)); EXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0)); ON_CALL(mModel, init()).WillByDefault(Return()); EXPECT_CALL(mModel, init()).Times(AtLeast(0)); ON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock)); EXPECT_CALL(mModel, configuration()).Times(AtLeast(0)); ON_CALL(mModel, connectToRobot()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected) ); EXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0)); ON_CALL(mModel, disconnectFromRobot()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected) ); EXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0)); ON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>())); EXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0)); ON_CALL(mModel, availablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>())); EXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0)); ON_CALL(mModel, applyConfiguration()).WillByDefault( Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured) ); EXPECT_CALL(mModel, applyConfiguration()).Times(1); ON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState)); EXPECT_CALL(mModel, connectionState()).Times(2); ON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline)); EXPECT_CALL(mModel, timeline()).Times(AtLeast(1)); ON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel)); EXPECT_CALL(mModelManager, model()).Times(AtLeast(1)); ON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return()); EXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0); /// @todo Don't like it. interpreterCore::textLanguage::RobotsBlockParser parser( mQrguiFacade->mainWindowInterpretersInterface().errorReporter() , mModelManager , []() { return 0; } ); DummyBlockFactory *blocksFactory = new DummyBlockFactory; blocksFactory->configure( mQrguiFacade->graphicalModelAssistInterface() , mQrguiFacade->logicalModelAssistInterface() , mModelManager , *mQrguiFacade->mainWindowInterpretersInterface().errorReporter() , &parser ); ON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault( Invoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) { Q_UNUSED(robotModel) return blocksFactory->block(id); } ) ); EXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0)); ON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault( Invoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) { Q_UNUSED(robotModel) return blocksFactory->providedBlocks().toSet(); } ) ); EXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0); mInterpreter.reset(new Interpreter( mQrguiFacade->graphicalModelAssistInterface() , mQrguiFacade->logicalModelAssistInterface() , mQrguiFacade->mainWindowInterpretersInterface() , mQrguiFacade->projectManagementInterface() , mBlocksFactoryManager , mModelManager , parser , *mFakeConnectToRobotAction )); } TEST_F(InterpreterTest, interpret) { EXPECT_CALL(mModel, stopRobot()).Times(1); mInterpreter->interpret(); } TEST_F(InterpreterTest, stopRobot) { // It shall be called directly here and in destructor of a model. EXPECT_CALL(mModel, stopRobot()).Times(2); mInterpreter->interpret(); mInterpreter->stopRobot(); } <|endoftext|>
<commit_before>/** * @file * @brief Implementation of CorryvreckanWriter module * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "CorryvreckanWriterModule.hpp" #include <string> #include <utility> #include "core/utils/log.h" using namespace allpix; CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager) : Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) { // ... Implement ... (Typically bounds the required messages and optionally sets configuration defaults) LOG(TRACE) << "Initializing module " << getUniqueName(); // Require PixelCharge messages for single detector messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED); } // Set up the output trees void CorryvreckanWriterModule::init() { LOG(TRACE) << "Initialising module " << getUniqueName(); // Create output file and directories fileName_ = getOutputPath(config_.get<std::string>("file_name", "corryvreckanOutput") + ".root", true); outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE"); outputFile_->cd(); outputFile_->mkdir("pixels"); // Loop over all detectors and make trees for data std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors(); for(auto& detector : detectors) { // Get the detector ID and type std::string detectorID = detector->getName(); // Create the tree std::string objectID = detectorID + "_pixels"; std::string treeName = detectorID + "_Timepix3_pixels"; outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str()); outputTrees_[objectID]->Branch("time", &time_); // Map the pixel object to the tree treePixels_[objectID] = new corryvreckan::Pixel(); outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]); } // Initialise the time time_ = 0; } // Make instantiations of Corryvreckan pixels, and store these in the trees during run time void CorryvreckanWriterModule::run(unsigned int) { // Loop through all receieved messages for(auto& message : pixel_messages_) { std::string detectorID = message->getDetector()->getName(); std::string objectID = detectorID + "_pixels"; LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID; LOG(DEBUG) << "Time on event hits will be " << time_; // Loop through all pixels received for(auto& allpix_pixel : message->getData()) { // Make a new output pixel unsigned int pixelX = allpix_pixel.getPixel().getIndex().X(); unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y(); double adc = allpix_pixel.getSignal(); long long int time(time_); corryvreckan::Pixel* outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time); LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID; // Map the pixel to the output tree and write it treePixels_[objectID] = outputPixel; outputTrees_[objectID]->Fill(); } } // Increment the time till the next event time_ += 10; } // Save the output trees to file // Set up the output trees void CorryvreckanWriterModule::finalize() { // Loop over all detectors and store the trees std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors(); for(auto& detector : detectors) { // Get the detector ID and type std::string detectorID = detector->getName(); std::string objectID = detectorID + "_pixels"; // Move to the write output file outputFile_->cd(); outputFile_->cd("pixels"); outputTrees_[objectID]->Write(); // Clean up the tree and remove object pointer delete outputTrees_[objectID]; treePixels_[objectID] = nullptr; } outputFile_->Close(); } <commit_msg>CorryvreckanWriter: clean up code a bit<commit_after>/** * @file * @brief Implementation of CorryvreckanWriter module * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "CorryvreckanWriterModule.hpp" #include <string> #include <utility> #include "core/utils/log.h" using namespace allpix; CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager) : Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) { // Require PixelCharge messages for single detector messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED); } // Set up the output trees void CorryvreckanWriterModule::init() { // Create output file and directories fileName_ = getOutputPath(config_.get<std::string>("file_name", "corryvreckanOutput") + ".root", true); outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE"); outputFile_->cd(); outputFile_->mkdir("pixels"); // Loop over all detectors and make trees for data auto detectors = geometryManager_->getDetectors(); for(auto& detector : detectors) { // Get the detector ID and type std::string detectorID = detector->getName(); // Create the tree std::string objectID = detectorID + "_pixels"; std::string treeName = detectorID + "_Timepix3_pixels"; outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str()); outputTrees_[objectID]->Branch("time", &time_); // Map the pixel object to the tree treePixels_[objectID] = new corryvreckan::Pixel(); outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]); } // Initialise the time time_ = 0; } // Make instantiations of Corryvreckan pixels, and store these in the trees during run time void CorryvreckanWriterModule::run(unsigned int) { // Loop through all receieved messages for(auto& message : pixel_messages_) { auto detectorID = message->getDetector()->getName(); auto objectID = detectorID + "_pixels"; LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID; LOG(DEBUG) << "Time on event hits will be " << time_; // Loop through all pixels received for(auto& allpix_pixel : message->getData()) { // Make a new output pixel unsigned int pixelX = allpix_pixel.getPixel().getIndex().X(); unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y(); double adc = allpix_pixel.getSignal(); long long int time(time_); auto outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time); LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID; // Map the pixel to the output tree and write it treePixels_[objectID] = outputPixel; outputTrees_[objectID]->Fill(); } } // Increment the time till the next event time_ += 10; } // Save the output trees to file void CorryvreckanWriterModule::finalize() { // Loop over all detectors and store the trees std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors(); for(auto& detector : detectors) { // Get the detector ID and type std::string detectorID = detector->getName(); std::string objectID = detectorID + "_pixels"; // Move to the write output file outputFile_->cd(); outputFile_->cd("pixels"); outputTrees_[objectID]->Write(); // Clean up the tree and remove object pointer delete outputTrees_[objectID]; treePixels_[objectID] = nullptr; } // Print statistics LOG(STATUS) << "Wrote output data to file:" << std::endl << fileName_; outputFile_->Close(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: WinClipboard.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: tra $ $Date: 2001-07-24 07:53:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _WINCLIPBOARD_HXX_ #include "WinClipboard.hxx" #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_CLIPBOARDEVENT_HPP_ #include <com/sun/star/datatransfer/clipboard/ClipboardEvent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _WINCLIPBIMPL_HXX_ #include "WinClipbImpl.hxx" #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace osl; using namespace std; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // defines //------------------------------------------------------------------------ #define WINCLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.ClipboardW32" //------------------------------------------------------------------------ // helper functions //------------------------------------------------------------------------ namespace { Sequence< OUString > SAL_CALL WinClipboard_getSupportedServiceNames() { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard"); return aRet; } } //------------------------------------------------------------------------ // ctor //------------------------------------------------------------------------ /*XEventListener,*/ CWinClipboard::CWinClipboard( const Reference< XMultiServiceFactory >& rServiceManager, const OUString& aClipboardName ) : WeakComponentImplHelper4< XClipboardEx, XFlushableClipboard, XClipboardNotifier, XServiceInfo >( m_aCbListenerMutex ), m_SrvMgr( rServiceManager ) { m_pImpl.reset( new CWinClipbImpl( aClipboardName, this ) ); } //======================================================================== // XClipboard //======================================================================== //------------------------------------------------------------------------ // getContent // to avoid unecessary traffic we check first if there is a clipboard // content which was set via setContent, in this case we don't need // to query the content from the clipboard, create a new wrapper object // and so on, we simply return the orignial XTransferable instead of our // DOTransferable //------------------------------------------------------------------------ Reference< XTransferable > SAL_CALL CWinClipboard::getContents( ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getContents( ); return Reference< XTransferable >( ); } //------------------------------------------------------------------------ // setContent //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::setContents( const Reference< XTransferable >& xTransferable, const Reference< XClipboardOwner >& xClipboardOwner ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) m_pImpl->setContents( xTransferable, xClipboardOwner ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ OUString SAL_CALL CWinClipboard::getName( ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getName( ); return OUString::createFromAscii( "" ); } //======================================================================== // XFlushableClipboard //======================================================================== void SAL_CALL CWinClipboard::flushClipboard( ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) m_pImpl->flushClipboard( ); } //======================================================================== // XClipboardEx //======================================================================== sal_Int8 SAL_CALL CWinClipboard::getRenderingCapabilities( ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getRenderingCapabilities( ); return 0; } //======================================================================== // XClipboardNotifier //======================================================================== //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); // check input parameter if ( !listener.is( ) ) throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ), static_cast< XClipboardEx* >( this ), 1 ); rBHelper.aLC.addInterface( getCppuType( &listener ), listener ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); // check input parameter if ( !listener.is( ) ) throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ), static_cast< XClipboardEx* >( this ), 1 ); rBHelper.aLC.removeInterface( getCppuType( &listener ), listener ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::notifyAllClipboardListener( ) { if ( !rBHelper.bDisposed ) { ClearableMutexGuard aGuard( rBHelper.rMutex ); if ( !rBHelper.bDisposed ) { aGuard.clear( ); OInterfaceContainerHelper* pICHelper = rBHelper.aLC.getContainer( getCppuType( ( Reference< XClipboardListener > * ) 0 ) ); if ( pICHelper ) { OInterfaceIteratorHelper iter( *pICHelper ); Reference< XTransferable > rXTransf = m_pImpl->getContents( ); ClipboardEvent aClipbEvent( static_cast< XClipboard* >( this ), rXTransf ); while( iter.hasMoreElements( ) ) { try { Reference< XClipboardListener > xCBListener( iter.next( ), UNO_QUERY ); if ( xCBListener.is( ) ) xCBListener->changedContents( aClipbEvent ); } catch( RuntimeException& ) { OSL_ENSURE( false, "RuntimeException caught" ); } catch( ... ) { OSL_ENSURE( false, "Exception during event dispatching" ); } } // while } // end if } // end if } // end if } //------------------------------------------------ // overwritten base class method which will be // called by the base class dispose method //------------------------------------------------ void SAL_CALL CWinClipboard::disposing() { // do my own stuff m_pImpl->dispose( ); // force destruction of the impl class m_pImpl.reset( NULL ); } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- OUString SAL_CALL CWinClipboard::getImplementationName( ) throw(RuntimeException) { return OUString::createFromAscii( WINCLIPBOARD_IMPL_NAME ); } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- sal_Bool SAL_CALL CWinClipboard::supportsService( const OUString& ServiceName ) throw(RuntimeException) { Sequence < OUString > SupportedServicesNames = WinClipboard_getSupportedServiceNames(); for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; ) if (SupportedServicesNames[n].compareTo(ServiceName) == 0) return sal_True; return sal_False; } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- Sequence< OUString > SAL_CALL CWinClipboard::getSupportedServiceNames( ) throw(RuntimeException) { return WinClipboard_getSupportedServiceNames(); }<commit_msg>INTEGRATION: CWS rt02 (1.10.94); FILE MERGED 2003/10/01 12:06:04 rt 1.10.94.1: #i19697# No newline at end of file<commit_after>/************************************************************************* * * $RCSfile: WinClipboard.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2003-10-06 14:37:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _WINCLIPBOARD_HXX_ #include "WinClipboard.hxx" #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_CLIPBOARDEVENT_HPP_ #include <com/sun/star/datatransfer/clipboard/ClipboardEvent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _WINCLIPBIMPL_HXX_ #include "WinClipbImpl.hxx" #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace osl; using namespace std; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // defines //------------------------------------------------------------------------ #define WINCLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.ClipboardW32" //------------------------------------------------------------------------ // helper functions //------------------------------------------------------------------------ namespace { Sequence< OUString > SAL_CALL WinClipboard_getSupportedServiceNames() { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard"); return aRet; } } //------------------------------------------------------------------------ // ctor //------------------------------------------------------------------------ /*XEventListener,*/ CWinClipboard::CWinClipboard( const Reference< XMultiServiceFactory >& rServiceManager, const OUString& aClipboardName ) : WeakComponentImplHelper4< XClipboardEx, XFlushableClipboard, XClipboardNotifier, XServiceInfo >( m_aCbListenerMutex ), m_SrvMgr( rServiceManager ) { m_pImpl.reset( new CWinClipbImpl( aClipboardName, this ) ); } //======================================================================== // XClipboard //======================================================================== //------------------------------------------------------------------------ // getContent // to avoid unecessary traffic we check first if there is a clipboard // content which was set via setContent, in this case we don't need // to query the content from the clipboard, create a new wrapper object // and so on, we simply return the orignial XTransferable instead of our // DOTransferable //------------------------------------------------------------------------ Reference< XTransferable > SAL_CALL CWinClipboard::getContents( ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getContents( ); return Reference< XTransferable >( ); } //------------------------------------------------------------------------ // setContent //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::setContents( const Reference< XTransferable >& xTransferable, const Reference< XClipboardOwner >& xClipboardOwner ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) m_pImpl->setContents( xTransferable, xClipboardOwner ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ OUString SAL_CALL CWinClipboard::getName( ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getName( ); return OUString::createFromAscii( "" ); } //======================================================================== // XFlushableClipboard //======================================================================== void SAL_CALL CWinClipboard::flushClipboard( ) throw( RuntimeException ) { MutexGuard aGuard( m_aMutex ); if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) m_pImpl->flushClipboard( ); } //======================================================================== // XClipboardEx //======================================================================== sal_Int8 SAL_CALL CWinClipboard::getRenderingCapabilities( ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); if ( NULL != m_pImpl.get( ) ) return m_pImpl->getRenderingCapabilities( ); return 0; } //======================================================================== // XClipboardNotifier //======================================================================== //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); // check input parameter if ( !listener.is( ) ) throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ), static_cast< XClipboardEx* >( this ), 1 ); rBHelper.aLC.addInterface( getCppuType( &listener ), listener ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException ) { if ( rBHelper.bDisposed ) throw DisposedException( OUString::createFromAscii( "object is already disposed" ), static_cast< XClipboardEx* >( this ) ); // check input parameter if ( !listener.is( ) ) throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ), static_cast< XClipboardEx* >( this ), 1 ); rBHelper.aLC.removeInterface( getCppuType( &listener ), listener ); } //------------------------------------------------------------------------ // getName //------------------------------------------------------------------------ void SAL_CALL CWinClipboard::notifyAllClipboardListener( ) { if ( !rBHelper.bDisposed ) { ClearableMutexGuard aGuard( rBHelper.rMutex ); if ( !rBHelper.bDisposed ) { aGuard.clear( ); OInterfaceContainerHelper* pICHelper = rBHelper.aLC.getContainer( getCppuType( ( Reference< XClipboardListener > * ) 0 ) ); if ( pICHelper ) { OInterfaceIteratorHelper iter( *pICHelper ); Reference< XTransferable > rXTransf = m_pImpl->getContents( ); ClipboardEvent aClipbEvent( static_cast< XClipboard* >( this ), rXTransf ); while( iter.hasMoreElements( ) ) { try { Reference< XClipboardListener > xCBListener( iter.next( ), UNO_QUERY ); if ( xCBListener.is( ) ) xCBListener->changedContents( aClipbEvent ); } catch( RuntimeException& ) { OSL_ENSURE( false, "RuntimeException caught" ); } catch( ... ) { OSL_ENSURE( false, "Exception during event dispatching" ); } } // while } // end if } // end if } // end if } //------------------------------------------------ // overwritten base class method which will be // called by the base class dispose method //------------------------------------------------ void SAL_CALL CWinClipboard::disposing() { // do my own stuff m_pImpl->dispose( ); // force destruction of the impl class m_pImpl.reset( NULL ); } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- OUString SAL_CALL CWinClipboard::getImplementationName( ) throw(RuntimeException) { return OUString::createFromAscii( WINCLIPBOARD_IMPL_NAME ); } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- sal_Bool SAL_CALL CWinClipboard::supportsService( const OUString& ServiceName ) throw(RuntimeException) { Sequence < OUString > SupportedServicesNames = WinClipboard_getSupportedServiceNames(); for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; ) if (SupportedServicesNames[n].compareTo(ServiceName) == 0) return sal_True; return sal_False; } // ------------------------------------------------- // XServiceInfo // ------------------------------------------------- Sequence< OUString > SAL_CALL CWinClipboard::getSupportedServiceNames( ) throw(RuntimeException) { return WinClipboard_getSupportedServiceNames(); } <|endoftext|>
<commit_before> #include "GLTexture.h" #include "Image.h" #include "GLDriver.h" #include "GLTypeMappings.h" namespace Demi { DiGLTextureDrv::DiGLTextureDrv(DiTexture* parent) :mGLFormat(GL_NONE), mGLTextureType(GL_TEXTURE_2D), mTextureID(0), mImageSize(0), mBuffer(nullptr), mCurrentLockFlag(LOCK_NORMAL) { } DiGLTextureDrv::~DiGLTextureDrv() { if (mBuffer->data) { delete[] (uint8*)mBuffer->data; mBuffer->data = nullptr; } } void DiGLTextureDrv::CopyToMemory(const DiBox &srcBox, const DiPixelBox &dst) { } void DiGLTextureDrv::Release() { glDeleteTextures(1, &mTextureID); if (mBuffer) { DI_DELETE mBuffer; mBuffer = nullptr; } } void DiGLTextureDrv::CreateTexture() { uint32 width = mParent->GetWidth(); uint32 height = mParent->GetHeight(); uint32 numLevels = mParent->GetNumLevels(); DiPixelFormat fmt = mParent->GetFormat(); mBuffer = DI_NEW DiPixelBox(width, height, fmt); mGLFormat = DiGLTypeMappings::GLFormatMapping[fmt]; if (mGLFormat == GL_NONE) { DI_WARNING("Unsupported pixel format: %d", fmt); return; } glGenTextures(1, &mTextureID); mGLTextureType = DiGLTypeMappings::GetGLTextureType(mParent->GetTextureType()); glBindTexture(mGLTextureType, mTextureID); if (GLEW_VERSION_1_2) glTexParameteri(mGLTextureType, GL_TEXTURE_MAX_LEVEL, numLevels); glTexParameteri(mGLTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(mGLTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GLEW_VERSION_1_2) { glTexParameteri(mGLTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(mGLTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } mImageSize = DiPixelBox::ComputeImageByteSize(width, height, fmt); // TODO: Auto generate mipmap BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); if (isCompressed) { uint32 imageSize = mImageSize; uint8 *tmpdata = new uint8[imageSize]; memset(tmpdata, 0, imageSize); for (size_t i = 0; i < numLevels; i++) { imageSize = DiPixelBox::ComputeImageByteSize(width, height, fmt); switch (mGLTextureType) { case GL_TEXTURE_2D: glCompressedTexImage2DARB(GL_TEXTURE_2D, i, mGLFormat, width, height, 0, imageSize, tmpdata); break; case GL_TEXTURE_CUBE_MAP: for (int face = 0; face < 6; face++) { glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, i, mGLFormat, width, height, 0, imageSize, tmpdata); } break; } if (width > 1) width = width / 2; if (height > 1) height = height / 2; } delete[] tmpdata; } else { for (size_t i = 0; i < numLevels; i++) { switch (mGLTextureType) { case GL_TEXTURE_2D: glTexImage2D(GL_TEXTURE_2D, i, mGLFormat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); break; case GL_TEXTURE_CUBE_MAP: for (int face = 0; face < 6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, i, mGLFormat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } break; } if (width > 1) width = width / 2; if (height > 1) height = height / 2; } } } void DiGLTextureDrv::Bind(uint32 samplerIndex) { if (!mTextureID) { glBindTexture(mGLTextureType, 0); } else { glEnable(mGLTextureType); glBindTexture(mGLTextureType, mTextureID); } } void* DiGLTextureDrv::LockLevel(uint32 level, uint32 surface, DiLockFlag lockflag) { DiBox lockbox(0, 0, mBuffer->GetWidth(), mBuffer->GetHeight()); AllocateBuffer(); mCurrentLockFlag = lockflag; if (lockflag != LOCK_DISCARD) { Download(*mBuffer, level, surface); } return mBuffer->data; } void DiGLTextureDrv::UnlockLevel(uint32 level, uint32 surface) { if (mCurrentLockFlag != LOCK_READ_ONLY) { DiBox lockbox(0, 0, mBuffer->GetWidth(), mBuffer->GetHeight()); Upload(*mBuffer, lockbox, level, surface); } DeallocateBuffer(); } void* DiGLTextureDrv::GetSurfaceHandle() { return nullptr; } void DiGLTextureDrv::CopyFromMemory(const DiPixelBox &srcBox, const DiBox &dst, uint32 level, uint32 surface /*= 0*/) { AllocateBuffer(); Upload(srcBox, dst, level, surface); DeallocateBuffer(); } void DiGLTextureDrv::AllocateBuffer() { if (!mBuffer->data) { mBuffer->data = DI_NEW uint8[mImageSize]; } } void DiGLTextureDrv::DeallocateBuffer() { if (mParent->GetResourceUsage() & RU_STATIC) { delete[] (uint8*)mBuffer->data; mBuffer->data = nullptr; } } void DiGLTextureDrv::Upload(const DiPixelBox &src, const DiBox &dst, uint32 level, uint32 surface) { glBindTexture(mGLTextureType, mTextureID); DiPixelFormat fmt = mParent->GetFormat(); BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); GLenum faceType = GL_TEXTURE_2D; if (mGLTextureType == GL_TEXTURE_CUBE_MAP) faceType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + surface; if (isCompressed) { switch (mGLTextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: if (dst.left == 0 && dst.top == 0) { glCompressedTexImage2DARB(faceType, level, mGLFormat, dst.GetWidth(), dst.GetHeight(), 0, src.GetConsecutiveSize(), src.data); } else { glCompressedTexSubImage2DARB(faceType, level, dst.left, dst.top, dst.GetWidth(), dst.GetHeight(), mGLFormat, src.GetConsecutiveSize(), src.data); } break; } } else { if (src.GetWidth() != src.rowPitch) glPixelStorei(GL_UNPACK_ROW_LENGTH, src.rowPitch); if (src.GetWidth() > 0 && src.GetHeight()*src.GetWidth() != src.slicePitch) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (src.slicePitch / src.GetWidth())); if (src.left > 0 || src.top > 0) glPixelStorei(GL_UNPACK_SKIP_PIXELS, src.left + src.rowPitch * src.top); if ((src.GetWidth()*DiPixelBox::GetNumElemBytes(src.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } switch (mGLTextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: glTexSubImage2D(faceType, level, dst.left, dst.top, dst.GetWidth(), dst.GetHeight(), mGLFormat, mGLFormat, src.data); break; } } // restore glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); if (GLEW_VERSION_1_2) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } void DiGLTextureDrv::Download(const DiPixelBox &data, uint32 level, uint32 surface) { if (data.GetWidth() != mParent->GetWidth() || data.GetHeight() != mParent->GetHeight()) { DI_WARNING("Only download of entire buffer of the texture is supported."); return; } glBindTexture(mGLTextureType, mTextureID); DiPixelFormat fmt = mParent->GetFormat(); BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); GLenum faceType = GL_TEXTURE_2D; if (mGLTextureType == GL_TEXTURE_CUBE_MAP) faceType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + surface; if (isCompressed) { glGetCompressedTexImageARB(faceType, level, data.data); } else { if (data.GetWidth() != data.rowPitch) glPixelStorei(GL_PACK_ROW_LENGTH, data.rowPitch); if (data.GetHeight()*data.GetWidth() != data.slicePitch) glPixelStorei(GL_PACK_IMAGE_HEIGHT, (data.slicePitch / data.GetWidth())); if (data.left > 0 || data.top > 0) glPixelStorei(GL_PACK_SKIP_PIXELS, data.left + data.rowPitch * data.top); if ((data.GetWidth()*DiPixelBox::GetNumElemBytes(data.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_PACK_ALIGNMENT, 1); } // We can only get the entire texture glGetTexImage(faceType, level, mGLFormat, mGLFormat, data.data); // Restore defaults glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); glPixelStorei(GL_PACK_ALIGNMENT, 4); } } }<commit_msg>CopyToMemory<commit_after> #include "GLTexture.h" #include "Image.h" #include "GLDriver.h" #include "GLTypeMappings.h" namespace Demi { DiGLTextureDrv::DiGLTextureDrv(DiTexture* parent) :mGLFormat(GL_NONE), mGLTextureType(GL_TEXTURE_2D), mTextureID(0), mImageSize(0), mBuffer(nullptr), mCurrentLockFlag(LOCK_NORMAL) { } DiGLTextureDrv::~DiGLTextureDrv() { if (mBuffer->data) { delete[] (uint8*)mBuffer->data; mBuffer->data = nullptr; } } void DiGLTextureDrv::CopyToMemory(const DiBox &srcBox, const DiPixelBox &dst) { DI_ASSERT(mBuffer); if (!mBuffer->Contains(srcBox)) { DI_WARNING("Source box out of range."); return; } if (mBuffer->GetWidth() != srcBox.GetWidth() || mBuffer->GetHeight() != srcBox.GetHeight()) { DI_WARNING("No scale is supported currently."); return; } Download(dst,0,0); } void DiGLTextureDrv::Release() { glDeleteTextures(1, &mTextureID); if (mBuffer) { DI_DELETE mBuffer; mBuffer = nullptr; } } void DiGLTextureDrv::CreateTexture() { uint32 width = mParent->GetWidth(); uint32 height = mParent->GetHeight(); uint32 numLevels = mParent->GetNumLevels(); DiPixelFormat fmt = mParent->GetFormat(); mBuffer = DI_NEW DiPixelBox(width, height, fmt); mGLFormat = DiGLTypeMappings::GLFormatMapping[fmt]; if (mGLFormat == GL_NONE) { DI_WARNING("Unsupported pixel format: %d", fmt); return; } glGenTextures(1, &mTextureID); mGLTextureType = DiGLTypeMappings::GetGLTextureType(mParent->GetTextureType()); glBindTexture(mGLTextureType, mTextureID); if (GLEW_VERSION_1_2) glTexParameteri(mGLTextureType, GL_TEXTURE_MAX_LEVEL, numLevels); glTexParameteri(mGLTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(mGLTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GLEW_VERSION_1_2) { glTexParameteri(mGLTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(mGLTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } mImageSize = DiPixelBox::ComputeImageByteSize(width, height, fmt); // TODO: Auto generate mipmap BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); if (isCompressed) { uint32 imageSize = mImageSize; uint8 *tmpdata = new uint8[imageSize]; memset(tmpdata, 0, imageSize); for (size_t i = 0; i < numLevels; i++) { imageSize = DiPixelBox::ComputeImageByteSize(width, height, fmt); switch (mGLTextureType) { case GL_TEXTURE_2D: glCompressedTexImage2DARB(GL_TEXTURE_2D, i, mGLFormat, width, height, 0, imageSize, tmpdata); break; case GL_TEXTURE_CUBE_MAP: for (int face = 0; face < 6; face++) { glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, i, mGLFormat, width, height, 0, imageSize, tmpdata); } break; } if (width > 1) width = width / 2; if (height > 1) height = height / 2; } delete[] tmpdata; } else { for (size_t i = 0; i < numLevels; i++) { switch (mGLTextureType) { case GL_TEXTURE_2D: glTexImage2D(GL_TEXTURE_2D, i, mGLFormat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); break; case GL_TEXTURE_CUBE_MAP: for (int face = 0; face < 6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, i, mGLFormat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } break; } if (width > 1) width = width / 2; if (height > 1) height = height / 2; } } } void DiGLTextureDrv::Bind(uint32 samplerIndex) { if (!mTextureID) { glBindTexture(mGLTextureType, 0); } else { glEnable(mGLTextureType); glBindTexture(mGLTextureType, mTextureID); } } void* DiGLTextureDrv::LockLevel(uint32 level, uint32 surface, DiLockFlag lockflag) { DiBox lockbox(0, 0, mBuffer->GetWidth(), mBuffer->GetHeight()); AllocateBuffer(); mCurrentLockFlag = lockflag; if (lockflag != LOCK_DISCARD) { Download(*mBuffer, level, surface); } return mBuffer->data; } void DiGLTextureDrv::UnlockLevel(uint32 level, uint32 surface) { if (mCurrentLockFlag != LOCK_READ_ONLY) { DiBox lockbox(0, 0, mBuffer->GetWidth(), mBuffer->GetHeight()); Upload(*mBuffer, lockbox, level, surface); } DeallocateBuffer(); } void* DiGLTextureDrv::GetSurfaceHandle() { return nullptr; } void DiGLTextureDrv::CopyFromMemory(const DiPixelBox &srcBox, const DiBox &dst, uint32 level, uint32 surface /*= 0*/) { AllocateBuffer(); Upload(srcBox, dst, level, surface); DeallocateBuffer(); } void DiGLTextureDrv::AllocateBuffer() { if (!mBuffer->data) { mBuffer->data = DI_NEW uint8[mImageSize]; } } void DiGLTextureDrv::DeallocateBuffer() { if (mParent->GetResourceUsage() & RU_STATIC) { delete[] (uint8*)mBuffer->data; mBuffer->data = nullptr; } } void DiGLTextureDrv::Upload(const DiPixelBox &src, const DiBox &dst, uint32 level, uint32 surface) { glBindTexture(mGLTextureType, mTextureID); DiPixelFormat fmt = mParent->GetFormat(); BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); GLenum faceType = GL_TEXTURE_2D; if (mGLTextureType == GL_TEXTURE_CUBE_MAP) faceType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + surface; if (isCompressed) { switch (mGLTextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: if (dst.left == 0 && dst.top == 0) { glCompressedTexImage2DARB(faceType, level, mGLFormat, dst.GetWidth(), dst.GetHeight(), 0, src.GetConsecutiveSize(), src.data); } else { glCompressedTexSubImage2DARB(faceType, level, dst.left, dst.top, dst.GetWidth(), dst.GetHeight(), mGLFormat, src.GetConsecutiveSize(), src.data); } break; } } else { if (src.GetWidth() != src.rowPitch) glPixelStorei(GL_UNPACK_ROW_LENGTH, src.rowPitch); if (src.GetWidth() > 0 && src.GetHeight()*src.GetWidth() != src.slicePitch) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (src.slicePitch / src.GetWidth())); if (src.left > 0 || src.top > 0) glPixelStorei(GL_UNPACK_SKIP_PIXELS, src.left + src.rowPitch * src.top); if ((src.GetWidth()*DiPixelBox::GetNumElemBytes(src.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } switch (mGLTextureType) { case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: glTexSubImage2D(faceType, level, dst.left, dst.top, dst.GetWidth(), dst.GetHeight(), mGLFormat, mGLFormat, src.data); break; } } // restore glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); if (GLEW_VERSION_1_2) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } void DiGLTextureDrv::Download(const DiPixelBox &data, uint32 level, uint32 surface) { if (data.GetWidth() != mParent->GetWidth() || data.GetHeight() != mParent->GetHeight()) { DI_WARNING("Only download of entire buffer of the texture is supported."); return; } glBindTexture(mGLTextureType, mTextureID); DiPixelFormat fmt = mParent->GetFormat(); BOOL isCompressed = DiPixelBox::IsCompressedFormat(fmt); GLenum faceType = GL_TEXTURE_2D; if (mGLTextureType == GL_TEXTURE_CUBE_MAP) faceType = GL_TEXTURE_CUBE_MAP_POSITIVE_X + surface; if (isCompressed) { glGetCompressedTexImageARB(faceType, level, data.data); } else { if (data.GetWidth() != data.rowPitch) glPixelStorei(GL_PACK_ROW_LENGTH, data.rowPitch); if (data.GetHeight()*data.GetWidth() != data.slicePitch) glPixelStorei(GL_PACK_IMAGE_HEIGHT, (data.slicePitch / data.GetWidth())); if (data.left > 0 || data.top > 0) glPixelStorei(GL_PACK_SKIP_PIXELS, data.left + data.rowPitch * data.top); if ((data.GetWidth()*DiPixelBox::GetNumElemBytes(data.format)) & 3) { // Standard alignment of 4 is not right glPixelStorei(GL_PACK_ALIGNMENT, 1); } // We can only get the entire texture glGetTexImage(faceType, level, mGLFormat, mGLFormat, data.data); // Restore defaults glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); glPixelStorei(GL_PACK_ALIGNMENT, 4); } } }<|endoftext|>
<commit_before>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <commit_msg>fixed test_upnp<commit_after>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); upnp_handler->discover_device(); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "router: " << upnp_handler->router_model() << std::endl; std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Arvid Norberg 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 the author 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. */ #include "test.hpp" #include "libtorrent/utf8.hpp" #include "libtorrent/ConvertUTF.h" #include "setup_transfer.hpp" // for load_file #include "libtorrent/file.hpp" // for combine_path #include <vector> using namespace libtorrent; int test_main() { std::vector<char> utf8_source; error_code ec; load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000); if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value() , ec.message().c_str()); TEST_CHECK(!ec); // test lower level conversions // utf8 -> utf16 -> utf32 -> utf8 { std::vector<UTF16> utf16(utf8_source.size()); UTF8 const* in8 = (UTF8 const*)&utf8_source[0]; UTF16* out16 = &utf16[0]; ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source.size() , &out16, out16 + utf16.size(), strictConversion); TEST_EQUAL(ret, conversionOK); std::vector<UTF32> utf32(utf8_source.size()); UTF16 const* in16 = &utf16[0]; UTF32* out32 = &utf32[0]; ret = ConvertUTF16toUTF32(&in16, out16 , &out32, out32 + utf32.size(), strictConversion); TEST_EQUAL(ret, conversionOK); std::vector<UTF8> utf8(utf8_source.size()); UTF32 const* in32 = &utf32[0]; UTF8* out8 = &utf8[0]; ret = ConvertUTF32toUTF8(&in32, out32 , &out8, out8 + utf8.size(), strictConversion); TEST_EQUAL(ret, conversionOK); TEST_EQUAL(out8 - &utf8[0], utf8_source.size()); TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0])); } // utf8 -> utf32 -> utf16 -> utf8 { std::vector<UTF32> utf32(utf8_source.size()); UTF8 const* in8 = (UTF8 const*)&utf8_source[0]; UTF32* out32 = &utf32[0]; ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source.size() , &out32, out32 + utf32.size(), strictConversion); TEST_EQUAL(ret, conversionOK); std::vector<UTF16> utf16(utf8_source.size()); UTF32 const* in32 = &utf32[0]; UTF16* out16 = &utf16[0]; ret = ConvertUTF32toUTF16(&in32, out32 , &out16, out16 + utf16.size(), strictConversion); TEST_EQUAL(ret, conversionOK); std::vector<UTF8> utf8(utf8_source.size()); UTF16 const* in16 = &utf16[0]; UTF8* out8 = &utf8[0]; ret = ConvertUTF16toUTF8(&in16, out16 , &out8, out8 + utf8.size(), strictConversion); TEST_EQUAL(ret, conversionOK); TEST_EQUAL(out8 - &utf8[0], utf8_source.size()); TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0])); } // test higher level conversions std::string utf8; std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8)); std::wstring wide; utf8_conv_result_t ret = utf8_wchar(utf8, wide); TEST_EQUAL(ret, conversion_ok); std::string identity; ret = wchar_utf8(wide, identity); TEST_EQUAL(ret, conversion_ok); TEST_EQUAL(utf8, identity); return 0; } <commit_msg>extend utf8 unit test<commit_after>/* Copyright (c) 2014, Arvid Norberg 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 the author 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. */ #include "test.hpp" #include "libtorrent/utf8.hpp" #include "libtorrent/ConvertUTF.h" #include "setup_transfer.hpp" // for load_file #include "libtorrent/file.hpp" // for combine_path #include <vector> using namespace libtorrent; void verify_transforms(char const* utf8_source, int utf8_source_len = -1) { if (utf8_source_len == -1) utf8_source_len = strlen(utf8_source); // utf8 -> utf16 -> utf32 -> utf8 { std::vector<UTF16> utf16(utf8_source_len); UTF8 const* in8 = (UTF8 const*)utf8_source; UTF16* out16 = &utf16[0]; ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source_len , &out16, out16 + utf16.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } std::vector<UTF32> utf32(utf8_source_len); UTF16 const* in16 = &utf16[0]; UTF32* out32 = &utf32[0]; ret = ConvertUTF16toUTF32(&in16, out16 , &out32, out32 + utf32.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } std::vector<UTF8> utf8(utf8_source_len); UTF32 const* in32 = &utf32[0]; UTF8* out8 = &utf8[0]; ret = ConvertUTF32toUTF8(&in32, out32 , &out8, out8 + utf8.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } TEST_EQUAL(out8 - &utf8[0], utf8_source_len); TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source)); } // utf8 -> utf32 -> utf16 -> utf8 { std::vector<UTF32> utf32(utf8_source_len); UTF8 const* in8 = (UTF8 const*)utf8_source; UTF32* out32 = &utf32[0]; ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source_len , &out32, out32 + utf32.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } std::vector<UTF16> utf16(utf8_source_len); UTF32 const* in32 = &utf32[0]; UTF16* out16 = &utf16[0]; ret = ConvertUTF32toUTF16(&in32, out32 , &out16, out16 + utf16.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } std::vector<UTF8> utf8(utf8_source_len); UTF16 const* in16 = &utf16[0]; UTF8* out8 = &utf8[0]; ret = ConvertUTF16toUTF8(&in16, out16 , &out8, out8 + utf8.size(), strictConversion); TEST_EQUAL(ret, conversionOK); if (ret != conversionOK && utf8_source_len < 10) { for (char const* i = utf8_source; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } TEST_EQUAL(out8 - &utf8[0], utf8_source_len); TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source)); } } void expect_error(char const* utf8, ConversionResult expect) { UTF8 const* in8 = (UTF8 const*)utf8; std::vector<UTF32> utf32(strlen(utf8)); UTF32* out32 = &utf32[0]; ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + strlen(utf8) , &out32, out32 + utf32.size(), strictConversion); TEST_EQUAL(ret, expect); if (ret != expect) { fprintf(stderr, "%d expected %d\n", ret, expect); for (char const* i = utf8; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } in8 = (UTF8 const*)utf8; std::vector<UTF16> utf16(strlen(utf8)); UTF16* out16 = &utf16[0]; ret = ConvertUTF8toUTF16(&in8, in8 + strlen(utf8) , &out16, out16 + utf16.size(), strictConversion); TEST_EQUAL(ret, expect); if (ret != expect) { fprintf(stderr, "%d expected %d\n", ret, expect); for (char const* i = utf8; *i != 0; ++i) fprintf(stderr, "%x ", UTF8(*i)); } } int test_main() { std::vector<char> utf8_source; error_code ec; load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000); if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value() , ec.message().c_str()); TEST_CHECK(!ec); // test lower level conversions verify_transforms(&utf8_source[0], utf8_source.size()); verify_transforms("\xc3\xb0"); verify_transforms("\xed\x9f\xbf"); verify_transforms("\xee\x80\x80"); verify_transforms("\xef\xbf\xbd"); verify_transforms("\xf4\x8f\xbf\xbf"); verify_transforms("\xf0\x91\x80\x80\x30"); // Unexpected continuation bytes expect_error("\x80", sourceIllegal); expect_error("\xbf", sourceIllegal); // Impossible bytes // The following two bytes cannot appear in a correct UTF-8 string expect_error("\xff", sourceExhausted); expect_error("\xfe", sourceExhausted); expect_error("\xff\xff\xfe\xfe", sourceExhausted); // Examples of an overlong ASCII character expect_error("\xc0\xaf", sourceIllegal); expect_error("\xe0\x80\xaf", sourceIllegal); expect_error("\xf0\x80\x80\xaf", sourceIllegal); expect_error("\xf8\x80\x80\x80\xaf ", sourceIllegal); expect_error("\xfc\x80\x80\x80\x80\xaf", sourceIllegal); // Maximum overlong sequences expect_error("\xc1\xbf", sourceIllegal); expect_error("\xe0\x9f\xbf", sourceIllegal); expect_error("\xf0\x8f\xbf\xbf", sourceIllegal); expect_error("\xf8\x87\xbf\xbf\xbf", sourceIllegal); expect_error("\xfc\x83\xbf\xbf\xbf\xbf", sourceIllegal); // Overlong representation of the NUL character expect_error("\xc0\x80", sourceIllegal); expect_error("\xe0\x80\x80", sourceIllegal); expect_error("\xf0\x80\x80\x80", sourceIllegal); expect_error("\xf8\x80\x80\x80\x80", sourceIllegal); expect_error("\xfc\x80\x80\x80\x80\x80", sourceIllegal); // Single UTF-16 surrogates expect_error("\xed\xa0\x80", sourceIllegal); expect_error("\xed\xad\xbf", sourceIllegal); expect_error("\xed\xae\x80", sourceIllegal); expect_error("\xed\xaf\xbf", sourceIllegal); expect_error("\xed\xb0\x80", sourceIllegal); expect_error("\xed\xbe\x80", sourceIllegal); expect_error("\xed\xbf\xbf", sourceIllegal); // Paired UTF-16 surrogates expect_error("\xed\xa0\x80\xed\xb0\x80", sourceIllegal); expect_error("\xed\xa0\x80\xed\xbf\xbf", sourceIllegal); expect_error("\xed\xad\xbf\xed\xb0\x80", sourceIllegal); expect_error("\xed\xad\xbf\xed\xbf\xbf", sourceIllegal); expect_error("\xed\xae\x80\xed\xb0\x80", sourceIllegal); expect_error("\xed\xae\x80\xed\xbf\xbf", sourceIllegal); expect_error("\xed\xaf\xbf\xed\xb0\x80", sourceIllegal); expect_error("\xed\xaf\xbf\xed\xbf\xbf", sourceIllegal); // test higher level conversions std::string utf8; std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8)); std::wstring wide; utf8_conv_result_t ret = utf8_wchar(utf8, wide); TEST_EQUAL(ret, conversion_ok); std::string identity; ret = wchar_utf8(wide, identity); TEST_EQUAL(ret, conversion_ok); TEST_EQUAL(utf8, identity); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "OrbitClientData/TracepointData.h" #include "OrbitBase/Logging.h" #include "OrbitBase/ThreadConstants.h" using orbit_client_protos::TracepointEventInfo; void TracepointData::EmplaceTracepointEvent(uint64_t time, uint64_t tracepoint_hash, int32_t process_id, int32_t thread_id, int32_t cpu, bool is_same_pid_as_target) { absl::MutexLock lock(&mutex_); num_total_tracepoint_events_++; orbit_client_protos::TracepointEventInfo event; event.set_time(time); CHECK(HasTracepointKey(tracepoint_hash)); event.set_tracepoint_info_key(tracepoint_hash); event.set_tid(thread_id); event.set_pid(process_id); event.set_cpu(cpu); int32_t insertion_thread_id = (is_same_pid_as_target) ? thread_id : orbit_base::kNotTargetProcessTid; auto [event_map_iterator, unused_inserted] = thread_id_to_time_to_tracepoint_.try_emplace(insertion_thread_id); auto [unused_iterator, event_inserted] = event_map_iterator->second.try_emplace(time, std::move(event)); if (!event_inserted) { ERROR( "Tracepoint event was not inserted as there was already an event on this time and " "thread."); } } void TracepointData::ForEachTracepointEvent( const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) const { absl::MutexLock lock(&mutex_); for (auto const& entry : thread_id_to_time_to_tracepoint_) { for (auto const& time_to_tracepoint_event : entry.second) { action(time_to_tracepoint_event.second); } } } namespace { void ForEachTracepointEventInRange( uint64_t min_tick, uint64_t max_tick_exclusive, const std::map<uint64_t, orbit_client_protos::TracepointEventInfo>& time_to_tracepoint_events, const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) { for (auto time_to_tracepoint_event = time_to_tracepoint_events.lower_bound(min_tick); time_to_tracepoint_event->first < max_tick_exclusive && (time_to_tracepoint_event != time_to_tracepoint_events.end()); ++time_to_tracepoint_event) { action(time_to_tracepoint_event->second); } } } // namespace void TracepointData::ForEachTracepointEventOfThreadInTimeRange( int32_t thread_id, uint64_t min_tick, uint64_t max_tick_exclusive, const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) const { absl::MutexLock lock(&mutex_); if (thread_id == orbit_base::kAllThreadsOfAllProcessesTid) { for (const auto& [unused_thread_id, time_to_tracepoint] : thread_id_to_time_to_tracepoint_) { ForEachTracepointEventInRange(min_tick, max_tick_exclusive, time_to_tracepoint, action); } } else if (thread_id == orbit_base::kAllProcessThreadsTid) { for (const auto& [thread_id, time_to_tracepoint] : thread_id_to_time_to_tracepoint_) { if (thread_id == orbit_base::kNotTargetProcessTid) { continue; } ForEachTracepointEventInRange(min_tick, max_tick_exclusive, time_to_tracepoint, action); } } else { const auto& it = thread_id_to_time_to_tracepoint_.find(thread_id); if (it == thread_id_to_time_to_tracepoint_.end()) { return; } ForEachTracepointEventInRange(min_tick, max_tick_exclusive, it->second, action); } } uint32_t TracepointData::GetNumTracepointEventsForThreadId(int32_t thread_id) const { absl::MutexLock lock(&mutex_); if (thread_id == orbit_base::kAllThreadsOfAllProcessesTid) { return num_total_tracepoint_events_; } if (thread_id == orbit_base::kAllProcessThreadsTid) { const auto not_target_process_tracepoints_it = thread_id_to_time_to_tracepoint_.find(orbit_base::kNotTargetProcessTid); if (not_target_process_tracepoints_it == thread_id_to_time_to_tracepoint_.end()) { return num_total_tracepoint_events_; } return num_total_tracepoint_events_ - not_target_process_tracepoints_it->second.size(); } const auto& it = thread_id_to_time_to_tracepoint_.find(thread_id); if (it == thread_id_to_time_to_tracepoint_.end()) { return 0; } return it->second.size(); } bool TracepointData::AddUniqueTracepointInfo(uint64_t key, orbit_grpc_protos::TracepointInfo tracepoint) { absl::MutexLock lock{&unique_tracepoints_mutex_}; auto [unused_it, inserted] = unique_tracepoints_.try_emplace(key, std::move(tracepoint)); return inserted; } orbit_grpc_protos::TracepointInfo TracepointData::GetTracepointInfo(uint64_t hash) const { absl::MutexLock lock{&unique_tracepoints_mutex_}; auto it = unique_tracepoints_.find(hash); if (it != unique_tracepoints_.end()) { return it->second; } return {}; } bool TracepointData::HasTracepointKey(uint64_t key) const { absl::MutexLock lock{&unique_tracepoints_mutex_}; return unique_tracepoints_.contains(key); } void TracepointData::ForEachUniqueTracepointInfo( const std::function<void(const orbit_client_protos::TracepointInfo&)>& action) const { absl::MutexLock lock(&unique_tracepoints_mutex_); for (const auto& it : unique_tracepoints_) { orbit_client_protos::TracepointInfo tracepoint_info; tracepoint_info.set_category(it.second.category()); tracepoint_info.set_name(it.second.name()); tracepoint_info.set_tracepoint_info_key(it.first); action(tracepoint_info); } } <commit_msg>Fix bug in TracepointData.cpp<commit_after>// Copyright (c) 2020 The Orbit 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 "OrbitClientData/TracepointData.h" #include "OrbitBase/Logging.h" #include "OrbitBase/ThreadConstants.h" using orbit_client_protos::TracepointEventInfo; void TracepointData::EmplaceTracepointEvent(uint64_t time, uint64_t tracepoint_hash, int32_t process_id, int32_t thread_id, int32_t cpu, bool is_same_pid_as_target) { absl::MutexLock lock(&mutex_); num_total_tracepoint_events_++; orbit_client_protos::TracepointEventInfo event; event.set_time(time); CHECK(HasTracepointKey(tracepoint_hash)); event.set_tracepoint_info_key(tracepoint_hash); event.set_tid(thread_id); event.set_pid(process_id); event.set_cpu(cpu); int32_t insertion_thread_id = (is_same_pid_as_target) ? thread_id : orbit_base::kNotTargetProcessTid; auto [event_map_iterator, unused_inserted] = thread_id_to_time_to_tracepoint_.try_emplace(insertion_thread_id); auto [unused_iterator, event_inserted] = event_map_iterator->second.try_emplace(time, std::move(event)); if (!event_inserted) { ERROR( "Tracepoint event was not inserted as there was already an event on this time and " "thread."); } } void TracepointData::ForEachTracepointEvent( const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) const { absl::MutexLock lock(&mutex_); for (auto const& entry : thread_id_to_time_to_tracepoint_) { for (auto const& time_to_tracepoint_event : entry.second) { action(time_to_tracepoint_event.second); } } } namespace { void ForEachTracepointEventInRange( uint64_t min_tick, uint64_t max_tick_exclusive, const std::map<uint64_t, orbit_client_protos::TracepointEventInfo>& time_to_tracepoint_events, const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) { for (auto time_to_tracepoint_event = time_to_tracepoint_events.lower_bound(min_tick); time_to_tracepoint_event != time_to_tracepoint_events.end() && time_to_tracepoint_event->first < max_tick_exclusive; ++time_to_tracepoint_event) { action(time_to_tracepoint_event->second); } } } // namespace void TracepointData::ForEachTracepointEventOfThreadInTimeRange( int32_t thread_id, uint64_t min_tick, uint64_t max_tick_exclusive, const std::function<void(const orbit_client_protos::TracepointEventInfo&)>& action) const { absl::MutexLock lock(&mutex_); if (thread_id == orbit_base::kAllThreadsOfAllProcessesTid) { for (const auto& [unused_thread_id, time_to_tracepoint] : thread_id_to_time_to_tracepoint_) { ForEachTracepointEventInRange(min_tick, max_tick_exclusive, time_to_tracepoint, action); } } else if (thread_id == orbit_base::kAllProcessThreadsTid) { for (const auto& [thread_id, time_to_tracepoint] : thread_id_to_time_to_tracepoint_) { if (thread_id == orbit_base::kNotTargetProcessTid) { continue; } ForEachTracepointEventInRange(min_tick, max_tick_exclusive, time_to_tracepoint, action); } } else { const auto& it = thread_id_to_time_to_tracepoint_.find(thread_id); if (it == thread_id_to_time_to_tracepoint_.end()) { return; } ForEachTracepointEventInRange(min_tick, max_tick_exclusive, it->second, action); } } uint32_t TracepointData::GetNumTracepointEventsForThreadId(int32_t thread_id) const { absl::MutexLock lock(&mutex_); if (thread_id == orbit_base::kAllThreadsOfAllProcessesTid) { return num_total_tracepoint_events_; } if (thread_id == orbit_base::kAllProcessThreadsTid) { const auto not_target_process_tracepoints_it = thread_id_to_time_to_tracepoint_.find(orbit_base::kNotTargetProcessTid); if (not_target_process_tracepoints_it == thread_id_to_time_to_tracepoint_.end()) { return num_total_tracepoint_events_; } return num_total_tracepoint_events_ - not_target_process_tracepoints_it->second.size(); } const auto& it = thread_id_to_time_to_tracepoint_.find(thread_id); if (it == thread_id_to_time_to_tracepoint_.end()) { return 0; } return it->second.size(); } bool TracepointData::AddUniqueTracepointInfo(uint64_t key, orbit_grpc_protos::TracepointInfo tracepoint) { absl::MutexLock lock{&unique_tracepoints_mutex_}; auto [unused_it, inserted] = unique_tracepoints_.try_emplace(key, std::move(tracepoint)); return inserted; } orbit_grpc_protos::TracepointInfo TracepointData::GetTracepointInfo(uint64_t hash) const { absl::MutexLock lock{&unique_tracepoints_mutex_}; auto it = unique_tracepoints_.find(hash); if (it != unique_tracepoints_.end()) { return it->second; } return {}; } bool TracepointData::HasTracepointKey(uint64_t key) const { absl::MutexLock lock{&unique_tracepoints_mutex_}; return unique_tracepoints_.contains(key); } void TracepointData::ForEachUniqueTracepointInfo( const std::function<void(const orbit_client_protos::TracepointInfo&)>& action) const { absl::MutexLock lock(&unique_tracepoints_mutex_); for (const auto& it : unique_tracepoints_) { orbit_client_protos::TracepointInfo tracepoint_info; tracepoint_info.set_category(it.second.category()); tracepoint_info.set_name(it.second.name()); tracepoint_info.set_tracepoint_info_key(it.first); action(tracepoint_info); } } <|endoftext|>
<commit_before>/** * Copyright (C) 2016 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_maker_selection_tree.h" #include "../../core/model/bson/repo_node_reference.h" #include "../modeloptimizer/repo_optimizer_ifc.h" using namespace repo::manipulator::modelutility; const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState"; const static std::string REPO_VISIBILITY_STATE_SHOW = "visible"; const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible"; const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible"; SelectionTreeMaker::SelectionTreeMaker( const repo::core::model::RepoScene *scene) : scene(scene) { } repo::lib::PropertyTree SelectionTreeMaker::generatePTree( const repo::core::model::RepoNode *currentNode, std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps, std::vector<std::pair<std::string, std::string>> &sharedIDToUniqueID, repo::lib::PropertyTree &idToMeshesTree, const std::string &currentPath, bool &hiddenOnDefault, std::vector<std::string> &hiddenNode, std::vector<std::string> &meshIds) const { repo::lib::PropertyTree tree; if (currentNode) { std::string idString = currentNode->getUniqueID().toString(); repoInfo << "Processing : " << idString << "[" << currentNode->getName() << "]"; repo::lib::RepoUUID sharedID = currentNode->getSharedID(); std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString; auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID); std::vector<repo::lib::PropertyTree> childrenTrees; std::vector<repo::core::model::RepoNode*> childrenTypes[2]; std::vector<repo::lib::RepoUUID> metaIDs; for (const auto &child : children) { if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA) { metaIDs.push_back(child->getUniqueID()); } else { //Ensure IFC Space (if any) are put into the tree first. if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos) childrenTypes[0].push_back(child); else childrenTypes[1].push_back(child); } } bool hasHiddenChildren = false; for (const auto &childrenSet : childrenTypes) { for (const auto &child : childrenSet) { if (child) { switch (child->getTypeAsEnum()) { case repo::core::model::NodeType::MESH: meshIds.push_back(child->getUniqueID().toString()); case repo::core::model::NodeType::TRANSFORMATION: case repo::core::model::NodeType::CAMERA: case repo::core::model::NodeType::REFERENCE: { bool hiddenChild = false; std::vector<std::string> childrenMeshes; repoInfo << "Recursing with kid: " << "[" << child->getName() << "] Kid of " << idString; childrenTrees.push_back(generatePTree(child, idMaps, sharedIDToUniqueID, idToMeshesTree, childPath, hiddenChild, hiddenNode, childrenMeshes)); hasHiddenChildren = hasHiddenChildren || hiddenChild; meshIds.insert(meshIds.end(), childrenMeshes.begin(), childrenMeshes.end()); } } } else { repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } } } std::string name = currentNode->getName(); if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum()) { if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode)) { auto refDb = refNode->getDatabaseName(); name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName(); } } tree.addToTree("account", scene->getDatabaseName()); tree.addToTree("project", scene->getProjectName()); tree.addToTree("type", currentNode->getType()); if (!name.empty()) tree.addToTree("name", name); tree.addToTree("path", childPath); tree.addToTree("_id", idString); tree.addToTree("shared_id", sharedID.toString()); tree.addToTree("children", childrenTrees); if (metaIDs.size()) tree.addToTree("meta", metaIDs); if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos && currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN); hiddenOnDefault = true; hiddenNode.push_back(idString); } else if (hiddenOnDefault || hasHiddenChildren) { hiddenOnDefault = (hiddenOnDefault || hasHiddenChildren); tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN); } else { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW); } idMaps[idString] = { name, childPath }; sharedIDToUniqueID.push_back({ idString, sharedID.toString() }); if (meshIds.size()) idToMeshesTree.addToTree(idString, meshIds); else if (currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH){ std::vector<repo::lib::RepoUUID> self = { currentNode->getUniqueID() }; idToMeshesTree.addToTree(idString, self); } } else { repoDebug << "Null pointer at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } return tree; } std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const { auto trees = getSelectionTreeAsPropertyTree(); std::map<std::string, std::vector<uint8_t>> buffer; for (const auto &tree : trees) { std::stringstream ss; tree.second.write_json(ss); std::string jsonString = ss.str(); if (!jsonString.empty()) { size_t byteLength = jsonString.size() * sizeof(*jsonString.data()); buffer[tree.first] = std::vector<uint8_t>(); buffer[tree.first].resize(byteLength); memcpy(buffer[tree.first].data(), jsonString.data(), byteLength); } else { repoError << "Failed to write selection tree into the buffer: JSON string is empty."; } } return buffer; } std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const { std::map<std::string, repo::lib::PropertyTree> trees; repo::core::model::RepoNode *root; if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT))) { std::unordered_map< std::string, std::pair<std::string, std::string>> map; std::vector<std::string> hiddenNodes, childrenMeshes; bool dummy = false; repo::lib::PropertyTree tree, settingsTree, treePathTree, shareIDToUniqueIDMap, idToMeshes; std::vector<std::pair<std::string, std::string>> sharedIDToUniqueID; tree.mergeSubTree("nodes", generatePTree(root, map, sharedIDToUniqueID, idToMeshes, "", dummy, hiddenNodes, childrenMeshes)); for (const auto pair : map) { //if there's an entry in maps it must have an entry in paths tree.addToTree("idToName." + pair.first, pair.second.first); treePathTree.addToTree("idToPath." + pair.first, pair.second.second); } for (const auto pair : sharedIDToUniqueID) { shareIDToUniqueIDMap.addToTree("idMap." + pair.first, pair.second); } trees["fulltree.json"] = tree; trees["tree_path.json"] = treePathTree; trees["idMap.json"] = shareIDToUniqueIDMap; trees["idToMeshes.json"] = idToMeshes; if (hiddenNodes.size()) { settingsTree.addToTree("hiddenNodes", hiddenNodes); trees["modelProperties.json"] = settingsTree; } } else { repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded"; } return trees; } SelectionTreeMaker::~SelectionTreeMaker() { }<commit_msg>ISSUE #223 remove debug<commit_after>/** * Copyright (C) 2016 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_maker_selection_tree.h" #include "../../core/model/bson/repo_node_reference.h" #include "../modeloptimizer/repo_optimizer_ifc.h" using namespace repo::manipulator::modelutility; const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState"; const static std::string REPO_VISIBILITY_STATE_SHOW = "visible"; const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible"; const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible"; SelectionTreeMaker::SelectionTreeMaker( const repo::core::model::RepoScene *scene) : scene(scene) { } repo::lib::PropertyTree SelectionTreeMaker::generatePTree( const repo::core::model::RepoNode *currentNode, std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps, std::vector<std::pair<std::string, std::string>> &sharedIDToUniqueID, repo::lib::PropertyTree &idToMeshesTree, const std::string &currentPath, bool &hiddenOnDefault, std::vector<std::string> &hiddenNode, std::vector<std::string> &meshIds) const { repo::lib::PropertyTree tree; if (currentNode) { std::string idString = currentNode->getUniqueID().toString(); repo::lib::RepoUUID sharedID = currentNode->getSharedID(); std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString; auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID); std::vector<repo::lib::PropertyTree> childrenTrees; std::vector<repo::core::model::RepoNode*> childrenTypes[2]; std::vector<repo::lib::RepoUUID> metaIDs; for (const auto &child : children) { if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA) { metaIDs.push_back(child->getUniqueID()); } else { //Ensure IFC Space (if any) are put into the tree first. if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos) childrenTypes[0].push_back(child); else childrenTypes[1].push_back(child); } } bool hasHiddenChildren = false; for (const auto &childrenSet : childrenTypes) { for (const auto &child : childrenSet) { if (child) { switch (child->getTypeAsEnum()) { case repo::core::model::NodeType::MESH: meshIds.push_back(child->getUniqueID().toString()); case repo::core::model::NodeType::TRANSFORMATION: case repo::core::model::NodeType::CAMERA: case repo::core::model::NodeType::REFERENCE: { bool hiddenChild = false; std::vector<std::string> childrenMeshes; childrenTrees.push_back(generatePTree(child, idMaps, sharedIDToUniqueID, idToMeshesTree, childPath, hiddenChild, hiddenNode, childrenMeshes)); hasHiddenChildren = hasHiddenChildren || hiddenChild; meshIds.insert(meshIds.end(), childrenMeshes.begin(), childrenMeshes.end()); } } } else { repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } } } std::string name = currentNode->getName(); if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum()) { if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode)) { auto refDb = refNode->getDatabaseName(); name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName(); } } tree.addToTree("account", scene->getDatabaseName()); tree.addToTree("project", scene->getProjectName()); tree.addToTree("type", currentNode->getType()); if (!name.empty()) tree.addToTree("name", name); tree.addToTree("path", childPath); tree.addToTree("_id", idString); tree.addToTree("shared_id", sharedID.toString()); tree.addToTree("children", childrenTrees); if (metaIDs.size()) tree.addToTree("meta", metaIDs); if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos && currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN); hiddenOnDefault = true; hiddenNode.push_back(idString); } else if (hiddenOnDefault || hasHiddenChildren) { hiddenOnDefault = (hiddenOnDefault || hasHiddenChildren); tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN); } else { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW); } idMaps[idString] = { name, childPath }; sharedIDToUniqueID.push_back({ idString, sharedID.toString() }); if (meshIds.size()) idToMeshesTree.addToTree(idString, meshIds); else if (currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH){ std::vector<repo::lib::RepoUUID> self = { currentNode->getUniqueID() }; idToMeshesTree.addToTree(idString, self); } } else { repoDebug << "Null pointer at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } return tree; } std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const { auto trees = getSelectionTreeAsPropertyTree(); std::map<std::string, std::vector<uint8_t>> buffer; for (const auto &tree : trees) { std::stringstream ss; tree.second.write_json(ss); std::string jsonString = ss.str(); if (!jsonString.empty()) { size_t byteLength = jsonString.size() * sizeof(*jsonString.data()); buffer[tree.first] = std::vector<uint8_t>(); buffer[tree.first].resize(byteLength); memcpy(buffer[tree.first].data(), jsonString.data(), byteLength); } else { repoError << "Failed to write selection tree into the buffer: JSON string is empty."; } } return buffer; } std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const { std::map<std::string, repo::lib::PropertyTree> trees; repo::core::model::RepoNode *root; if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT))) { std::unordered_map< std::string, std::pair<std::string, std::string>> map; std::vector<std::string> hiddenNodes, childrenMeshes; bool dummy = false; repo::lib::PropertyTree tree, settingsTree, treePathTree, shareIDToUniqueIDMap, idToMeshes; std::vector<std::pair<std::string, std::string>> sharedIDToUniqueID; tree.mergeSubTree("nodes", generatePTree(root, map, sharedIDToUniqueID, idToMeshes, "", dummy, hiddenNodes, childrenMeshes)); for (const auto pair : map) { //if there's an entry in maps it must have an entry in paths tree.addToTree("idToName." + pair.first, pair.second.first); treePathTree.addToTree("idToPath." + pair.first, pair.second.second); } for (const auto pair : sharedIDToUniqueID) { shareIDToUniqueIDMap.addToTree("idMap." + pair.first, pair.second); } trees["fulltree.json"] = tree; trees["tree_path.json"] = treePathTree; trees["idMap.json"] = shareIDToUniqueIDMap; trees["idToMeshes.json"] = idToMeshes; if (hiddenNodes.size()) { settingsTree.addToTree("hiddenNodes", hiddenNodes); trees["modelProperties.json"] = settingsTree; } } else { repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded"; } return trees; } SelectionTreeMaker::~SelectionTreeMaker() { }<|endoftext|>
<commit_before>// spatial_type.cpp // #include "common/common.h" #include "spatial_type.h" #include "page_info.h" namespace sdl { namespace db { namespace { namespace hilbert { //FIXME: make static array to map (X,Y) <=> distance //https://en.wikipedia.org/wiki/Hilbert_curve // The following code performs the mappings in both directions, // using iteration and bit operations rather than recursion. // It assumes a square divided into n by n cells, for n a power of 2, // with integer coordinates, with (0,0) in the lower left corner, (n-1,n-1) in the upper right corner, // and a distance d that starts at 0 in the lower left corner and goes to n^2-1 in the lower-right corner. //rotate/flip a quadrant appropriately void rot(const int n, int & x, int & y, const int rx, const int ry) { SDL_ASSERT(is_power_two(n)); if (ry == 0) { if (rx == 1) { x = n - 1 - x; y = n - 1 - y; } //Swap x and y auto t = x; x = y; y = t; } } //convert (x,y) to d int xy2d(const int n, int x, int y) { SDL_ASSERT(is_power_two(n)); SDL_ASSERT(x < n); SDL_ASSERT(y < n); int rx, ry, d = 0; for (int s = n/2; s > 0; s /= 2) { rx = (x & s) > 0; ry = (y & s) > 0; d += s * s * ((3 * rx) ^ ry); rot(s, x, y, rx, ry); } SDL_ASSERT((d >= 0) && (d < (n * n))); SDL_ASSERT(d < 256); // to be compatible with spatial_cell::id_type return d; } //convert d to (x,y) void d2xy(const int n, const int d, int & x, int & y) { SDL_ASSERT(is_power_two(n)); SDL_ASSERT((d >= 0) && (d < (n * n))); int rx, ry, t = d; x = y = 0; for (int s = 1; s < n; s *= 2) { rx = 1 & (t / 2); ry = 1 & (t ^ rx); rot(s, x, y, rx, ry); x += s * rx; y += s * ry; t /= 4; } SDL_ASSERT((x >= 0) && (x < n)); SDL_ASSERT((y >= 0) && (y < n)); } } // hilbert point_t<double> project_globe(spatial_point const & p) { SDL_ASSERT(p.is_valid()); point_t<double> p1, p2, p3; double meridian, sector; p3.X = 0.5; if (p.latitude < 0) { // south hemisphere p3.Y = 0.25; if (p.longitude >= 0) { // north-east if (p.longitude <= 45) { p1 = { 1, 0.25 }; p2 = { 1, 0 }; meridian = 0; sector = 45; } else if (p.longitude <= 135) { p1 = { 1, 0 }; p2 = { 0, 0 }; meridian = 45; sector = 90; } else { SDL_ASSERT(p.longitude <= 180); p1 = { 0, 0 }; p2 = { 0, 0.25 }; meridian = 135; sector = 45; } } else { // north-west if (p.longitude >= -45) { p1 = { 1, 0.5 }; p2 = { 1, 0.25 }; meridian = -45; sector = 45; } else if (p.longitude >= -135) { p1 = { 0, 0.5 }; p2 = { 1, 0.5 }; meridian = -135; sector = 90; } else { SDL_ASSERT(-180 <= p.longitude); p1 = { 0, 0.25 }; p2 = { 0, 0.5 }; meridian = -180; sector = 45; } } } else { // north hemisphere p3.Y = 0.75; if (p.longitude >= 0) { // south-east if (p.longitude <= 45) { p1 = { 1, 0.75 }; p2 = { 1, 1 }; meridian = 0; sector = 45; } else if (p.longitude <= 135) { p1 = { 1, 1 }; p2 = { 0, 1 }; meridian = 45; sector = 90; } else { SDL_ASSERT(p.longitude <= 180); p1 = { 0, 1 }; p2 = { 0, 0.75 }; meridian = 135; sector = 45; } } else { // south-west if (p.longitude >= -45) { p1 = { 1, 0.5 }; p2 = { 1, 0.75 }; meridian = -45; sector = 45; } else if (p.longitude >= -135) { p1 = { 0, 0.5 }; p2 = { 1, 0.5 }; meridian = -135; sector = 90; } else { SDL_ASSERT(-180 <= p.longitude); p1 = { 0, 0.75 }; p2 = { 0, 0.5 }; meridian = -180; sector = 45; } } } SDL_ASSERT(p.longitude >= meridian); SDL_ASSERT((p.longitude - meridian) <= sector); double const move_longitude = (p.longitude - meridian) / sector; SDL_ASSERT(move_longitude <= 1); const point_t<double> base = { p1.X + (p2.X - p1.X) * move_longitude, p1.Y + (p2.Y - p1.Y) * move_longitude }; double const move_latitude = std::fabs(p.latitude) / 90.0; const point_t<double> result = { base.X + (p3.X - base.X) * move_latitude, base.Y + (p3.Y - base.Y) * move_latitude }; SDL_ASSERT((result.X >= 0) && (result.Y >= 0)); SDL_ASSERT((result.X <= 1) && (result.Y <= 1)); return result; } } // namespace point_t<int> spatial_transform::make_XY(spatial_cell const & p, spatial_grid::grid_size const grid) { point_t<int> xy; hilbert::d2xy(grid, p[0], xy.X, xy.Y); return xy; } vector_cell spatial_transform::make_cell(spatial_point const & p, spatial_grid const & grid) { const point_t<double> globe = project_globe(p); const int g_0 = grid[0]; const int X = a_min<int>(static_cast<int>(globe.X * g_0), g_0 - 1); const int Y = a_min<int>(static_cast<int>(globe.Y * g_0), g_0 - 1); const int dist_0 = hilbert::xy2d(g_0, X, Y); vector_cell vc(1); vc[0][0] = static_cast<spatial_cell::id_type>(dist_0); vc[0].data.last = spatial_cell::last_4; //FIXME: to be tested return vc; } spatial_point spatial_transform::make_point(spatial_cell const & p, spatial_grid const & grid) { const int g_0 = grid[0]; const int g_1 = grid[1]; const int g_2 = grid[2]; const int g_3 = grid[3]; return {}; } } // db } // sdl #if SDL_DEBUG namespace sdl { namespace db { namespace { class unit_test { public: unit_test() { A_STATIC_ASSERT_IS_POD(spatial_cell); A_STATIC_ASSERT_IS_POD(spatial_point); A_STATIC_ASSERT_IS_POD(point_t<double>); static_assert(sizeof(spatial_cell) == 5, ""); static_assert(sizeof(spatial_point) == 16, ""); static_assert(is_power_2<1>::value, ""); static_assert(is_power_2<spatial_grid::LOW>::value, ""); static_assert(is_power_2<spatial_grid::MEDIUM>::value, ""); static_assert(is_power_2<spatial_grid::HIGH>::value, ""); SDL_ASSERT(is_power_two(spatial_grid::LOW)); SDL_ASSERT(is_power_two(spatial_grid::MEDIUM)); SDL_ASSERT(is_power_two(spatial_grid::HIGH)); { spatial_cell x{}; spatial_cell y{}; SDL_ASSERT(!(x < y)); } test_hilbert(); test_spatial(); } private: static void trace_hilbert(const int n) { for (int y = 0; y < n; ++y) { std::cout << y; for (int x = 0; x < n; ++x) { const int d = hilbert::xy2d(n, x, y); std::cout << "," << d; } std::cout << std::endl; } } static void test_hilbert(const int n) { for (int d = 0; d < (n * n); ++d) { int x = 0, y = 0; hilbert::d2xy(n, d, x, y); SDL_ASSERT(d == hilbert::xy2d(n, x, y)); //SDL_TRACE("d2xy: n = ", n, " d = ", d, " x = ", x, " y = ", y); } } static void test_hilbert() { spatial_grid::grid_size const sz = spatial_grid::HIGH; for (int i = 0; (1 << i) <= sz; ++i) { test_hilbert(1 << i); } } static void trace_cell(const vector_cell & vc) { SDL_ASSERT(!vc.empty()); for (auto & v : vc) { SDL_TRACE(to_string::type(v)); } } static void test_spatial(const spatial_grid & grid) { if (0) { spatial_point p1{}, p2{}; for (int i = 0; i <= 4; ++i) { for (int j = 0; j <= 2; ++j) { p1.longitude = 45 * i; p2.longitude = -45 * i; p1.latitude = 45 * j; p2.latitude = -45 * j; project_globe(p1); project_globe(p2); spatial_transform::make_cell(p1, spatial_grid(spatial_grid::HIGH)); }} } if (0) { static const spatial_point test[] = { // latitude, longitude { 0, 0 }, { 0, 135 }, { 0, 90 }, { 90, 0 }, { -90, 0 }, { 0, -45 }, { 45, 45 }, { 0, 180 }, { 0, -180 }, { 0, 131 }, { 0, 134 }, { 0, 144 }, { 0, 145 }, { 0, 166 }, { 0, -86 }, // cell_id = 128-234-255-15-4 { 55.7975, 49.2194 }, // cell_id = 157-178-149-55-4 { 47.2629, 39.7111 }, // cell_id = 163-78-72-221-4 { 47.261, 39.7068 }, // cell_id = 163-78-72-223-4 { 55.7831, 37.3567 }, // cell_id = 156-38-25-118-4 }; for (size_t i = 0; i < A_ARRAY_SIZE(test); ++i) { std::cout << i << ": " << to_string::type(test[i]) << " => "; trace_cell(spatial_transform::make_cell(test[i], grid)); } SDL_TRACE(); } } static void test_spatial() { test_spatial(spatial_grid(spatial_grid::HIGH)); } }; static unit_test s_test; } } // db } // sdl #endif //#if SV_DEBUG <commit_msg>todo: project_globe<commit_after>// spatial_type.cpp // #include "common/common.h" #include "spatial_type.h" #include "page_info.h" namespace sdl { namespace db { namespace { namespace hilbert { //FIXME: make static array to map (X,Y) <=> distance //https://en.wikipedia.org/wiki/Hilbert_curve // The following code performs the mappings in both directions, // using iteration and bit operations rather than recursion. // It assumes a square divided into n by n cells, for n a power of 2, // with integer coordinates, with (0,0) in the lower left corner, (n-1,n-1) in the upper right corner, // and a distance d that starts at 0 in the lower left corner and goes to n^2-1 in the lower-right corner. //rotate/flip a quadrant appropriately void rot(const int n, int & x, int & y, const int rx, const int ry) { SDL_ASSERT(is_power_two(n)); if (ry == 0) { if (rx == 1) { x = n - 1 - x; y = n - 1 - y; } //Swap x and y auto t = x; x = y; y = t; } } //convert (x,y) to d int xy2d(const int n, int x, int y) { SDL_ASSERT(is_power_two(n)); SDL_ASSERT(x < n); SDL_ASSERT(y < n); int rx, ry, d = 0; for (int s = n/2; s > 0; s /= 2) { rx = (x & s) > 0; ry = (y & s) > 0; d += s * s * ((3 * rx) ^ ry); rot(s, x, y, rx, ry); } SDL_ASSERT((d >= 0) && (d < (n * n))); SDL_ASSERT(d < 256); // to be compatible with spatial_cell::id_type return d; } //convert d to (x,y) void d2xy(const int n, const int d, int & x, int & y) { SDL_ASSERT(is_power_two(n)); SDL_ASSERT((d >= 0) && (d < (n * n))); int rx, ry, t = d; x = y = 0; for (int s = 1; s < n; s *= 2) { rx = 1 & (t / 2); ry = 1 & (t ^ rx); rot(s, x, y, rx, ry); x += s * rx; y += s * ry; t /= 4; } SDL_ASSERT((x >= 0) && (x < n)); SDL_ASSERT((y >= 0) && (y < n)); } } // hilbert double longitude_distance(double const left, double const right) { SDL_ASSERT(std::fabs(left) <= 180); SDL_ASSERT(std::fabs(right) <= 180); if (left >= 0) { if (right >= 0) { SDL_ASSERT(right >= left); return right - left; } return (right + 180) + (180 - left); } else { if (right < 0) { SDL_ASSERT(right >= left); return right - left; } return right - left; } } point_t<double> project_globe(spatial_point const & s) { SDL_ASSERT(s.is_valid()); const bool north_hemisphere = (s.latitude >= 0); const bool east_hemisphere = (s.longitude >= 0); point_t<double> p1, p2, p3; spatial_point s1, s2, s3; s1.latitude = s2.latitude = 0; s3.latitude = north_hemisphere ? 90 : -90; if (north_hemisphere) { p3 = { 0.5, 0.75 }; if (east_hemisphere) { if (s.longitude <= 45) { p1 = { 1, 0.5 }; p2 = { 1, 1 }; s1.longitude = -45; s2.longitude = 45; s3.longitude = 0; } else if (s.longitude <= 135) { p1 = { 1, 1 }; p2 = { 0, 1 }; s1.longitude = 45; s2.longitude = 135; s3.longitude = 90; } else { SDL_ASSERT(s.longitude <= 180); p1 = { 0, 1 }; p2 = { 0, 0.5 }; s1.longitude = 135; s2.longitude = -135; s3.longitude = 180; } } else { // west hemisphere SDL_ASSERT(s.longitude < 0); if (s.longitude >= -45) { p1 = { 1, 0.5 }; p2 = { 1, 1 }; s1.longitude = -45; s2.longitude = 45; s3.longitude = 0; } else if (s.longitude >= -135) { p1 = { 0, 0.5 }; p2 = { 1, 0.5 }; s1.longitude = -135; s2.longitude = -45; s3.longitude = -90; } else { SDL_ASSERT(s.longitude >= -180); p1 = { 0, 1 }; p2 = { 0, 0.5 }; s1.longitude = 135; s2.longitude = -135; s3.longitude = -180; } } SDL_ASSERT(p1.Y >= 0.5); SDL_ASSERT(p2.Y >= 0.5); } else { // south hemisphere SDL_ASSERT(s.latitude < 0); p3 = { 0.5, 0.25 }; if (east_hemisphere) { if (s.longitude <= 45) { p1 = { 1, 0.5 }; p2 = { 1, 0 }; s1.longitude = -45; s2.longitude = 45; s3.longitude = 0; } else if (s.longitude <= 135) { p1 = { 1, 0 }; p2 = { 0, 0 }; s1.longitude = 45; s2.longitude = 135; s3.longitude = 90; } else { SDL_ASSERT(s.longitude <= 180); p1 = { 0, 0 }; p2 = { 0, 0.5 }; s1.longitude = 135; s2.longitude = -135; s3.longitude = 180; } } else { // west hemisphere SDL_ASSERT(s.longitude < 0); if (s.longitude >= -45) { p1 = { 1, 0.5 }; p2 = { 1, 0 }; s1.longitude = -45; s2.longitude = 45; s3.longitude = 0; } else if (s.longitude >= -135) { p1 = { 0, 0.5 }; p2 = { 1, 0.5 }; s1.longitude = -135; s2.longitude = -45; s3.longitude = -90; } else { SDL_ASSERT(s.longitude >= -180); p1 = { 0, 0 }; p2 = { 0, 0.5 }; s1.longitude = 135; s2.longitude = -135; s3.longitude = -180; } } SDL_ASSERT(p1.Y <= 0.5); SDL_ASSERT(p2.Y <= 0.5); } SDL_ASSERT(!east_hemisphere || (s3.longitude >= 0)); SDL_ASSERT(east_hemisphere || (s3.longitude <= 0)); SDL_ASSERT(fequal(longitude_distance(s1.longitude, s2.longitude), 90.0)); SDL_ASSERT(std::fabs(s.latitude - s3.latitude) <= 90); //https://en.wikipedia.org/wiki/Barycentric_coordinate_system return{}; } } // namespace point_t<int> spatial_transform::make_XY(spatial_cell const & p, spatial_grid::grid_size const grid) { point_t<int> xy; hilbert::d2xy(grid, p[0], xy.X, xy.Y); return xy; } vector_cell spatial_transform::make_cell(spatial_point const & p, spatial_grid const & grid) { const point_t<double> globe = project_globe(p); const int g_0 = grid[0]; const point_t<double> d = { globe.X * g_0, globe.Y * g_0 }; const int X = a_min<int>(static_cast<int>(d.X), g_0 - 1); const int Y = a_min<int>(static_cast<int>(d.Y), g_0 - 1); const int dist_0 = hilbert::xy2d(g_0, X, Y); vector_cell vc(1); vc[0][0] = static_cast<spatial_cell::id_type>(dist_0); vc[0].data.last = spatial_cell::last_4; //FIXME: to be tested return vc; } spatial_point spatial_transform::make_point(spatial_cell const & p, spatial_grid const & grid) { const int g_0 = grid[0]; const int g_1 = grid[1]; const int g_2 = grid[2]; const int g_3 = grid[3]; return {}; } } // db } // sdl #if SDL_DEBUG namespace sdl { namespace db { namespace { class unit_test { public: unit_test() { A_STATIC_ASSERT_IS_POD(spatial_cell); A_STATIC_ASSERT_IS_POD(spatial_point); A_STATIC_ASSERT_IS_POD(point_t<double>); static_assert(sizeof(spatial_cell) == 5, ""); static_assert(sizeof(spatial_point) == 16, ""); static_assert(is_power_2<1>::value, ""); static_assert(is_power_2<spatial_grid::LOW>::value, ""); static_assert(is_power_2<spatial_grid::MEDIUM>::value, ""); static_assert(is_power_2<spatial_grid::HIGH>::value, ""); SDL_ASSERT(is_power_two(spatial_grid::LOW)); SDL_ASSERT(is_power_two(spatial_grid::MEDIUM)); SDL_ASSERT(is_power_two(spatial_grid::HIGH)); { spatial_cell x{}; spatial_cell y{}; SDL_ASSERT(!(x < y)); } test_hilbert(); test_spatial(); } private: static void trace_hilbert(const int n) { for (int y = 0; y < n; ++y) { std::cout << y; for (int x = 0; x < n; ++x) { const int d = hilbert::xy2d(n, x, y); std::cout << "," << d; } std::cout << std::endl; } } static void test_hilbert(const int n) { for (int d = 0; d < (n * n); ++d) { int x = 0, y = 0; hilbert::d2xy(n, d, x, y); SDL_ASSERT(d == hilbert::xy2d(n, x, y)); //SDL_TRACE("d2xy: n = ", n, " d = ", d, " x = ", x, " y = ", y); } } static void test_hilbert() { spatial_grid::grid_size const sz = spatial_grid::HIGH; for (int i = 0; (1 << i) <= sz; ++i) { test_hilbert(1 << i); } } static void trace_cell(const vector_cell & vc) { //SDL_ASSERT(!vc.empty()); for (auto & v : vc) { SDL_TRACE(to_string::type(v)); } } static void test_spatial(const spatial_grid & grid) { if (1) { spatial_point p1{}, p2{}; for (int i = 0; i <= 4; ++i) { for (int j = 0; j <= 2; ++j) { p1.longitude = 45 * i; p2.longitude = -45 * i; p1.latitude = 45 * j; p2.latitude = -45 * j; project_globe(p1); project_globe(p2); spatial_transform::make_cell(p1, spatial_grid(spatial_grid::LOW)); spatial_transform::make_cell(p1, spatial_grid(spatial_grid::MEDIUM)); spatial_transform::make_cell(p1, spatial_grid(spatial_grid::HIGH)); }} } if (1) { static const spatial_point test[] = { // latitude, longitude { 0, 0 }, { 0, 135 }, { 0, 90 }, { 90, 0 }, { -90, 0 }, { 0, -45 }, { 45, 45 }, { 0, 180 }, { 0, -180 }, { 0, 131 }, { 0, 134 }, { 0, 144 }, { 0, 145 }, { 0, 166 }, { 48.7139, 44.4984 }, // cell_id = 156-163-67-177-4 { 55.7975, 49.2194 }, // cell_id = 157-178-149-55-4 { 47.2629, 39.7111 }, // cell_id = 163-78-72-221-4 { 47.261, 39.7068 }, // cell_id = 163-78-72-223-4 { 55.7831, 37.3567 }, // cell_id = 156-38-25-118-4 { 0, -86 }, // cell_id = 128-234-255-15-4 { 45, -135 }, // cell_id = 70-170-170-170-4 { 45, 135 }, // cell_id = 91-255-255-255-4 { 45, 0 }, // cell_id = 160-236-255-239-4 | 181-153-170-154-4 { 45, -45 }, // cell_id = 134-170-170-170-4 | 137-255-255-255-4 | 182-0-0-0-4 | 185-85-85-85-4 }; for (size_t i = 0; i < A_ARRAY_SIZE(test); ++i) { std::cout << i << ": " << to_string::type(test[i]) << " => "; trace_cell(spatial_transform::make_cell(test[i], grid)); } SDL_TRACE(); } } static void test_spatial() { test_spatial(spatial_grid(spatial_grid::HIGH)); } }; static unit_test s_test; } } // db } // sdl #endif //#if SV_DEBUG <|endoftext|>
<commit_before>#include "rltk.hpp" #include "texture.hpp" #include <memory> namespace rltk { std::unique_ptr<sf::RenderWindow> main_window; std::unique_ptr<virtual_terminal> root_console; sf::RenderWindow * get_window() { return main_window.get(); } virtual_terminal * get_root_console() { return root_console.get(); } void init(const int window_width, const int window_height, const std::string window_title) { main_window = std::make_unique<sf::RenderWindow>(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title); main_window->setVerticalSyncEnabled(true); } void run(std::function<void(double)> on_tick, const std::string root_console_font) { root_console = std::make_unique<virtual_terminal>(root_console_font, 0, 0); sf::Vector2u size_pixels = main_window->getSize(); root_console->resize_pixels(size_pixels.x, size_pixels.y); double duration_ms = 0.0; while (main_window->isOpen()) { clock_t start_time = clock(); sf::Event event; while (main_window->pollEvent(event)) { if (event.type == sf::Event::Closed) { main_window->close(); } } main_window->clear(); root_console->clear(); on_tick(duration_ms); root_console->render(*main_window); main_window->display(); duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC; } } } <commit_msg>Support window resize.<commit_after>#include "rltk.hpp" #include "texture.hpp" #include <memory> namespace rltk { std::unique_ptr<sf::RenderWindow> main_window; std::unique_ptr<virtual_terminal> root_console; sf::RenderWindow * get_window() { return main_window.get(); } virtual_terminal * get_root_console() { return root_console.get(); } void init(const int window_width, const int window_height, const std::string window_title) { main_window = std::make_unique<sf::RenderWindow>(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title); main_window->setVerticalSyncEnabled(true); } void run(std::function<void(double)> on_tick, const std::string root_console_font) { root_console = std::make_unique<virtual_terminal>(root_console_font, 0, 0); sf::Vector2u size_pixels = main_window->getSize(); root_console->resize_pixels(size_pixels.x, size_pixels.y); double duration_ms = 0.0; while (main_window->isOpen()) { clock_t start_time = clock(); sf::Event event; while (main_window->pollEvent(event)) { if (event.type == sf::Event::Closed) { main_window->close(); } else if (event.type == sf::Event::Resized) { sf::Vector2u size_pixels = main_window->getSize(); root_console->resize_pixels(event.size.width, event.size.height); main_window->setView(sf::View(sf::FloatRect(0.f, 0.f, event.size.width, event.size.height))); } } main_window->clear(); root_console->clear(); on_tick(duration_ms); root_console->render(*main_window); main_window->display(); duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC; } } } <|endoftext|>
<commit_before>#include "udpping.h" #include <time.h> #include <windows.h> #include <mswsock.h> #include <Mstcpip.h> #include <pcap.h> bool getAddress(const QString &address, sockaddr_any *addr); PingProbe receiveLoop(pcap_t *capture, PingProbe probe, sockaddr_any destination); UdpPing::UdpPing(QObject *parent) : Measurement(parent), currentStatus(Unknown) { WSADATA wsaData; // Initialize Winsock if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { // TODO: emit error } } UdpPing::~UdpPing() { WSACleanup(); } Measurement::Status UdpPing::status() const { return currentStatus; } void UdpPing::setStatus(Status status) { if (currentStatus != status) { currentStatus = status; emit statusChanged(status); } } bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition) { Q_UNUSED(networkManager); pcap_if_t *alldevs; char errbuf[PCAP_ERRBUF_SIZE] = ""; char source[PCAP_BUF_SIZE] = ""; char address[16] = ""; sockaddr_any dst_addr; unsigned long netmask; struct bpf_program fcode; definition = measurementDefinition.dynamicCast<UdpPingDefinition>(); memset(&dst_addr, 0, sizeof(dst_addr)); // translate domain name to IP address getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); strncpy(address, inet_ntoa(dst_addr.sin.sin_addr), sizeof(address)); if (pcap_createsrcstr(source, PCAP_SRC_IFLOCAL, address, NULL, NULL, errbuf) != 0) { emit error("pcap_createsrcstr: " + QString(errbuf)); return false; } if (pcap_findalldevs_ex(source, NULL, &alldevs, errbuf) != 0) { emit error("pcap_findalldevs_ex: " + QString(errbuf)); return false; } // take the first device m_device = alldevs; if (m_device == NULL) { emit error("pcap: no device found"); return false; } // Open the device m_capture = pcap_open(m_device->name, 100, PCAP_OPENFLAG_NOCAPTURE_LOCAL, 2000, NULL, errbuf); if (m_capture == NULL) { emit error("pcap_open: " + QString(errbuf)); return false; } // set filter if (m_device->addresses != NULL) { // Retrieve the mask of the first address of the interface netmask = ((struct sockaddr_in *) (m_device->addresses->netmask))->sin_addr.S_un.S_addr; } else { // If the interface is without an address we suppose to be in a C class network netmask = 0xffffff; } // capture only our UDP request and some ICMP responses QString filter = "(icmp and icmptype != icmp-echo) or (udp and dst host " + QString::fromLocal8Bit(address) + ")"; if (pcap_compile(m_capture, &fcode, filter.toStdString().c_str(), 1, netmask) < 0) { pcap_freealldevs(alldevs); return false; } if (pcap_setfilter(m_capture, &fcode) < 0) { pcap_freealldevs(alldevs); return false; } // At this point, we don't need any more the device list. Free it pcap_freealldevs(alldevs); return true; } bool UdpPing::start() { PingProbe probe; setStatus(UdpPing::Running); for (quint32 i = 0; i < definition->count; i++) { memset(&probe, 0, sizeof(probe)); probe.sock = initSocket(); if (probe.sock < 0) { emit error("initSocket"); continue; } ping(&probe); closesocket(probe.sock); m_pingProbes.append(probe); } setStatus(UdpPing::Finished); emit finished(); return true; } bool UdpPing::stop() { return true; } ResultPtr UdpPing::result() const { QVariantList res; foreach (const PingProbe &probe, m_pingProbes) { if (probe.sendTime > 0 && probe.recvTime > 0) { res << probe.recvTime - probe.sendTime; } } return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant())); } int UdpPing::initSocket() { int ttl = definition->ttl ? definition->ttl : 64; sockaddr_any src_addr; sockaddr_any dst_addr; SOCKET sock = INVALID_SOCKET; memset(&src_addr, 0, sizeof(src_addr)); memset(&dst_addr, 0, sizeof(dst_addr)); getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { // TODO: emit error return -1; } src_addr.sa.sa_family = AF_INET; src_addr.sin.sin_port = htons(definition->sourcePort); if (bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr)) != 0) { emit error("bind: " + QString(strerror(errno))); goto cleanup; } // set TTL if (setsockopt(sock, IPPROTO_IP, IP_TTL, (char *) &ttl, sizeof(ttl)) != 0) { emit error("setsockopt IP_TTL: " + QString(strerror(errno))); goto cleanup; } if (::connect(sock, (struct sockaddr *) &dst_addr, sizeof(dst_addr)) < 0) { emit error("connect: " + QString(strerror(errno))); goto cleanup; } return sock; cleanup: closesocket(sock); return -1; } bool UdpPing::sendData(PingProbe *probe) { if (send(probe->sock, definition->payload, sizeof(definition->payload), 0) < 0) { emit error("send: " + QString(strerror(errno))); return false; } return true; } void UdpPing::receiveData(PingProbe *probe) { Q_UNUSED(probe); } void UdpPing::ping(PingProbe *probe) { PingProbe result; QFuture<PingProbe> future; sockaddr_any dst_addr; // translate domain name to IP address getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); future = QtConcurrent::run(&receiveLoop, m_capture, *probe, dst_addr); if (sendData(probe)) { future.waitForFinished(); result = future.result(); if (result.sendTime > 0 && result.recvTime > 0) { probe->sendTime = result.sendTime; probe->recvTime = result.recvTime; switch (result.response) { case DESTINATION_UNREACHABLE: emit destinationUnreachable(*probe); break; case TTL_EXCEEDED: emit ttlExceeded(*probe); break; case UNHANDLED_ICMP: emit error("Unhandled ICMP packet (type/code): " + QString::number(result.icmpType) + "/" + QString::number(result.icmpCode)); break; } } else if (result.sendTime == 0 && result.recvTime == 0) { emit error("timeout"); } else { emit error("error receiving packets"); } } else { emit error("error while sending"); } } bool getAddress(const QString &address, sockaddr_any *addr) { struct addrinfo hints; struct addrinfo *rp = NULL, *result = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_flags = AI_FQDN; if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result)) { return false; } for (rp = result; rp && rp->ai_family != AF_INET; rp = rp->ai_next) { } if (!rp) { rp = result; } memcpy(addr, rp->ai_addr, rp->ai_addrlen); freeaddrinfo(result); return true; } static PingProbe receiveLoop(pcap_t *capture, PingProbe probe, sockaddr_any destination) { struct ipAddress { u_char byte1; u_char byte2; u_char byte3; u_char byte4; }; int res; char sourceAddress[16] = ""; char destinationAddress[16] = ""; const u_char *data; pcap_pkthdr *header; ipAddress *source; quint8 *icmpType; quint8 *icmpCode; quint8 *ipProto; PingProbe newProbe; memcpy(&newProbe, &probe, sizeof(newProbe)); for (;;) { res = pcap_next_ex(capture, &header, &data); ipProto = (quint8 *) (data + 23); source = (ipAddress *) (data + 26); icmpType = (quint8 *) (data + 34); icmpCode = (quint8 *) (data + 35); switch (res) { case 0: // timed out newProbe.sendTime = 0; newProbe.recvTime = 0; goto exit; case -1: // error indication goto error; default: // packets received // TODO: ensure the packets are really ours by checking them // source address of the response packet sprintf(sourceAddress, "%d.%d.%d.%d", source->byte1, source->byte2, source->byte3, source->byte4); // destination of request packet strncpy(destinationAddress, inet_ntoa(destination.sin.sin_addr), sizeof(destinationAddress)); if (*ipProto == 17) { // UDP request newProbe.sendTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; } else if (*ipProto == 1) { // ICMP response if (*icmpCode == 3 && *icmpType == 3) { // destination and port unreachable: this was a successful ping if (strncmp(sourceAddress, destinationAddress, 16) == 0) { newProbe.recvTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; newProbe.response = DESTINATION_UNREACHABLE; goto exit; } } else if (*icmpCode == 0 && *icmpType == 11) { /* * TTL exceeded * * Let's missuse source and sourceAddress for the destination of the original IP header. */ source = (ipAddress *) (data + 76); sprintf(sourceAddress, "%d.%d.%d.%d", source->byte1, source->byte2, source->byte3, source->byte4); if (strncmp(sourceAddress, destinationAddress, 16) == 0) { newProbe.recvTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; newProbe.response = TTL_EXCEEDED; goto exit; } } else { /* * An unhandled ICMP packet has been captured. We need to check this and * handle it if needed. */ newProbe.icmpType = *icmpType; newProbe.icmpCode = *icmpCode; newProbe.response = UNHANDLED_ICMP; goto exit; } } else { /* * This else-branch exists because of paranoia only. * The WinPCAP filter is set to capture certain ICMP and UDP packets only * and therefore should never end up here. */ goto error; } } } error: // error indication newProbe.sendTime = -1; newProbe.recvTime = -1; exit: return newProbe; } // vim: set sts=4 sw=4 et: <commit_msg>satisfy code checker v2<commit_after>#include "udpping.h" #include <time.h> #include <windows.h> #include <mswsock.h> #include <Mstcpip.h> #include <pcap.h> bool getAddress(const QString &address, sockaddr_any *addr); PingProbe receiveLoop(pcap_t *capture, PingProbe probe, sockaddr_any destination); UdpPing::UdpPing(QObject *parent) : Measurement(parent), currentStatus(Unknown), m_device(NULL), m_capture(NULL) { WSADATA wsaData; // Initialize Winsock if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { // TODO: emit error } } UdpPing::~UdpPing() { WSACleanup(); } Measurement::Status UdpPing::status() const { return currentStatus; } void UdpPing::setStatus(Status status) { if (currentStatus != status) { currentStatus = status; emit statusChanged(status); } } bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition) { Q_UNUSED(networkManager); pcap_if_t *alldevs; char errbuf[PCAP_ERRBUF_SIZE] = ""; char source[PCAP_BUF_SIZE] = ""; char address[16] = ""; sockaddr_any dst_addr; unsigned long netmask; struct bpf_program fcode; definition = measurementDefinition.dynamicCast<UdpPingDefinition>(); memset(&dst_addr, 0, sizeof(dst_addr)); // translate domain name to IP address getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); strncpy(address, inet_ntoa(dst_addr.sin.sin_addr), sizeof(address)); if (pcap_createsrcstr(source, PCAP_SRC_IFLOCAL, address, NULL, NULL, errbuf) != 0) { emit error("pcap_createsrcstr: " + QString(errbuf)); return false; } if (pcap_findalldevs_ex(source, NULL, &alldevs, errbuf) != 0) { emit error("pcap_findalldevs_ex: " + QString(errbuf)); return false; } // take the first device m_device = alldevs; if (m_device == NULL) { emit error("pcap: no device found"); return false; } // Open the device m_capture = pcap_open(m_device->name, 100, PCAP_OPENFLAG_NOCAPTURE_LOCAL, 2000, NULL, errbuf); if (m_capture == NULL) { emit error("pcap_open: " + QString(errbuf)); return false; } // set filter if (m_device->addresses != NULL) { // Retrieve the mask of the first address of the interface netmask = ((struct sockaddr_in *) (m_device->addresses->netmask))->sin_addr.S_un.S_addr; } else { // If the interface is without an address we suppose to be in a C class network netmask = 0xffffff; } // capture only our UDP request and some ICMP responses QString filter = "(icmp and icmptype != icmp-echo) or (udp and dst host " + QString::fromLocal8Bit(address) + ")"; if (pcap_compile(m_capture, &fcode, filter.toStdString().c_str(), 1, netmask) < 0) { pcap_freealldevs(alldevs); return false; } if (pcap_setfilter(m_capture, &fcode) < 0) { pcap_freealldevs(alldevs); return false; } // At this point, we don't need any more the device list. Free it pcap_freealldevs(alldevs); return true; } bool UdpPing::start() { PingProbe probe; setStatus(UdpPing::Running); for (quint32 i = 0; i < definition->count; i++) { memset(&probe, 0, sizeof(probe)); probe.sock = initSocket(); if (probe.sock < 0) { emit error("initSocket"); continue; } ping(&probe); closesocket(probe.sock); m_pingProbes.append(probe); } setStatus(UdpPing::Finished); emit finished(); return true; } bool UdpPing::stop() { return true; } ResultPtr UdpPing::result() const { QVariantList res; foreach (const PingProbe &probe, m_pingProbes) { if (probe.sendTime > 0 && probe.recvTime > 0) { res << probe.recvTime - probe.sendTime; } } return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant())); } int UdpPing::initSocket() { int ttl = definition->ttl ? definition->ttl : 64; sockaddr_any src_addr; sockaddr_any dst_addr; SOCKET sock = INVALID_SOCKET; memset(&src_addr, 0, sizeof(src_addr)); memset(&dst_addr, 0, sizeof(dst_addr)); getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { // TODO: emit error return -1; } src_addr.sa.sa_family = AF_INET; src_addr.sin.sin_port = htons(definition->sourcePort); if (bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr)) != 0) { emit error("bind: " + QString(strerror(errno))); goto cleanup; } // set TTL if (setsockopt(sock, IPPROTO_IP, IP_TTL, (char *) &ttl, sizeof(ttl)) != 0) { emit error("setsockopt IP_TTL: " + QString(strerror(errno))); goto cleanup; } if (::connect(sock, (struct sockaddr *) &dst_addr, sizeof(dst_addr)) < 0) { emit error("connect: " + QString(strerror(errno))); goto cleanup; } return sock; cleanup: closesocket(sock); return -1; } bool UdpPing::sendData(PingProbe *probe) { if (send(probe->sock, definition->payload, sizeof(definition->payload), 0) < 0) { emit error("send: " + QString(strerror(errno))); return false; } return true; } void UdpPing::receiveData(PingProbe *probe) { Q_UNUSED(probe); } void UdpPing::ping(PingProbe *probe) { PingProbe result; QFuture<PingProbe> future; sockaddr_any dst_addr; // translate domain name to IP address getAddress(definition->url, &dst_addr); dst_addr.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); future = QtConcurrent::run(&receiveLoop, m_capture, *probe, dst_addr); if (sendData(probe)) { future.waitForFinished(); result = future.result(); if (result.sendTime > 0 && result.recvTime > 0) { probe->sendTime = result.sendTime; probe->recvTime = result.recvTime; switch (result.response) { case DESTINATION_UNREACHABLE: emit destinationUnreachable(*probe); break; case TTL_EXCEEDED: emit ttlExceeded(*probe); break; case UNHANDLED_ICMP: emit error("Unhandled ICMP packet (type/code): " + QString::number(result.icmpType) + "/" + QString::number(result.icmpCode)); break; } } else if (result.sendTime == 0 && result.recvTime == 0) { emit error("timeout"); } else { emit error("error receiving packets"); } } else { emit error("error while sending"); } } bool getAddress(const QString &address, sockaddr_any *addr) { struct addrinfo hints; struct addrinfo *rp = NULL, *result = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_flags = AI_FQDN; if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result)) { return false; } for (rp = result; rp && rp->ai_family != AF_INET; rp = rp->ai_next) { } if (!rp) { rp = result; } memcpy(addr, rp->ai_addr, rp->ai_addrlen); freeaddrinfo(result); return true; } static PingProbe receiveLoop(pcap_t *capture, PingProbe probe, sockaddr_any destination) { struct ipAddress { u_char byte1; u_char byte2; u_char byte3; u_char byte4; }; int res; char sourceAddress[16] = ""; char destinationAddress[16] = ""; const u_char *data; pcap_pkthdr *header; ipAddress *source; quint8 *icmpType; quint8 *icmpCode; quint8 *ipProto; PingProbe newProbe; memcpy(&newProbe, &probe, sizeof(newProbe)); for (;;) { res = pcap_next_ex(capture, &header, &data); ipProto = (quint8 *) (data + 23); source = (ipAddress *) (data + 26); icmpType = (quint8 *) (data + 34); icmpCode = (quint8 *) (data + 35); switch (res) { case 0: // timed out newProbe.sendTime = 0; newProbe.recvTime = 0; goto exit; case -1: // error indication goto error; default: // packets received // TODO: ensure the packets are really ours by checking them // source address of the response packet sprintf(sourceAddress, "%d.%d.%d.%d", source->byte1, source->byte2, source->byte3, source->byte4); // destination of request packet strncpy(destinationAddress, inet_ntoa(destination.sin.sin_addr), sizeof(destinationAddress)); if (*ipProto == 17) { // UDP request newProbe.sendTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; } else if (*ipProto == 1) { // ICMP response if (*icmpCode == 3 && *icmpType == 3) { // destination and port unreachable: this was a successful ping if (strncmp(sourceAddress, destinationAddress, 16) == 0) { newProbe.recvTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; newProbe.response = DESTINATION_UNREACHABLE; goto exit; } } else if (*icmpCode == 0 && *icmpType == 11) { /* * TTL exceeded * * Let's missuse source and sourceAddress for the destination of the original IP header. */ source = (ipAddress *) (data + 76); sprintf(sourceAddress, "%d.%d.%d.%d", source->byte1, source->byte2, source->byte3, source->byte4); if (strncmp(sourceAddress, destinationAddress, 16) == 0) { newProbe.recvTime = header->ts.tv_sec * 1e6 + header->ts.tv_usec; newProbe.response = TTL_EXCEEDED; goto exit; } } else { /* * An unhandled ICMP packet has been captured. We need to check this and * handle it if needed. */ newProbe.icmpType = *icmpType; newProbe.icmpCode = *icmpCode; newProbe.response = UNHANDLED_ICMP; goto exit; } } else { /* * This else-branch exists because of paranoia only. * The WinPCAP filter is set to capture certain ICMP and UDP packets only * and therefore should never end up here. */ goto error; } } } error: // error indication newProbe.sendTime = -1; newProbe.recvTime = -1; exit: return newProbe; } // vim: set sts=4 sw=4 et: <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_, L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(window_->browser()); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripta panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableScriptsTab) { RunTest("testEnableScriptsTab", kDebuggerTestPage); } } // namespace <commit_msg>DevTools: fix debugger test, reenable debugger and resources tests.<commit_after>// Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_, L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(window_->browser()); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } } // namespace <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <deque> #include <string> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/help.hpp> #include <process/http.hpp> #include <process/id.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <process/metrics/gauge.hpp> #include <process/metrics/metrics.hpp> #include <process/metrics/timer.hpp> #include <stout/lambda.hpp> #include <stout/none.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/protobuf.hpp> #include "common/type_utils.hpp" #include "master/registrar.hpp" #include "master/registry.hpp" #include "state/protobuf.hpp" using mesos::internal::state::protobuf::State; using mesos::internal::state::protobuf::Variable; using process::dispatch; using process::spawn; using process::terminate; using process::wait; // Necessary on some OS's to disambiguate. using process::DESCRIPTION; using process::Failure; using process::Future; using process::HELP; using process::Owned; using process::Process; using process::Promise; using process::TLDR; using process::USAGE; using process::http::OK; using process::metrics::Gauge; using process::metrics::Timer; using std::deque; using std::string; namespace mesos { namespace internal { namespace master { using process::http::Response; using process::http::Request; class RegistrarProcess : public Process<RegistrarProcess> { public: RegistrarProcess(const Flags& _flags, State* _state) : ProcessBase(process::ID::generate("registrar")), metrics(*this), updating(false), flags(_flags), state(_state) {} virtual ~RegistrarProcess() {} // Registrar implementation. Future<Registry> recover(const MasterInfo& info); Future<bool> apply(Owned<Operation> operation); protected: virtual void initialize() { route("/registry", registryHelp(), &RegistrarProcess::registry); } private: // HTTP handlers. // /registrar(N)/registry Future<Response> registry(const Request& request); static string registryHelp(); // The 'Recover' operation adds the latest MasterInfo. class Recover : public Operation { public: explicit Recover(const MasterInfo& _info) : info(_info) {} protected: virtual Try<bool> perform( Registry* registry, hashset<SlaveID>* slaveIDs, bool strict) { registry->mutable_master()->mutable_info()->CopyFrom(info); return true; // Mutation. } private: const MasterInfo info; }; // Metrics. struct Metrics { explicit Metrics(const RegistrarProcess& process) : queued_operations( "registrar/queued_operations", defer(process, &RegistrarProcess::_queued_operations)), registry_size_bytes( "registrar/registry_size_bytes", defer(process, &RegistrarProcess::_registry_size_bytes)), state_fetch("registrar/state_fetch"), state_store("registrar/state_store", Days(1)) { process::metrics::add(queued_operations); process::metrics::add(registry_size_bytes); process::metrics::add(state_fetch); process::metrics::add(state_store); } ~Metrics() { process::metrics::remove(queued_operations); process::metrics::remove(registry_size_bytes); process::metrics::remove(state_fetch); process::metrics::remove(state_store); } Gauge queued_operations; Gauge registry_size_bytes; Timer<Milliseconds> state_fetch; Timer<Milliseconds> state_store; } metrics; // Gauge handlers double _queued_operations() { return operations.size(); } Future<double> _registry_size_bytes() { if (variable.isSome()) { return variable.get().get().ByteSize(); } return Failure("Not recovered yet"); } // Continuations. void _recover( const MasterInfo& info, const Future<Variable<Registry> >& recovery); void __recover(const Future<bool>& recover); Future<bool> _apply(Owned<Operation> operation); // Helper for updating state (performing store). void update(); void _update( const Future<Option<Variable<Registry> > >& store, deque<Owned<Operation> > operations); // Fails all pending operations and transitions the Registrar // into an error state in which all subsequent operations will fail. // This ensures we don't attempt to re-acquire log leadership by // performing more State storage operations. void abort(const string& message); Option<Variable<Registry> > variable; deque<Owned<Operation> > operations; bool updating; // Used to signify fetching (recovering) or storing. const Flags flags; State* state; // Used to compose our operations with recovery. Option<Owned<Promise<Registry> > > recovered; // When an error is encountered from abort(), we'll fail all // subsequent operations. Option<Error> error; }; // Helper for treating State operations that timeout as failures. template <typename T> Future<T> timeout( const string& operation, const Duration& duration, Future<T> future) { future.discard(); return Failure( "Failed to perform " + operation + " within " + stringify(duration)); } // Helper for failing a deque of operations. void fail(deque<Owned<Operation> >* operations, const string& message) { while (!operations->empty()) { const Owned<Operation>& operation = operations->front(); operations->pop_front(); operation->fail(message); } } Future<Response> RegistrarProcess::registry(const Request& request) { JSON::Object result; if (variable.isSome()) { result = JSON::Protobuf(variable.get().get()); } return OK(result, request.query.get("jsonp")); } string RegistrarProcess::registryHelp() { return HELP( TLDR( "Returns the current contents of the Registry in JSON."), USAGE( "/registrar(1)/registry"), DESCRIPTION( "Example:" "", "```", "{", " \"master\":", " {", " \"info\":", " {", " \"hostname\": \"localhost\",", " \"id\": \"20140325-235542-1740121354-5050-33357\",", " \"ip\": 2130706433,", " \"pid\": \"[email protected]:5050\",", " \"port\": 5050", " }", " },", "", " \"slaves\":", " {", " \"slaves\":", " [", " {", " \"info\":", " {", " \"checkpoint\": true,", " \"hostname\": \"localhost\",", " \"id\":", " { ", " \"value\": \"20140325-234618-1740121354-5050-29065-0\"", " },", " \"port\": 5051,", " \"resources\":", " [", " {", " \"name\": \"cpus\",", " \"role\": \"*\",", " \"scalar\": { \"value\": 24 },", " \"type\": \"SCALAR\"", " }", " ],", " \"webui_hostname\": \"localhost\"", " }", " }", " ]", " }", "}", "```")); } Future<Registry> RegistrarProcess::recover(const MasterInfo& info) { if (recovered.isNone()) { LOG(INFO) << "Recovering registrar"; metrics.state_fetch.time(state->fetch<Registry>("registry")) .after(flags.registry_fetch_timeout, lambda::bind( &timeout<Variable<Registry> >, "fetch", flags.registry_fetch_timeout, lambda::_1)) .onAny(defer(self(), &Self::_recover, info, lambda::_1)); updating = true; recovered = Owned<Promise<Registry> >(new Promise<Registry>()); } return recovered.get()->future(); } void RegistrarProcess::_recover( const MasterInfo& info, const Future<Variable<Registry> >& recovery) { updating = false; CHECK(!recovery.isPending()); if (!recovery.isReady()) { recovered.get()->fail("Failed to recover registrar: " + (recovery.isFailed() ? recovery.failure() : "discarded")); } else { // Save the registry. variable = recovery.get(); LOG(INFO) << "Successfully fetched the registry " << "(" << Bytes(variable.get().get().ByteSize()) << ")"; // Perform the Recover operation to add the new MasterInfo. Owned<Operation> operation(new Recover(info)); operations.push_back(operation); operation->future() .onAny(defer(self(), &Self::__recover, lambda::_1)); update(); } } void RegistrarProcess::__recover(const Future<bool>& recover) { CHECK(!recover.isPending()); if (!recover.isReady()) { recovered.get()->fail("Failed to recover registrar: " "Failed to persist MasterInfo: " + (recover.isFailed() ? recover.failure() : "discarded")); } else if (!recover.get()) { recovered.get()->fail("Failed to recover registrar: " "Failed to persist MasterInfo: version mismatch"); } else { LOG(INFO) << "Successfully recovered registrar"; // At this point _update() has updated 'variable' to contain // the Registry with the latest MasterInfo. // Set the promise and un-gate any pending operations. CHECK_SOME(variable); recovered.get()->set(variable.get().get()); } } Future<bool> RegistrarProcess::apply(Owned<Operation> operation) { if (recovered.isNone()) { return Failure("Attempted to apply the operation before recovering"); } return recovered.get()->future() .then(defer(self(), &Self::_apply, operation)); } Future<bool> RegistrarProcess::_apply(Owned<Operation> operation) { if (error.isSome()) { return Failure(error.get()); } CHECK_SOME(variable); operations.push_back(operation); Future<bool> future = operation->future(); if (!updating) { update(); } return future; } void RegistrarProcess::update() { if (operations.empty()) { return; // No-op. } CHECK(!updating); CHECK(error.isNone()); updating = true; LOG(INFO) << "Attempting to update the 'registry'"; CHECK_SOME(variable); // Create a snapshot of the current registry. Registry registry = variable.get().get(); // Create the 'slaveIDs' accumulator. hashset<SlaveID> slaveIDs; foreach (const Registry::Slave& slave, registry.slaves().slaves()) { slaveIDs.insert(slave.info().id()); } foreach (Owned<Operation> operation, operations) { // No need to process the result of the operation. (*operation)(&registry, &slaveIDs, flags.registry_strict); } // Perform the store, and time the operation. metrics.state_store.time(state->store(variable.get().mutate(registry))) .after(flags.registry_store_timeout, lambda::bind( &timeout<Option<Variable<Registry> > >, "store", flags.registry_store_timeout, lambda::_1)) .onAny(defer(self(), &Self::_update, lambda::_1, operations)); // Clear the operations, _update will transition the Promises! operations.clear(); } void RegistrarProcess::_update( const Future<Option<Variable<Registry> > >& store, deque<Owned<Operation> > applied) { updating = false; // Abort if the storage operation did not succeed. if (!store.isReady() || store.get().isNone()) { string message = "Failed to update 'registry': "; if (store.isFailed()) { message += store.failure(); } else if (store.isDiscarded()) { message += "discarded"; } else { message += "version mismatch"; } fail(&applied, message); abort(message); return; } LOG(INFO) << "Successfully updated 'registry'"; variable = store.get().get(); // Remove the operations. while (!applied.empty()) { Owned<Operation> operation = applied.front(); applied.pop_front(); operation->set(); } if (!operations.empty()) { update(); } } void RegistrarProcess::abort(const string& message) { error = Error(message); LOG(ERROR) << "Registrar aborting: " << message; fail(&operations, message); } Registrar::Registrar(const Flags& flags, State* state) { process = new RegistrarProcess(flags, state); spawn(process); } Registrar::~Registrar() { terminate(process); wait(process); delete process; } Future<Registry> Registrar::recover(const MasterInfo& info) { return dispatch(process, &RegistrarProcess::recover, info); } Future<bool> Registrar::apply(Owned<Operation> operation) { return dispatch(process, &RegistrarProcess::apply, operation); } } // namespace master { } // namespace internal { } // namespace mesos { <commit_msg>MESOS-1376: Fixed an invalid reference in the Registrar.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <deque> #include <string> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/help.hpp> #include <process/http.hpp> #include <process/id.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <process/metrics/gauge.hpp> #include <process/metrics/metrics.hpp> #include <process/metrics/timer.hpp> #include <stout/lambda.hpp> #include <stout/none.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/protobuf.hpp> #include "common/type_utils.hpp" #include "master/registrar.hpp" #include "master/registry.hpp" #include "state/protobuf.hpp" using mesos::internal::state::protobuf::State; using mesos::internal::state::protobuf::Variable; using process::dispatch; using process::spawn; using process::terminate; using process::wait; // Necessary on some OS's to disambiguate. using process::DESCRIPTION; using process::Failure; using process::Future; using process::HELP; using process::Owned; using process::Process; using process::Promise; using process::TLDR; using process::USAGE; using process::http::OK; using process::metrics::Gauge; using process::metrics::Timer; using std::deque; using std::string; namespace mesos { namespace internal { namespace master { using process::http::Response; using process::http::Request; class RegistrarProcess : public Process<RegistrarProcess> { public: RegistrarProcess(const Flags& _flags, State* _state) : ProcessBase(process::ID::generate("registrar")), metrics(*this), updating(false), flags(_flags), state(_state) {} virtual ~RegistrarProcess() {} // Registrar implementation. Future<Registry> recover(const MasterInfo& info); Future<bool> apply(Owned<Operation> operation); protected: virtual void initialize() { route("/registry", registryHelp(), &RegistrarProcess::registry); } private: // HTTP handlers. // /registrar(N)/registry Future<Response> registry(const Request& request); static string registryHelp(); // The 'Recover' operation adds the latest MasterInfo. class Recover : public Operation { public: explicit Recover(const MasterInfo& _info) : info(_info) {} protected: virtual Try<bool> perform( Registry* registry, hashset<SlaveID>* slaveIDs, bool strict) { registry->mutable_master()->mutable_info()->CopyFrom(info); return true; // Mutation. } private: const MasterInfo info; }; // Metrics. struct Metrics { explicit Metrics(const RegistrarProcess& process) : queued_operations( "registrar/queued_operations", defer(process, &RegistrarProcess::_queued_operations)), registry_size_bytes( "registrar/registry_size_bytes", defer(process, &RegistrarProcess::_registry_size_bytes)), state_fetch("registrar/state_fetch"), state_store("registrar/state_store", Days(1)) { process::metrics::add(queued_operations); process::metrics::add(registry_size_bytes); process::metrics::add(state_fetch); process::metrics::add(state_store); } ~Metrics() { process::metrics::remove(queued_operations); process::metrics::remove(registry_size_bytes); process::metrics::remove(state_fetch); process::metrics::remove(state_store); } Gauge queued_operations; Gauge registry_size_bytes; Timer<Milliseconds> state_fetch; Timer<Milliseconds> state_store; } metrics; // Gauge handlers double _queued_operations() { return operations.size(); } Future<double> _registry_size_bytes() { if (variable.isSome()) { return variable.get().get().ByteSize(); } return Failure("Not recovered yet"); } // Continuations. void _recover( const MasterInfo& info, const Future<Variable<Registry> >& recovery); void __recover(const Future<bool>& recover); Future<bool> _apply(Owned<Operation> operation); // Helper for updating state (performing store). void update(); void _update( const Future<Option<Variable<Registry> > >& store, deque<Owned<Operation> > operations); // Fails all pending operations and transitions the Registrar // into an error state in which all subsequent operations will fail. // This ensures we don't attempt to re-acquire log leadership by // performing more State storage operations. void abort(const string& message); Option<Variable<Registry> > variable; deque<Owned<Operation> > operations; bool updating; // Used to signify fetching (recovering) or storing. const Flags flags; State* state; // Used to compose our operations with recovery. Option<Owned<Promise<Registry> > > recovered; // When an error is encountered from abort(), we'll fail all // subsequent operations. Option<Error> error; }; // Helper for treating State operations that timeout as failures. template <typename T> Future<T> timeout( const string& operation, const Duration& duration, Future<T> future) { future.discard(); return Failure( "Failed to perform " + operation + " within " + stringify(duration)); } // Helper for failing a deque of operations. void fail(deque<Owned<Operation> >* operations, const string& message) { while (!operations->empty()) { Owned<Operation> operation = operations->front(); operations->pop_front(); operation->fail(message); } } Future<Response> RegistrarProcess::registry(const Request& request) { JSON::Object result; if (variable.isSome()) { result = JSON::Protobuf(variable.get().get()); } return OK(result, request.query.get("jsonp")); } string RegistrarProcess::registryHelp() { return HELP( TLDR( "Returns the current contents of the Registry in JSON."), USAGE( "/registrar(1)/registry"), DESCRIPTION( "Example:" "", "```", "{", " \"master\":", " {", " \"info\":", " {", " \"hostname\": \"localhost\",", " \"id\": \"20140325-235542-1740121354-5050-33357\",", " \"ip\": 2130706433,", " \"pid\": \"[email protected]:5050\",", " \"port\": 5050", " }", " },", "", " \"slaves\":", " {", " \"slaves\":", " [", " {", " \"info\":", " {", " \"checkpoint\": true,", " \"hostname\": \"localhost\",", " \"id\":", " { ", " \"value\": \"20140325-234618-1740121354-5050-29065-0\"", " },", " \"port\": 5051,", " \"resources\":", " [", " {", " \"name\": \"cpus\",", " \"role\": \"*\",", " \"scalar\": { \"value\": 24 },", " \"type\": \"SCALAR\"", " }", " ],", " \"webui_hostname\": \"localhost\"", " }", " }", " ]", " }", "}", "```")); } Future<Registry> RegistrarProcess::recover(const MasterInfo& info) { if (recovered.isNone()) { LOG(INFO) << "Recovering registrar"; metrics.state_fetch.time(state->fetch<Registry>("registry")) .after(flags.registry_fetch_timeout, lambda::bind( &timeout<Variable<Registry> >, "fetch", flags.registry_fetch_timeout, lambda::_1)) .onAny(defer(self(), &Self::_recover, info, lambda::_1)); updating = true; recovered = Owned<Promise<Registry> >(new Promise<Registry>()); } return recovered.get()->future(); } void RegistrarProcess::_recover( const MasterInfo& info, const Future<Variable<Registry> >& recovery) { updating = false; CHECK(!recovery.isPending()); if (!recovery.isReady()) { recovered.get()->fail("Failed to recover registrar: " + (recovery.isFailed() ? recovery.failure() : "discarded")); } else { // Save the registry. variable = recovery.get(); LOG(INFO) << "Successfully fetched the registry " << "(" << Bytes(variable.get().get().ByteSize()) << ")"; // Perform the Recover operation to add the new MasterInfo. Owned<Operation> operation(new Recover(info)); operations.push_back(operation); operation->future() .onAny(defer(self(), &Self::__recover, lambda::_1)); update(); } } void RegistrarProcess::__recover(const Future<bool>& recover) { CHECK(!recover.isPending()); if (!recover.isReady()) { recovered.get()->fail("Failed to recover registrar: " "Failed to persist MasterInfo: " + (recover.isFailed() ? recover.failure() : "discarded")); } else if (!recover.get()) { recovered.get()->fail("Failed to recover registrar: " "Failed to persist MasterInfo: version mismatch"); } else { LOG(INFO) << "Successfully recovered registrar"; // At this point _update() has updated 'variable' to contain // the Registry with the latest MasterInfo. // Set the promise and un-gate any pending operations. CHECK_SOME(variable); recovered.get()->set(variable.get().get()); } } Future<bool> RegistrarProcess::apply(Owned<Operation> operation) { if (recovered.isNone()) { return Failure("Attempted to apply the operation before recovering"); } return recovered.get()->future() .then(defer(self(), &Self::_apply, operation)); } Future<bool> RegistrarProcess::_apply(Owned<Operation> operation) { if (error.isSome()) { return Failure(error.get()); } CHECK_SOME(variable); operations.push_back(operation); Future<bool> future = operation->future(); if (!updating) { update(); } return future; } void RegistrarProcess::update() { if (operations.empty()) { return; // No-op. } CHECK(!updating); CHECK(error.isNone()); updating = true; LOG(INFO) << "Attempting to update the 'registry'"; CHECK_SOME(variable); // Create a snapshot of the current registry. Registry registry = variable.get().get(); // Create the 'slaveIDs' accumulator. hashset<SlaveID> slaveIDs; foreach (const Registry::Slave& slave, registry.slaves().slaves()) { slaveIDs.insert(slave.info().id()); } foreach (Owned<Operation> operation, operations) { // No need to process the result of the operation. (*operation)(&registry, &slaveIDs, flags.registry_strict); } // Perform the store, and time the operation. metrics.state_store.time(state->store(variable.get().mutate(registry))) .after(flags.registry_store_timeout, lambda::bind( &timeout<Option<Variable<Registry> > >, "store", flags.registry_store_timeout, lambda::_1)) .onAny(defer(self(), &Self::_update, lambda::_1, operations)); // Clear the operations, _update will transition the Promises! operations.clear(); } void RegistrarProcess::_update( const Future<Option<Variable<Registry> > >& store, deque<Owned<Operation> > applied) { updating = false; // Abort if the storage operation did not succeed. if (!store.isReady() || store.get().isNone()) { string message = "Failed to update 'registry': "; if (store.isFailed()) { message += store.failure(); } else if (store.isDiscarded()) { message += "discarded"; } else { message += "version mismatch"; } fail(&applied, message); abort(message); return; } LOG(INFO) << "Successfully updated 'registry'"; variable = store.get().get(); // Remove the operations. while (!applied.empty()) { Owned<Operation> operation = applied.front(); applied.pop_front(); operation->set(); } if (!operations.empty()) { update(); } } void RegistrarProcess::abort(const string& message) { error = Error(message); LOG(ERROR) << "Registrar aborting: " << message; fail(&operations, message); } Registrar::Registrar(const Flags& flags, State* state) { process = new RegistrarProcess(flags, state); spawn(process); } Registrar::~Registrar() { terminate(process); wait(process); delete process; } Future<Registry> Registrar::recover(const MasterInfo& info) { return dispatch(process, &RegistrarProcess::recover, info); } Future<bool> Registrar::apply(Owned<Operation> operation) { return dispatch(process, &RegistrarProcess::apply, operation); } } // namespace master { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>#include <elves/factorize/BigInt.h> #include <elves/factorize/cuda/Factorize.h> #include <elves/factorize/cuda/NumberHelper.h> #include <elves/cuda-utils/Memory.h> #include <gtest/gtest.h> #include <functional> #include <cstdlib> extern void testAdd(PNumData left, PNumData right, PNumData result); extern void testSub(PNumData left, PNumData right, PNumData result); extern void testMul(PNumData left, PNumData right, PNumData result); extern void testDiv(PNumData left, PNumData right, PNumData result); extern void testSmallerThan(PNumData left, PNumData right, bool* result); extern void testShiftLeft(PNumData left, uint32_t offset, PNumData result); extern void testShiftRight(PNumData left, uint32_t offset, PNumData result); using namespace std; BigInt invokeShiftKernel(const BigInt& left, const uint32_t right, function<void (PNumData, uint32_t, PNumData)> kernelCall) { CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> out_d(NUM_FIELDS); kernelCall(left_d.get(), right, out_d.get()); return NumberHelper::NumberToBigInt(out_d); } bool invokeBoolKernel(const BigInt& left, const BigInt& right, function<void (PNumData, PNumData, bool*)> kernelCall) { bool outputData; CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> right_d(NumberHelper::BigIntToNumber(right)); CudaUtils::Memory<bool> out_d(1); kernelCall(left_d.get(), right_d.get(), out_d.get()); out_d.transferTo(&outputData); return outputData; } BigInt invokeKernel(const BigInt& left, const BigInt& right, function<void (PNumData, PNumData, PNumData)> kernelCall) { CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> right_d(NumberHelper::BigIntToNumber(right)); CudaUtils::Memory<uint32_t> out_d(NUM_FIELDS); kernelCall(left_d.get(), right_d.get(), out_d.get()); return NumberHelper::NumberToBigInt(out_d); } TEST(CudaBigIntTest, testMpzConversion) { BigInt start("1231490623"); NumData test; memset(test, 0, sizeof(uint32_t) * NUM_FIELDS); mpz_export(test, nullptr, -1, sizeof(uint32_t), 0, 0, start.get_mpz_t()); BigInt compare; mpz_import(compare.get_mpz_t(), NUM_FIELDS, -1, sizeof(uint32_t), 0, 0, test); EXPECT_EQ(start, compare); } TEST(CudaBigIntTest, testAddition) { BigInt left("12314906231232141243"); BigInt right("21317833214213"); BigInt expected("12314927549065355456"); auto actual = invokeKernel(left, right, testAdd); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSubtraction) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("90108101410172790"); auto actual = invokeKernel(left, right, testSub); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testMultiplication) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("70873452463358713606126842179959"); auto actual = invokeKernel(left, right, testMul); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testMultiplicationSmallNumbers) { BigInt left("5"); BigInt right("8"); BigInt expected("40"); auto actual = invokeKernel(left, right, testMul); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivision) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("116"); auto actual = invokeKernel(left, right, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivisionEqualValues) { BigInt left("90887891231490623"); BigInt right("90887891231490623"); BigInt expected("1"); auto actual = invokeKernel(left, right, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivisionEqualOperands) { BigInt left("90887891231490623"); BigInt expected("1"); auto actual = invokeKernel(left, left, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSmallerThan) { BigInt left("90887891231490623"); BigInt right("7797822229821317833"); bool expected(true); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testNotSmallerThan) { BigInt left("90887891231490624"); BigInt right("90887891231490623"); bool expected(false); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSmallerThanWithEqualOperands) { BigInt left("90887891231490623"); BigInt right("90887891231490623"); bool expected(false); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeft) { BigInt left("1"); uint32_t offset(32); BigInt expected("4294967296"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeftBiggerNumber) { BigInt left("1282943598234"); uint32_t offset(23); BigInt expected("10762110931694518272"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeftBiggerNumber2) { BigInt left("1282943598234"); uint32_t offset(3333); BigInt expected("0"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRight) { BigInt left("4294967296"); uint32_t offset(32); BigInt expected("1"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightBiggerNumber) { BigInt left("1301820391234234234342"); uint32_t offset(33); BigInt expected("151551839806"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightBiggerNumber2) { BigInt left("2135987035920910082395021706169552114602704522356652769947041607822219725780640550022962086936575"); uint32_t offset(33); BigInt expected("248661618204893321077691124073410420050228075398673858720231988446579748506266687766527"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightOutrageousShiftOffset) { BigInt left("1"); uint32_t offset(33333); BigInt expected("0"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } <commit_msg>renamed cuda bigint testcase<commit_after>#include <elves/factorize/BigInt.h> #include <elves/factorize/cuda/Factorize.h> #include <elves/factorize/cuda/NumberHelper.h> #include <elves/cuda-utils/Memory.h> #include <gtest/gtest.h> #include <functional> #include <cstdlib> extern void testAdd(PNumData left, PNumData right, PNumData result); extern void testSub(PNumData left, PNumData right, PNumData result); extern void testMul(PNumData left, PNumData right, PNumData result); extern void testDiv(PNumData left, PNumData right, PNumData result); extern void testSmallerThan(PNumData left, PNumData right, bool* result); extern void testShiftLeft(PNumData left, uint32_t offset, PNumData result); extern void testShiftRight(PNumData left, uint32_t offset, PNumData result); using namespace std; BigInt invokeShiftKernel(const BigInt& left, const uint32_t right, function<void (PNumData, uint32_t, PNumData)> kernelCall) { CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> out_d(NUM_FIELDS); kernelCall(left_d.get(), right, out_d.get()); return NumberHelper::NumberToBigInt(out_d); } bool invokeBoolKernel(const BigInt& left, const BigInt& right, function<void (PNumData, PNumData, bool*)> kernelCall) { bool outputData; CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> right_d(NumberHelper::BigIntToNumber(right)); CudaUtils::Memory<bool> out_d(1); kernelCall(left_d.get(), right_d.get(), out_d.get()); out_d.transferTo(&outputData); return outputData; } BigInt invokeKernel(const BigInt& left, const BigInt& right, function<void (PNumData, PNumData, PNumData)> kernelCall) { CudaUtils::Memory<uint32_t> left_d(NumberHelper::BigIntToNumber(left)); CudaUtils::Memory<uint32_t> right_d(NumberHelper::BigIntToNumber(right)); CudaUtils::Memory<uint32_t> out_d(NUM_FIELDS); kernelCall(left_d.get(), right_d.get(), out_d.get()); return NumberHelper::NumberToBigInt(out_d); } TEST(CudaBigIntTest, testMpzConversion) { BigInt start("1231490623"); NumData test; memset(test, 0, sizeof(uint32_t) * NUM_FIELDS); mpz_export(test, nullptr, -1, sizeof(uint32_t), 0, 0, start.get_mpz_t()); BigInt compare; mpz_import(compare.get_mpz_t(), NUM_FIELDS, -1, sizeof(uint32_t), 0, 0, test); EXPECT_EQ(start, compare); } TEST(CudaBigIntTest, testAddition) { BigInt left("12314906231232141243"); BigInt right("21317833214213"); BigInt expected("12314927549065355456"); auto actual = invokeKernel(left, right, testAdd); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSubtraction) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("90108101410172790"); auto actual = invokeKernel(left, right, testSub); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testMultiplication) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("70873452463358713606126842179959"); auto actual = invokeKernel(left, right, testMul); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testMultiplicationSmallNumbers) { BigInt left("5"); BigInt right("8"); BigInt expected("40"); auto actual = invokeKernel(left, right, testMul); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivision) { BigInt left("90887891231490623"); BigInt right("779789821317833"); BigInt expected("116"); auto actual = invokeKernel(left, right, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivisionEqualValues) { BigInt left("90887891231490623"); BigInt right("90887891231490623"); BigInt expected("1"); auto actual = invokeKernel(left, right, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testDivisionEqualOperands) { BigInt left("90887891231490623"); BigInt expected("1"); auto actual = invokeKernel(left, left, testDiv); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSmallerThan) { BigInt left("90887891231490623"); BigInt right("7797822229821317833"); bool expected(true); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testNotSmallerThan) { BigInt left("90887891231490624"); BigInt right("90887891231490623"); bool expected(false); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testSmallerThanWithEqualOperands) { BigInt left("90887891231490623"); BigInt right("90887891231490623"); bool expected(false); auto actual = invokeBoolKernel(left, right, testSmallerThan); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeft) { BigInt left("1"); uint32_t offset(32); BigInt expected("4294967296"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeftBiggerNumber) { BigInt left("1282943598234"); uint32_t offset(23); BigInt expected("10762110931694518272"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftLeftWithBigShiftOffset) { BigInt left("1282943598234"); uint32_t offset(3333); BigInt expected("0"); auto actual = invokeShiftKernel(left, offset, testShiftLeft); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRight) { BigInt left("4294967296"); uint32_t offset(32); BigInt expected("1"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightBiggerNumber) { BigInt left("1301820391234234234342"); uint32_t offset(33); BigInt expected("151551839806"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightBiggerNumber2) { BigInt left("2135987035920910082395021706169552114602704522356652769947041607822219725780640550022962086936575"); uint32_t offset(33); BigInt expected("248661618204893321077691124073410420050228075398673858720231988446579748506266687766527"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } TEST(CudaBigIntTest, testShiftRightWithBigShiftOffset) { BigInt left("1"); uint32_t offset(33333); BigInt expected("0"); auto actual = invokeShiftKernel(left, offset, testShiftRight); EXPECT_EQ(expected, actual); } <|endoftext|>
<commit_before>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #include "View.h" #include "ActionHandler.h" #include "Binding.h" DC_BEGIN_DREEMCHEST namespace mvvm { // ** View::notify void View::notify( const String& event ) { ActionHandlers::Parts& actionHandlers = m_actionHandlers.parts(); for( ActionHandlers::Parts::iterator i = actionHandlers.begin(), end = actionHandlers.end(); i != end; ++i ) { i->second->handleEvent( event ); } } // ** View::clear void View::clear( void ) { m_bindings.clear(); m_data.clear(); m_actionHandlers.clear(); } // ** View::addBinding void View::addBinding( Binding* instance ) { instance->refresh(); m_bindings.push_back( instance ); } } // namespace mvvm DC_END_DREEMCHEST <commit_msg>Fixed Mvvm::View compilation error<commit_after>/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #include "View.h" #include "ActionHandler.h" #include "Binding.h" DC_BEGIN_DREEMCHEST namespace mvvm { // ** View::notify void View::notify( const String& event ) { ActionHandlers::Parts& actionHandlers = m_actionHandlers.parts(); for( ActionHandlers::Parts::iterator i = actionHandlers.begin(), end = actionHandlers.end(); i != end; ++i ) { i->second->handleEvent( event ); } } // ** View::clear void View::clear( void ) { m_bindings.clear(); m_data.clear(); m_actionHandlers.clear(); } // ** View::addBinding void View::addBinding( Binding* instance ) { instance->refreshView(); m_bindings.push_back( instance ); } } // namespace mvvm DC_END_DREEMCHEST <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "buildsettingspropertiespage.h" #include "buildstep.h" #include "buildstepspage.h" #include "project.h" #include <coreplugin/coreconstants.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QInputDialog> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; /// /// BuildSettingsPanelFactory /// bool BuildSettingsPanelFactory::supports(Project *project) { return project->hasBuildSettings(); } PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project) { return new BuildSettingsPanel(project); } /// /// BuildSettingsPanel /// BuildSettingsPanel::BuildSettingsPanel(Project *project) : PropertiesPanel(), m_widget(new BuildSettingsWidget(project)) { } BuildSettingsPanel::~BuildSettingsPanel() { delete m_widget; } QString BuildSettingsPanel::name() const { return tr("Build Settings"); } QWidget *BuildSettingsPanel::widget() { return m_widget; } /// // BuildSettingsSubWidgets /// BuildSettingsSubWidgets::~BuildSettingsSubWidgets() { clear(); } void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget) { QLabel *label = new QLabel(this); label->setText(name); QFont f = label->font(); f.setBold(true); f.setPointSizeF(f.pointSizeF() *1.2); label->setFont(f); layout()->addWidget(label); layout()->addWidget(widget); m_labels.append(label); m_widgets.append(widget); } void BuildSettingsSubWidgets::clear() { qDeleteAll(m_widgets); qDeleteAll(m_labels); m_widgets.clear(); m_labels.clear(); } QList<QWidget *> BuildSettingsSubWidgets::widgets() const { return m_widgets; } BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent) : QGroupBox(parent) { new QVBoxLayout(this); } /// /// BuildSettingsWidget /// BuildSettingsWidget::~BuildSettingsWidget() { } BuildSettingsWidget::BuildSettingsWidget(Project *project) : m_project(project) { QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setContentsMargins(0, -1, 0, -1); QHBoxLayout *hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(tr("Build Configuration:"), this)); m_buildConfigurationComboBox = new QComboBox(this); hbox->addWidget(m_buildConfigurationComboBox); m_addButton = new QPushButton(this); m_addButton->setText(tr("Add")); m_addButton->setIcon(QIcon(Core::Constants::ICON_PLUS)); m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); hbox->addWidget(m_addButton); m_removeButton = new QPushButton(this); m_removeButton->setText(tr("Remove")); m_removeButton->setIcon(QIcon(Core::Constants::ICON_MINUS)); m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); hbox->addWidget(m_removeButton); hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed)); vbox->addLayout(hbox); m_subWidgets = new BuildSettingsSubWidgets(this); vbox->addWidget(m_subWidgets); QMenu *addButtonMenu = new QMenu(this); addButtonMenu->addAction(tr("Create &New"), this, SLOT(createConfiguration())); addButtonMenu->addAction(tr("&Clone Selected"), this, SLOT(cloneConfiguration())); m_addButton->setMenu(addButtonMenu); connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int))); // TODO currentIndexChanged // needs to change active configuration // and set widgets connect(m_removeButton, SIGNAL(clicked()), this, SLOT(deleteConfiguration())); connect(m_project, SIGNAL(activeBuildConfigurationChanged()), this, SLOT(activeBuildConfigurationChanged())); connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)), this, SLOT(buildConfigurationDisplayNameChanged(const QString &))); updateBuildSettings(); } void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration) { for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) { if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) { m_buildConfigurationComboBox->setItemText(i, m_project->displayNameFor(buildConfiguration)); break; } } } void BuildSettingsWidget::updateBuildSettings() { // TODO save position, entry from combbox // Delete old tree items m_buildConfigurationComboBox->blockSignals(true); // TODO ... m_buildConfigurationComboBox->clear(); m_subWidgets->clear(); // update buttons m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1); // Add pages BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget(); m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget); m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project)); m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true)); QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets(); foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets) m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget); // Add tree items QString activeBuildConfiguration = m_project->activeBuildConfiguration(); foreach (const QString &buildConfiguration, m_project->buildConfigurations()) { m_buildConfigurationComboBox->addItem(m_project->displayNameFor(buildConfiguration), buildConfiguration); if (buildConfiguration == activeBuildConfiguration) m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1); } // TODO ... m_buildConfigurationComboBox->blockSignals(false); // TODO Restore position, entry from combbox // TODO? select entry from combobox ? activeBuildConfigurationChanged(); } void BuildSettingsWidget::currentIndexChanged(int index) { QString buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString(); m_project->setActiveBuildConfiguration(buildConfiguration); } void BuildSettingsWidget::activeBuildConfigurationChanged() { const QString &activeBuildConfiguration = m_project->activeBuildConfiguration(); for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) { if (m_buildConfigurationComboBox->itemData(i).toString() == activeBuildConfiguration) { m_buildConfigurationComboBox->setCurrentIndex(i); break; } } foreach (QWidget *widget, m_subWidgets->widgets()) { if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) { buildStepWidget->init(activeBuildConfiguration); } } } void BuildSettingsWidget::createConfiguration() { bool ok; QString newBuildConfiguration = QInputDialog::getText(this, tr("New configuration"), tr("New Configuration Name:"), QLineEdit::Normal, QString(), &ok); if (!ok || newBuildConfiguration.isEmpty()) return; QString newDisplayName = newBuildConfiguration; // Check that the internal name is not taken and use a different one otherwise const QStringList &buildConfigurations = m_project->buildConfigurations(); if (buildConfigurations.contains(newBuildConfiguration)) { int i = 2; while (buildConfigurations.contains(newBuildConfiguration + QString::number(i))) ++i; newBuildConfiguration += QString::number(i); } // Check that we don't have a configuration with the same displayName QStringList displayNames; foreach (const QString &bc, buildConfigurations) displayNames << m_project->displayNameFor(bc); if (displayNames.contains(newDisplayName)) { int i = 2; while (displayNames.contains(newDisplayName + QString::number(i))) ++i; newDisplayName += QString::number(i); } m_project->addBuildConfiguration(newBuildConfiguration); m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName); m_project->newBuildConfiguration(newBuildConfiguration); m_project->setActiveBuildConfiguration(newBuildConfiguration); updateBuildSettings(); } void BuildSettingsWidget::cloneConfiguration() { const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString(); cloneConfiguration(configuration); } void BuildSettingsWidget::deleteConfiguration() { const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString(); deleteConfiguration(configuration); } void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration) { if (sourceConfiguration.isEmpty()) return; QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")); if (newBuildConfiguration.isEmpty()) return; QString newDisplayName = newBuildConfiguration; // Check that the internal name is not taken and use a different one otherwise const QStringList &buildConfigurations = m_project->buildConfigurations(); if (buildConfigurations.contains(newBuildConfiguration)) { int i = 2; while (buildConfigurations.contains(newBuildConfiguration + QString::number(i))) ++i; newBuildConfiguration += QString::number(i); } // Check that we don't have a configuration with the same displayName QStringList displayNames; foreach (const QString &bc, buildConfigurations) displayNames << m_project->displayNameFor(bc); if (displayNames.contains(newDisplayName)) { int i = 2; while (displayNames.contains(newDisplayName + QString::number(i))) ++i; newDisplayName += QString::number(i); } m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration); m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName); updateBuildSettings(); m_project->setActiveBuildConfiguration(newBuildConfiguration); } void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration) { if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1) return; if (m_project->activeBuildConfiguration() == deleteConfiguration) { foreach (const QString &otherConfiguration, m_project->buildConfigurations()) { if (otherConfiguration != deleteConfiguration) { m_project->setActiveBuildConfiguration(otherConfiguration); break; } } } m_project->removeBuildConfiguration(deleteConfiguration); updateBuildSettings(); } <commit_msg>Build Configuration Combobx on project page not adjusting to contents.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "buildsettingspropertiespage.h" #include "buildstep.h" #include "buildstepspage.h" #include "project.h" #include <coreplugin/coreconstants.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QInputDialog> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; /// /// BuildSettingsPanelFactory /// bool BuildSettingsPanelFactory::supports(Project *project) { return project->hasBuildSettings(); } PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project) { return new BuildSettingsPanel(project); } /// /// BuildSettingsPanel /// BuildSettingsPanel::BuildSettingsPanel(Project *project) : PropertiesPanel(), m_widget(new BuildSettingsWidget(project)) { } BuildSettingsPanel::~BuildSettingsPanel() { delete m_widget; } QString BuildSettingsPanel::name() const { return tr("Build Settings"); } QWidget *BuildSettingsPanel::widget() { return m_widget; } /// // BuildSettingsSubWidgets /// BuildSettingsSubWidgets::~BuildSettingsSubWidgets() { clear(); } void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget) { QLabel *label = new QLabel(this); label->setText(name); QFont f = label->font(); f.setBold(true); f.setPointSizeF(f.pointSizeF() *1.2); label->setFont(f); layout()->addWidget(label); layout()->addWidget(widget); m_labels.append(label); m_widgets.append(widget); } void BuildSettingsSubWidgets::clear() { qDeleteAll(m_widgets); qDeleteAll(m_labels); m_widgets.clear(); m_labels.clear(); } QList<QWidget *> BuildSettingsSubWidgets::widgets() const { return m_widgets; } BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent) : QGroupBox(parent) { new QVBoxLayout(this); } /// /// BuildSettingsWidget /// BuildSettingsWidget::~BuildSettingsWidget() { } BuildSettingsWidget::BuildSettingsWidget(Project *project) : m_project(project) { QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setContentsMargins(0, -1, 0, -1); QHBoxLayout *hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(tr("Build Configuration:"), this)); m_buildConfigurationComboBox = new QComboBox(this); m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); hbox->addWidget(m_buildConfigurationComboBox); m_addButton = new QPushButton(this); m_addButton->setText(tr("Add")); m_addButton->setIcon(QIcon(Core::Constants::ICON_PLUS)); m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); hbox->addWidget(m_addButton); m_removeButton = new QPushButton(this); m_removeButton->setText(tr("Remove")); m_removeButton->setIcon(QIcon(Core::Constants::ICON_MINUS)); m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); hbox->addWidget(m_removeButton); hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed)); vbox->addLayout(hbox); m_subWidgets = new BuildSettingsSubWidgets(this); vbox->addWidget(m_subWidgets); QMenu *addButtonMenu = new QMenu(this); addButtonMenu->addAction(tr("Create &New"), this, SLOT(createConfiguration())); addButtonMenu->addAction(tr("&Clone Selected"), this, SLOT(cloneConfiguration())); m_addButton->setMenu(addButtonMenu); connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int))); // TODO currentIndexChanged // needs to change active configuration // and set widgets connect(m_removeButton, SIGNAL(clicked()), this, SLOT(deleteConfiguration())); connect(m_project, SIGNAL(activeBuildConfigurationChanged()), this, SLOT(activeBuildConfigurationChanged())); connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)), this, SLOT(buildConfigurationDisplayNameChanged(const QString &))); updateBuildSettings(); } void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration) { for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) { if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) { m_buildConfigurationComboBox->setItemText(i, m_project->displayNameFor(buildConfiguration)); break; } } } void BuildSettingsWidget::updateBuildSettings() { // TODO save position, entry from combbox // Delete old tree items m_buildConfigurationComboBox->blockSignals(true); // TODO ... m_buildConfigurationComboBox->clear(); m_subWidgets->clear(); // update buttons m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1); // Add pages BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget(); m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget); m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project)); m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true)); QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets(); foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets) m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget); // Add tree items QString activeBuildConfiguration = m_project->activeBuildConfiguration(); foreach (const QString &buildConfiguration, m_project->buildConfigurations()) { m_buildConfigurationComboBox->addItem(m_project->displayNameFor(buildConfiguration), buildConfiguration); if (buildConfiguration == activeBuildConfiguration) m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1); } // TODO ... m_buildConfigurationComboBox->blockSignals(false); // TODO Restore position, entry from combbox // TODO? select entry from combobox ? activeBuildConfigurationChanged(); } void BuildSettingsWidget::currentIndexChanged(int index) { QString buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString(); m_project->setActiveBuildConfiguration(buildConfiguration); } void BuildSettingsWidget::activeBuildConfigurationChanged() { const QString &activeBuildConfiguration = m_project->activeBuildConfiguration(); for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) { if (m_buildConfigurationComboBox->itemData(i).toString() == activeBuildConfiguration) { m_buildConfigurationComboBox->setCurrentIndex(i); break; } } foreach (QWidget *widget, m_subWidgets->widgets()) { if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) { buildStepWidget->init(activeBuildConfiguration); } } } void BuildSettingsWidget::createConfiguration() { bool ok; QString newBuildConfiguration = QInputDialog::getText(this, tr("New configuration"), tr("New Configuration Name:"), QLineEdit::Normal, QString(), &ok); if (!ok || newBuildConfiguration.isEmpty()) return; QString newDisplayName = newBuildConfiguration; // Check that the internal name is not taken and use a different one otherwise const QStringList &buildConfigurations = m_project->buildConfigurations(); if (buildConfigurations.contains(newBuildConfiguration)) { int i = 2; while (buildConfigurations.contains(newBuildConfiguration + QString::number(i))) ++i; newBuildConfiguration += QString::number(i); } // Check that we don't have a configuration with the same displayName QStringList displayNames; foreach (const QString &bc, buildConfigurations) displayNames << m_project->displayNameFor(bc); if (displayNames.contains(newDisplayName)) { int i = 2; while (displayNames.contains(newDisplayName + QString::number(i))) ++i; newDisplayName += QString::number(i); } m_project->addBuildConfiguration(newBuildConfiguration); m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName); m_project->newBuildConfiguration(newBuildConfiguration); m_project->setActiveBuildConfiguration(newBuildConfiguration); updateBuildSettings(); } void BuildSettingsWidget::cloneConfiguration() { const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString(); cloneConfiguration(configuration); } void BuildSettingsWidget::deleteConfiguration() { const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString(); deleteConfiguration(configuration); } void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration) { if (sourceConfiguration.isEmpty()) return; QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")); if (newBuildConfiguration.isEmpty()) return; QString newDisplayName = newBuildConfiguration; // Check that the internal name is not taken and use a different one otherwise const QStringList &buildConfigurations = m_project->buildConfigurations(); if (buildConfigurations.contains(newBuildConfiguration)) { int i = 2; while (buildConfigurations.contains(newBuildConfiguration + QString::number(i))) ++i; newBuildConfiguration += QString::number(i); } // Check that we don't have a configuration with the same displayName QStringList displayNames; foreach (const QString &bc, buildConfigurations) displayNames << m_project->displayNameFor(bc); if (displayNames.contains(newDisplayName)) { int i = 2; while (displayNames.contains(newDisplayName + QString::number(i))) ++i; newDisplayName += QString::number(i); } m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration); m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName); updateBuildSettings(); m_project->setActiveBuildConfiguration(newBuildConfiguration); } void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration) { if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1) return; if (m_project->activeBuildConfiguration() == deleteConfiguration) { foreach (const QString &otherConfiguration, m_project->buildConfigurations()) { if (otherConfiguration != deleteConfiguration) { m_project->setActiveBuildConfiguration(otherConfiguration); break; } } } m_project->removeBuildConfiguration(deleteConfiguration); updateBuildSettings(); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, H; int A[100010]; int B[100010]; int C[100010]; int D[100010]; vector<int> V[420]; int M = 210; int input[420]; int output[420]; int from[420]; int visited[420]; bool ret = true; void add_edge(int i) { int from, to; if (C[i] == 0) { from = A[i]; } else { from = -C[i]; } if (D[i] == 0) { to = -B[i]; } else { to = D[i]; } V[from + M].push_back(to + M); output[from + M]++; input[to + M]++; } void visit(int i, int p) { if (visited[i] == -1) { from[i] = p; int now = p; bool ok = false; while (now != i) { if (output[now] == input[now]) { now = from[now]; } else { ok = true; break; } } if (!ok) { ret = false; } } else if (visited[i] == -2) { from[i] = p; visited[i] = -1; for (auto x : V[i]) { visit(x, i); } visited[i] = 0; } } int main () { cin >> N >> H; fill(input, input+420, 0); fill(output, output+420, 0); for (auto i = 0; i < N; ++i) { cin >> A[i] >> B[i] >> C[i] >> D[i]; add_edge(i); } for (auto i = 1; i <= H; ++i) { if (input[i + M] > output[i + M]) { cout << "NO" << endl; return 0; } } for (auto i = 1; i <= H; ++i) { if (input[-i + M] < output[-i + M]) { cout << "NO" << endl; return 0; } } fill(visited, visited+420, -2); fill(from, from+420, -1); for (auto i = 1; i <= H; ++i) { visit(i + M, -1); visit(-i + M, -1); } cout << (ret ? "YES" : "NO") << endl; } <commit_msg>submit E.cpp to 'E - Jigsaw' (agc017) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, H; int A[100010]; int B[100010]; int C[100010]; int D[100010]; vector<int> V[420]; int M = 210; int input[420]; int output[420]; int from[420]; int visited[420]; bool ret = true; void add_edge(int i) { int from, to; if (C[i] == 0) { from = A[i]; } else { from = -C[i]; } if (D[i] == 0) { to = -B[i]; } else { to = D[i]; } V[from + M].push_back(to + M); output[from + M]++; input[to + M]++; } void visit(int i, int p) { if (visited[i] == -1) { from[i] = p; int now = p; bool ok = false; while (now != i) { if (output[now] == 1 && input[now] == 1) { now = from[now]; } else { ok = true; break; } } if (!ok) { ret = false; } } else if (visited[i] == -2) { from[i] = p; visited[i] = -1; for (auto x : V[i]) { visit(x, i); } visited[i] = 0; } } int main () { cin >> N >> H; fill(input, input+420, 0); fill(output, output+420, 0); for (auto i = 0; i < N; ++i) { cin >> A[i] >> B[i] >> C[i] >> D[i]; add_edge(i); } for (auto i = 1; i <= H; ++i) { if (input[i + M] > output[i + M]) { cout << "NO" << endl; return 0; } } for (auto i = 1; i <= H; ++i) { if (input[-i + M] < output[-i + M]) { cout << "NO" << endl; return 0; } } fill(visited, visited+420, -2); fill(from, from+420, -1); for (auto i = 1; i <= H; ++i) { visit(i + M, -1); visit(-i + M, -1); } cout << (ret ? "YES" : "NO") << endl; } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } } // namespace <commit_msg>DevTools: temporarily disable breakpoint tests<commit_after>// Copyright (c) 2009 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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } } // namespace <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ephemeral_bucket_test.h" #include "ephemeral_bucket.h" #include "test_helpers.h" #include "../mock/mock_dcp_consumer.h" #include "dcp/dcpconnmap.h" /* * Test statistics related to an individual VBucket's sequence list. */ void EphemeralBucketStatTest::addDocumentsForSeqListTesting(uint16_t vb) { // Add some documents to the vBucket to use to test the stats. store_item(vb, makeStoredDocKey("deleted"), "value"); delete_item(vb, makeStoredDocKey("deleted")); store_item(vb, makeStoredDocKey("doc"), "value"); store_item(vb, makeStoredDocKey("doc"), "value 2"); } TEST_F(EphemeralBucketStatTest, VBSeqlistStats) { // Check preconditions. auto stats = get_stat("vbucket-details 0"); ASSERT_EQ("0", stats.at("vb_0:seqlist_high_seqno")); // Add some documents to the vBucket to use to test the stats. addDocumentsForSeqListTesting(vbid); stats = get_stat("vbucket-details 0"); EXPECT_EQ("0", stats.at("vb_0:auto_delete_count")); EXPECT_EQ("2", stats.at("vb_0:seqlist_count")) << "Expected both current and deleted documents"; EXPECT_EQ("1", stats.at("vb_0:seqlist_deleted_count")); EXPECT_EQ("4", stats.at("vb_0:seqlist_high_seqno")); EXPECT_EQ("4", stats.at("vb_0:seqlist_highest_deduped_seqno")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_begin")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_end")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_count")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_count")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_value_bytes")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_metadata_bytes")); // Trigger the "automatic" deletion of an item by paging it out. auto vb = store->getVBucket(vbid); auto key = makeStoredDocKey("doc"); auto lock = vb->ht.getLockedBucket(key); auto* value = vb->fetchValidValue( lock, key, WantsDeleted::No, TrackReference::Yes, QueueExpired::No); ASSERT_TRUE(vb->pageOut(lock, value)); stats = get_stat("vbucket-details 0"); EXPECT_EQ("1", stats.at("vb_0:auto_delete_count")); EXPECT_EQ("2", stats.at("vb_0:seqlist_deleted_count")); EXPECT_EQ("5", stats.at("vb_0:seqlist_high_seqno")); } TEST_F(SingleThreadedEphemeralBackfillTest, RangeIteratorVBDeleteRaceTest) { /* The destructor of RangeIterator attempts to release locks in the * seqList, which is owned by the Ephemeral VB. If the evb is * destructed before the iterator, unexepected behaviour will arise. * In MB-24631 the destructor spun trying to acquire a lock which * was now garbage data after the memory was reused. * * Due to the variable results of this, the test alone does not * confirm the absence of this issue, but AddressSanitizer should * report heap-use-after-free. */ // Make vbucket active. setVBucketStateAndRunPersistTask(vbid, vbucket_state_active); auto vb = store->getVBuckets().getBucket(vbid); ASSERT_NE(nullptr, vb.get()); // prep data store_item(vbid, makeStoredDocKey("key1"), "value"); store_item(vbid, makeStoredDocKey("key2"), "value"); auto& ckpt_mgr = vb->checkpointManager; ASSERT_EQ(1, ckpt_mgr.getNumCheckpoints()); // make checkpoint to cause backfill later rather than straight to in-memory ckpt_mgr.createNewCheckpoint(); bool new_ckpt_created; ASSERT_EQ(2, ckpt_mgr.removeClosedUnrefCheckpoints(*vb, new_ckpt_created)); // Create a Mock Dcp producer mock_dcp_producer_t producer = new MockDcpProducer(*engine, cookie, "test_producer", /*flags*/ 0, {/*no json*/}); // Create a Mock Active Stream stream_t stream = new MockActiveStream( static_cast<EventuallyPersistentEngine*>(engine.get()), producer, /*flags*/ 0, /*opaque*/ 0, *vb, /*st_seqno*/ 0, /*en_seqno*/ ~0, /*vb_uuid*/ 0xabcd, /*snap_start_seqno*/ 0, /*snap_end_seqno*/ ~0, IncludeValue::Yes, IncludeXattrs::Yes); MockActiveStream* mock_stream = static_cast<MockActiveStream*>(stream.get()); ASSERT_TRUE(mock_stream->isPending()) << "stream state should be Pending"; mock_stream->transitionStateToBackfilling(); ASSERT_TRUE(mock_stream->isBackfilling()) << "stream state should have transitioned to Backfilling"; size_t byteLimit = engine->getConfiguration().getDcpScanByteLimit(); auto& manager = producer->getBFM(); /* Hack to make DCPBackfillMemoryBuffered::create construct the range * iterator, but DCPBackfillMemoryBuffered::scan /not/ complete the * backfill immediately - we pretend the buffer is full. This is * reset in manager->backfill() */ manager.bytesCheckAndRead(byteLimit + 1); // Directly run backfill once, to create the range iterator manager.backfill(); const char* vbDeleteTaskName = "Removing (dead) vb:0 from memory"; ASSERT_FALSE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); /* Bin the vbucket. This will eventually lead to the destruction of * the seqList. If the vb were to be destroyed *now*, * AddressSanitizer would report heap-use-after-free when the * DCPBackfillMemoryBuffered is destroyed (it owns a range iterator) * This should no longer happen, as the backfill now hold a * shared_ptr to the evb. */ store->deleteVBucket(vbid, nullptr); vb.reset(); // vb can't yet be deleted, there is a range iterator over it still! EXPECT_FALSE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); // Now bin the producer engine->getDcpConnMap().shutdownAllConnections(); stream.reset(); producer.reset(); // run the backfill task so the backfill can reach state // backfill_finished and be destroyed destroying the range iterator // in the process auto& lpAuxioQ = *task_executor->getLpTaskQ()[AUXIO_TASK_IDX]; runNextTask(lpAuxioQ, "Backfilling items for a DCP Connection"); // Now the backfill is gone, the evb can be deleted EXPECT_TRUE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); } class SingleThreadedEphemeralPurgerTest : public SingleThreadedKVBucketTest { protected: void SetUp() override { config_string += "bucket_type=ephemeral;" "max_vbuckets=" + std::to_string(numVbs) + ";" "ephemeral_metadata_purge_age=0;" "ephemeral_metadata_purge_stale_chunk_duration=0"; SingleThreadedKVBucketTest::SetUp(); /* Set up 4 vbuckets */ for (int vbid = 0; vbid < numVbs; ++vbid) { setVBucketStateAndRunPersistTask(vbid, vbucket_state_active); } } bool checkAllPurged(uint64_t expPurgeUpto) { for (int vbid = 0; vbid < numVbs; ++vbid) { if (store->getVBucket(vbid)->getPurgeSeqno() < expPurgeUpto) { return false; } } return true; } const int numVbs = 4; }; TEST_F(SingleThreadedEphemeralPurgerTest, manu) { /* Set 100 item in all vbuckets. We need hundred items atleast because our ProgressTracker checks whether to pause only after INITIAL_VISIT_COUNT_CHECK = 100 */ const int numItems = 100; for (int vbid = 0; vbid < numVbs; ++vbid) { for (int i = 0; i < numItems; ++i) { const std::string key("key" + std::to_string(vbid) + std::to_string(i)); store_item(vbid, makeStoredDocKey(key), "value"); } } /* Add and delete an item in every vbucket */ for (int vbid = 0; vbid < numVbs; ++vbid) { const std::string key("keydelete" + std::to_string(vbid)); storeAndDeleteItem(vbid, makeStoredDocKey(key), "value"); } /* We have added an item at seqno 100 and deleted it immediately */ const uint64_t expPurgeUpto = numItems + 2; /* Add another item as we do not purge last element in the list */ for (int vbid = 0; vbid < numVbs; ++vbid) { const std::string key("afterdelete" + std::to_string(vbid)); store_item(vbid, makeStoredDocKey(key), "value"); } /* Run the HTCleaner task, so that we can wake up the stale item deleter */ EphemeralBucket* bucket = dynamic_cast<EphemeralBucket*>(store); bucket->enableTombstonePurgerTask(); bucket->attemptToFreeMemory(); // this wakes up the HTCleaner task auto& lpAuxioQ = *task_executor->getLpTaskQ()[NONIO_TASK_IDX]; runNextTask(lpAuxioQ, "Eph tombstone hashtable cleaner"); /* Run the EphTombstoneStaleItemDeleter task. It we expect it to pause and resume atleast once. We run it, until it purges all the deleted across all the vbuckets */ int numPaused = -1; while (!checkAllPurged(expPurgeUpto)) { runNextTask(lpAuxioQ, "Eph tombstone stale item deleter"); ++numPaused; } EXPECT_GE(numPaused, 1); } <commit_msg>[2.5/n] MB-25920: Fix a race condition in StaleItemDeleter test<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ephemeral_bucket_test.h" #include "ephemeral_bucket.h" #include "test_helpers.h" #include "../mock/mock_dcp_consumer.h" #include "dcp/dcpconnmap.h" /* * Test statistics related to an individual VBucket's sequence list. */ void EphemeralBucketStatTest::addDocumentsForSeqListTesting(uint16_t vb) { // Add some documents to the vBucket to use to test the stats. store_item(vb, makeStoredDocKey("deleted"), "value"); delete_item(vb, makeStoredDocKey("deleted")); store_item(vb, makeStoredDocKey("doc"), "value"); store_item(vb, makeStoredDocKey("doc"), "value 2"); } TEST_F(EphemeralBucketStatTest, VBSeqlistStats) { // Check preconditions. auto stats = get_stat("vbucket-details 0"); ASSERT_EQ("0", stats.at("vb_0:seqlist_high_seqno")); // Add some documents to the vBucket to use to test the stats. addDocumentsForSeqListTesting(vbid); stats = get_stat("vbucket-details 0"); EXPECT_EQ("0", stats.at("vb_0:auto_delete_count")); EXPECT_EQ("2", stats.at("vb_0:seqlist_count")) << "Expected both current and deleted documents"; EXPECT_EQ("1", stats.at("vb_0:seqlist_deleted_count")); EXPECT_EQ("4", stats.at("vb_0:seqlist_high_seqno")); EXPECT_EQ("4", stats.at("vb_0:seqlist_highest_deduped_seqno")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_begin")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_end")); EXPECT_EQ("0", stats.at("vb_0:seqlist_range_read_count")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_count")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_value_bytes")); EXPECT_EQ("0", stats.at("vb_0:seqlist_stale_metadata_bytes")); // Trigger the "automatic" deletion of an item by paging it out. auto vb = store->getVBucket(vbid); auto key = makeStoredDocKey("doc"); auto lock = vb->ht.getLockedBucket(key); auto* value = vb->fetchValidValue( lock, key, WantsDeleted::No, TrackReference::Yes, QueueExpired::No); ASSERT_TRUE(vb->pageOut(lock, value)); stats = get_stat("vbucket-details 0"); EXPECT_EQ("1", stats.at("vb_0:auto_delete_count")); EXPECT_EQ("2", stats.at("vb_0:seqlist_deleted_count")); EXPECT_EQ("5", stats.at("vb_0:seqlist_high_seqno")); } TEST_F(SingleThreadedEphemeralBackfillTest, RangeIteratorVBDeleteRaceTest) { /* The destructor of RangeIterator attempts to release locks in the * seqList, which is owned by the Ephemeral VB. If the evb is * destructed before the iterator, unexepected behaviour will arise. * In MB-24631 the destructor spun trying to acquire a lock which * was now garbage data after the memory was reused. * * Due to the variable results of this, the test alone does not * confirm the absence of this issue, but AddressSanitizer should * report heap-use-after-free. */ // Make vbucket active. setVBucketStateAndRunPersistTask(vbid, vbucket_state_active); auto vb = store->getVBuckets().getBucket(vbid); ASSERT_NE(nullptr, vb.get()); // prep data store_item(vbid, makeStoredDocKey("key1"), "value"); store_item(vbid, makeStoredDocKey("key2"), "value"); auto& ckpt_mgr = vb->checkpointManager; ASSERT_EQ(1, ckpt_mgr.getNumCheckpoints()); // make checkpoint to cause backfill later rather than straight to in-memory ckpt_mgr.createNewCheckpoint(); bool new_ckpt_created; ASSERT_EQ(2, ckpt_mgr.removeClosedUnrefCheckpoints(*vb, new_ckpt_created)); // Create a Mock Dcp producer mock_dcp_producer_t producer = new MockDcpProducer(*engine, cookie, "test_producer", /*flags*/ 0, {/*no json*/}); // Create a Mock Active Stream stream_t stream = new MockActiveStream( static_cast<EventuallyPersistentEngine*>(engine.get()), producer, /*flags*/ 0, /*opaque*/ 0, *vb, /*st_seqno*/ 0, /*en_seqno*/ ~0, /*vb_uuid*/ 0xabcd, /*snap_start_seqno*/ 0, /*snap_end_seqno*/ ~0, IncludeValue::Yes, IncludeXattrs::Yes); MockActiveStream* mock_stream = static_cast<MockActiveStream*>(stream.get()); ASSERT_TRUE(mock_stream->isPending()) << "stream state should be Pending"; mock_stream->transitionStateToBackfilling(); ASSERT_TRUE(mock_stream->isBackfilling()) << "stream state should have transitioned to Backfilling"; size_t byteLimit = engine->getConfiguration().getDcpScanByteLimit(); auto& manager = producer->getBFM(); /* Hack to make DCPBackfillMemoryBuffered::create construct the range * iterator, but DCPBackfillMemoryBuffered::scan /not/ complete the * backfill immediately - we pretend the buffer is full. This is * reset in manager->backfill() */ manager.bytesCheckAndRead(byteLimit + 1); // Directly run backfill once, to create the range iterator manager.backfill(); const char* vbDeleteTaskName = "Removing (dead) vb:0 from memory"; ASSERT_FALSE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); /* Bin the vbucket. This will eventually lead to the destruction of * the seqList. If the vb were to be destroyed *now*, * AddressSanitizer would report heap-use-after-free when the * DCPBackfillMemoryBuffered is destroyed (it owns a range iterator) * This should no longer happen, as the backfill now hold a * shared_ptr to the evb. */ store->deleteVBucket(vbid, nullptr); vb.reset(); // vb can't yet be deleted, there is a range iterator over it still! EXPECT_FALSE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); // Now bin the producer engine->getDcpConnMap().shutdownAllConnections(); stream.reset(); producer.reset(); // run the backfill task so the backfill can reach state // backfill_finished and be destroyed destroying the range iterator // in the process auto& lpAuxioQ = *task_executor->getLpTaskQ()[AUXIO_TASK_IDX]; runNextTask(lpAuxioQ, "Backfilling items for a DCP Connection"); // Now the backfill is gone, the evb can be deleted EXPECT_TRUE( task_executor->isTaskScheduled(NONIO_TASK_IDX, vbDeleteTaskName)); } class SingleThreadedEphemeralPurgerTest : public SingleThreadedKVBucketTest { protected: void SetUp() override { config_string += "bucket_type=ephemeral;" "max_vbuckets=" + std::to_string(numVbs) + ";" "ephemeral_metadata_purge_age=0;" "ephemeral_metadata_purge_stale_chunk_duration=0"; SingleThreadedKVBucketTest::SetUp(); /* Set up 4 vbuckets */ for (int vbid = 0; vbid < numVbs; ++vbid) { setVBucketStateAndRunPersistTask(vbid, vbucket_state_active); } } bool checkAllPurged(uint64_t expPurgeUpto) { for (int vbid = 0; vbid < numVbs; ++vbid) { if (store->getVBucket(vbid)->getPurgeSeqno() < expPurgeUpto) { return false; } } return true; } const int numVbs = 4; }; TEST_F(SingleThreadedEphemeralPurgerTest, PurgeAcrossAllVbuckets) { /* Set 100 item in all vbuckets. We need hundred items atleast because our ProgressTracker checks whether to pause only after INITIAL_VISIT_COUNT_CHECK = 100 */ const int numItems = 100; for (int vbid = 0; vbid < numVbs; ++vbid) { for (int i = 0; i < numItems; ++i) { const std::string key("key" + std::to_string(vbid) + std::to_string(i)); store_item(vbid, makeStoredDocKey(key), "value"); } } /* Add and delete an item in every vbucket */ for (int vbid = 0; vbid < numVbs; ++vbid) { const std::string key("keydelete" + std::to_string(vbid)); storeAndDeleteItem(vbid, makeStoredDocKey(key), "value"); } /* We have added an item at seqno 100 and deleted it immediately */ const uint64_t expPurgeUpto = numItems + 2; /* Add another item as we do not purge last element in the list */ for (int vbid = 0; vbid < numVbs; ++vbid) { const std::string key("afterdelete" + std::to_string(vbid)); store_item(vbid, makeStoredDocKey(key), "value"); } /* Run the HTCleaner task, so that we can wake up the stale item deleter */ EphemeralBucket* bucket = dynamic_cast<EphemeralBucket*>(store); bucket->enableTombstonePurgerTask(); bucket->attemptToFreeMemory(); // this wakes up the HTCleaner task auto& lpAuxioQ = *task_executor->getLpTaskQ()[NONIO_TASK_IDX]; /* Run the HTCleaner and EphTombstoneStaleItemDeleter tasks. We expect pause and resume of EphTombstoneStaleItemDeleter atleast once and we run until all the deleted items across all the vbuckets are purged */ int numPaused = 0; while (!checkAllPurged(expPurgeUpto)) { runNextTask(lpAuxioQ); ++numPaused; } EXPECT_GT(numPaused, 2 /* 1 run of 'HTCleaner' and more than 1 run of 'EphTombstoneStaleItemDeleter' */); } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "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 Nokia Corporation and its Subsidiary(-ies) 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." ****************************************************************************/ #include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #include <sqlite3.h> #define DEBUG if (0) qDebug() << this << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { m_refreshTimer.setInterval(10000); connect(&m_refreshTimer, SIGNAL(timeout()), this, SLOT(refresh())); MediaScanner *scanner = Backend::instance()->mediaScanner(); connect(scanner, SIGNAL(scanStarted(QString)), this, SLOT(handleScanStarted(QString))); connect(scanner, SIGNAL(scanFinished(QString)), this, SLOT(handleScanFinished(QString))); connect(scanner, SIGNAL(searchPathRemoved(QString, QString)), this, SLOT(handleScanFinished(QString))); m_readerThread = new QThread(this); m_readerThread->start(); } MediaModel::~MediaModel() { if (m_reader) { m_reader->stop(); m_reader->deleteLater(); m_readerThread->quit(); m_readerThread->wait(); } } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { if (type == m_mediaType) return; DEBUG << type; m_mediaType = type; emit mediaTypeChanged(); // Add the fields of the table as role names QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(DotDotRole, "dotdot"); hash.insert(IsLeafRole, "isLeaf"); hash.insert(ModelIndexRole,"modelIndex"); hash.insert(PreviewUrlRole, "previewUrl"); for (int i = 0; i < record.count(); i++) { hash.insert(FieldRolesBegin + i, record.fieldName(i).toUtf8()); m_fieldToRole.insert(record.fieldName(i), FieldRolesBegin + i); } setRoleNames(hash); reload(); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { if (str == m_structure) return; DEBUG << str; m_structure = str; m_layoutInfo.clear(); foreach(const QString &part, m_structure.split("|")) m_layoutInfo.append(part.split(",")); reload(); emit structureChanged(); } void MediaModel::enter(int index) { if (m_cursor.count() + 1 == m_layoutInfo.count() && !m_data.at(index)[DotDotRole].toBool() /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (m_data.at(index)[DotDotRole].toBool() && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); reload(); emit partChanged(); } void MediaModel::back(int count) { if (count == 0 || m_cursor.count() < 1) return; if (m_cursor.count() > count) { for (int i = 0; i < count; ++i) m_cursor.removeLast(); } else { m_cursor.clear(); } reload(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == ModelIndexRole) return qVariantFromValue(index); return m_data.value(index.row()).value(role); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_layoutInfo.isEmpty()) { DEBUG << "false " << parent.isValid() << m_mediaType.isEmpty() << m_layoutInfo.isEmpty(); return false; } DEBUG << (!m_loading && !m_loaded); return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; DEBUG << ""; m_loading = true; QSqlQuery q = buildQuery(); DEBUG << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::createNewDbReader() { DEBUG << ""; if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = new DbReader; m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); } void MediaModel::reload() { createNewDbReader(); beginResetModel(); m_loading = m_loaded = false; m_data.clear(); endResetModel(); } QHash<int, QVariant> MediaModel::dataFromRecord(const QSqlRecord &record) const { QHash<int, QVariant> data; for (int j = 0; j < record.count(); j++) { int role = m_fieldToRole.value(record.fieldName(j)); if (record.fieldName(j) == "uri") data.insert(role, QUrl::fromEncoded(record.value(j).toByteArray())); else data.insert(role, record.value(j)); } // Provide 'display' role as , separated values QStringList cols = m_layoutInfo.value(m_cursor.count()); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << record.value(cols[j]).toString(); } data.insert(Qt::DisplayRole, displayString.join(", ")); data.insert(DotDotRole, false); data.insert(IsLeafRole, m_cursor.count() + 1 == m_layoutInfo.count()); data.insert(PreviewUrlRole, QUrl::fromEncoded(record.value("thumbnail").toByteArray())); return data; } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (m_data.isEmpty()) { insertAll(records); } else { insertNew(records); } m_loading = false; m_loaded = true; } void MediaModel::insertAll(const QList<QSqlRecord> &records) { if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } for (int i = 0; i < records.count(); i++) { QHash<int, QVariant> data = dataFromRecord(records[i]); m_data.append(data); } if (!m_cursor.isEmpty()) { QHash<int, QVariant> data; data.insert(Qt::DisplayRole, tr("..")); data.insert(DotDotRole, true); data.insert(IsLeafRole, false); m_data.append(data); } endInsertRows(); } int MediaModel::compareData(int idx, const QSqlRecord &record) const { const QHash<int, QVariant> &curData = m_data[idx]; QStringList cols = m_layoutInfo.value(m_cursor.count()); foreach(const QString &col, cols) { const int role = m_fieldToRole.value(col); int cmp = QString::compare(curData.value(role).toString(), record.value(col).toString(), Qt::CaseInsensitive); // ## must use sqlite's compare if (cmp != 0) return cmp; } return 0; } void MediaModel::insertNew(const QList<QSqlRecord> &records) { int old = 0, shiny = 0; while (shiny < records.length()) { const QSqlRecord &record = records[shiny]; int cmp = old == m_data.count() ? 1 : compareData(old, record); if (cmp == 0) { ++old; ++shiny; } else if (cmp < 0) { beginRemoveRows(QModelIndex(), old, old); m_data.removeAt(old); endRemoveRows(); } else { beginInsertRows(QModelIndex(), old, old); m_data.insert(old, dataFromRecord(record)); endInsertRows(); ++old; ++shiny; } } } QSqlQuery MediaModel::buildQuery() const { QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QStringList escapedCurParts; QStringList curParts = m_layoutInfo[m_cursor.count()]; for (int i = 0; i < curParts.count(); i++) escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName)); QString escapedCurPart = escapedCurParts.join(","); QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); QStringList placeHolders; const bool lastPart = m_cursor.count() == m_layoutInfo.count()-1; QString queryString; // SQLite allows us to select columns that are not present in the GROUP BY. We use this feature // to select thumbnails for non-leaf nodes queryString.append("SELECT *"); queryString.append(" FROM " + driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName)); if (!m_cursor.isEmpty()) { QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QStringList subParts = m_layoutInfo[i]; for (int j = 0; j < subParts.count(); j++) { where.append(subParts[j] + " = ?"); const int role = m_fieldToRole.value(subParts[j]); placeHolders << m_cursor[i].value(role).toString(); } } queryString.append(" WHERE " + where.join(" AND ")); } if (!lastPart) queryString.append(" GROUP BY " + escapedCurPart); queryString.append(" ORDER BY " + escapedCurPart + " COLLATE NOCASE"); query.prepare(queryString); foreach(const QString &placeHolder, placeHolders) query.addBindValue(placeHolder); return query; } void MediaModel::handleScanStarted(const QString &type) { if (type != m_mediaType) return; m_refreshTimer.start(); } void MediaModel::handleScanFinished(const QString &type) { if (type != m_mediaType) return; m_refreshTimer.stop(); refresh(); } void MediaModel::refresh() { createNewDbReader(); m_loading = true; m_loaded = false; QSqlQuery q = buildQuery(); DEBUG << m_mediaType << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } <commit_msg>Remove superfluous rows from the end of the old list<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "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 Nokia Corporation and its Subsidiary(-ies) 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." ****************************************************************************/ #include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #include <sqlite3.h> #define DEBUG if (0) qDebug() << this << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { m_refreshTimer.setInterval(10000); connect(&m_refreshTimer, SIGNAL(timeout()), this, SLOT(refresh())); MediaScanner *scanner = Backend::instance()->mediaScanner(); connect(scanner, SIGNAL(scanStarted(QString)), this, SLOT(handleScanStarted(QString))); connect(scanner, SIGNAL(scanFinished(QString)), this, SLOT(handleScanFinished(QString))); connect(scanner, SIGNAL(searchPathRemoved(QString, QString)), this, SLOT(handleScanFinished(QString))); m_readerThread = new QThread(this); m_readerThread->start(); } MediaModel::~MediaModel() { if (m_reader) { m_reader->stop(); m_reader->deleteLater(); m_readerThread->quit(); m_readerThread->wait(); } } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { if (type == m_mediaType) return; DEBUG << type; m_mediaType = type; emit mediaTypeChanged(); // Add the fields of the table as role names QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(DotDotRole, "dotdot"); hash.insert(IsLeafRole, "isLeaf"); hash.insert(ModelIndexRole,"modelIndex"); hash.insert(PreviewUrlRole, "previewUrl"); for (int i = 0; i < record.count(); i++) { hash.insert(FieldRolesBegin + i, record.fieldName(i).toUtf8()); m_fieldToRole.insert(record.fieldName(i), FieldRolesBegin + i); } setRoleNames(hash); reload(); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { if (str == m_structure) return; DEBUG << str; m_structure = str; m_layoutInfo.clear(); foreach(const QString &part, m_structure.split("|")) m_layoutInfo.append(part.split(",")); reload(); emit structureChanged(); } void MediaModel::enter(int index) { if (m_cursor.count() + 1 == m_layoutInfo.count() && !m_data.at(index)[DotDotRole].toBool() /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (m_data.at(index)[DotDotRole].toBool() && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); reload(); emit partChanged(); } void MediaModel::back(int count) { if (count == 0 || m_cursor.count() < 1) return; if (m_cursor.count() > count) { for (int i = 0; i < count; ++i) m_cursor.removeLast(); } else { m_cursor.clear(); } reload(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == ModelIndexRole) return qVariantFromValue(index); return m_data.value(index.row()).value(role); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_layoutInfo.isEmpty()) { DEBUG << "false " << parent.isValid() << m_mediaType.isEmpty() << m_layoutInfo.isEmpty(); return false; } DEBUG << (!m_loading && !m_loaded); return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; DEBUG << ""; m_loading = true; QSqlQuery q = buildQuery(); DEBUG << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::createNewDbReader() { DEBUG << ""; if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = new DbReader; m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); } void MediaModel::reload() { createNewDbReader(); beginResetModel(); m_loading = m_loaded = false; m_data.clear(); endResetModel(); } QHash<int, QVariant> MediaModel::dataFromRecord(const QSqlRecord &record) const { QHash<int, QVariant> data; for (int j = 0; j < record.count(); j++) { int role = m_fieldToRole.value(record.fieldName(j)); if (record.fieldName(j) == "uri") data.insert(role, QUrl::fromEncoded(record.value(j).toByteArray())); else data.insert(role, record.value(j)); } // Provide 'display' role as , separated values QStringList cols = m_layoutInfo.value(m_cursor.count()); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << record.value(cols[j]).toString(); } data.insert(Qt::DisplayRole, displayString.join(", ")); data.insert(DotDotRole, false); data.insert(IsLeafRole, m_cursor.count() + 1 == m_layoutInfo.count()); data.insert(PreviewUrlRole, QUrl::fromEncoded(record.value("thumbnail").toByteArray())); return data; } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (m_data.isEmpty()) { insertAll(records); } else { insertNew(records); } m_loading = false; m_loaded = true; } void MediaModel::insertAll(const QList<QSqlRecord> &records) { if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } for (int i = 0; i < records.count(); i++) { QHash<int, QVariant> data = dataFromRecord(records[i]); m_data.append(data); } if (!m_cursor.isEmpty()) { QHash<int, QVariant> data; data.insert(Qt::DisplayRole, tr("..")); data.insert(DotDotRole, true); data.insert(IsLeafRole, false); m_data.append(data); } endInsertRows(); } int MediaModel::compareData(int idx, const QSqlRecord &record) const { const QHash<int, QVariant> &curData = m_data[idx]; QStringList cols = m_layoutInfo.value(m_cursor.count()); foreach(const QString &col, cols) { const int role = m_fieldToRole.value(col); int cmp = QString::compare(curData.value(role).toString(), record.value(col).toString(), Qt::CaseInsensitive); // ## must use sqlite's compare if (cmp != 0) return cmp; } return 0; } void MediaModel::insertNew(const QList<QSqlRecord> &records) { int old = 0, shiny = 0; while (shiny < records.length()) { const QSqlRecord &record = records[shiny]; int cmp = old == m_data.count() ? 1 : compareData(old, record); if (cmp == 0) { ++old; ++shiny; } else if (cmp < 0) { beginRemoveRows(QModelIndex(), old, old); m_data.removeAt(old); endRemoveRows(); } else { beginInsertRows(QModelIndex(), old, old); m_data.insert(old, dataFromRecord(record)); endInsertRows(); ++old; ++shiny; } } if (old != m_data.count()) { beginRemoveRows(QModelIndex(), old, m_data.count()-1); m_data = m_data.mid(0, old); endRemoveRows(); } } QSqlQuery MediaModel::buildQuery() const { QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QStringList escapedCurParts; QStringList curParts = m_layoutInfo[m_cursor.count()]; for (int i = 0; i < curParts.count(); i++) escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName)); QString escapedCurPart = escapedCurParts.join(","); QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); QStringList placeHolders; const bool lastPart = m_cursor.count() == m_layoutInfo.count()-1; QString queryString; // SQLite allows us to select columns that are not present in the GROUP BY. We use this feature // to select thumbnails for non-leaf nodes queryString.append("SELECT *"); queryString.append(" FROM " + driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName)); if (!m_cursor.isEmpty()) { QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QStringList subParts = m_layoutInfo[i]; for (int j = 0; j < subParts.count(); j++) { where.append(subParts[j] + " = ?"); const int role = m_fieldToRole.value(subParts[j]); placeHolders << m_cursor[i].value(role).toString(); } } queryString.append(" WHERE " + where.join(" AND ")); } if (!lastPart) queryString.append(" GROUP BY " + escapedCurPart); queryString.append(" ORDER BY " + escapedCurPart + " COLLATE NOCASE"); query.prepare(queryString); foreach(const QString &placeHolder, placeHolders) query.addBindValue(placeHolder); return query; } void MediaModel::handleScanStarted(const QString &type) { if (type != m_mediaType) return; m_refreshTimer.start(); } void MediaModel::handleScanFinished(const QString &type) { if (type != m_mediaType) return; m_refreshTimer.stop(); refresh(); } void MediaModel::refresh() { createNewDbReader(); m_loading = true; m_loaded = false; QSqlQuery q = buildQuery(); DEBUG << m_mediaType << q.lastQuery(); QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } <|endoftext|>
<commit_before> #ifndef __BUFFER_CACHE_WRITEBACK_TCC__ #define __BUFFER_CACHE_WRITEBACK_TCC__ template <class config_t> writeback_tmpl_t<config_t>::writeback_tmpl_t( cache_t *cache, bool wait_for_flush, unsigned int flush_timer_ms, unsigned int flush_threshold) : flush_timer(NULL), wait_for_flush(wait_for_flush), flush_timer_ms(flush_timer_ms), flush_threshold(flush_threshold), cache(cache), num_txns(0), start_next_sync_immediately(false), shutdown_callback(NULL), in_shutdown_sync(false), transaction_backdoor(false), state(state_none), transaction(NULL) { } template <class config_t> writeback_tmpl_t<config_t>::~writeback_tmpl_t() { gdelete(flush_lock); } template <class config_t> void writeback_tmpl_t<config_t>::start() { flush_lock = gnew<rwi_lock_t>(&get_cpu_context()->event_queue->message_hub, get_cpu_context()->event_queue->queue_id); } template <class config_t> void writeback_tmpl_t<config_t>::shutdown(sync_callback_t *callback) { assert(shutdown_callback == NULL); shutdown_callback = callback; if (!num_txns) // If num_txns, commit() will do this sync(callback); } template <class config_t> void writeback_tmpl_t<config_t>::sync(sync_callback_t *callback) { if (callback) sync_callbacks.push_back(callback); // TODO: If state == state_locking, we could probably still join the current writeback rather // than waiting for the next one. if (state == state_none) { /* Start the writeback process immediately */ writeback(NULL); } else { /* There is a writeback currently in progress, but sync() has been called, so there is more data that needs to be flushed that didn't become part of the current sync. So we start another sync right after this one. */ start_next_sync_immediately = true; } } template <class config_t> bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) { assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write); // TODO(NNW): If there's ever any asynchrony between socket reads and // begin_transaction, we'll need a better check here. assert(shutdown_callback == NULL || transaction_backdoor); num_txns++; if (txn->get_access() == rwi_read) return true; bool locked = flush_lock->lock(rwi_read, txn); return locked; } template <class config_t> bool writeback_tmpl_t<config_t>::commit(transaction_t *txn) { num_txns --; if (txn->get_access() == rwi_write) { flush_lock -> unlock(); } if (num_txns == 0 && shutdown_callback != NULL && !in_shutdown_sync) { // All txns shut down, start final sync. // So we don't do this again when the final sync's transaction commits in_shutdown_sync = true; sync(shutdown_callback); } if (txn->get_access() == rwi_write) { /* At the end of every write transaction, check if the number of dirty blocks exceeds the threshold to force writeback to start. */ if (num_dirty_blocks() > flush_threshold) { sync(NULL); } /* Otherwise, start the flush timer so that the modified data doesn't sit in memory for too long without being written to disk. */ else if (!flush_timer && flush_timer_ms != NEVER_FLUSH) { flush_timer = get_cpu_context()->event_queue-> fire_timer_once(flush_timer_ms, flush_timer_callback, this); } } if (txn->get_access() == rwi_write && wait_for_flush) { /* Push the callback in manually rather than calling sync(); we will patiently wait for the next sync to come naturally. */ sync_callbacks.push_back(txn); return false; } else { return true; } } template <class config_t> void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) { if (written) writeback(buf); } template <class config_t> unsigned int writeback_tmpl_t<config_t>::num_dirty_blocks() { return dirty_bufs.size(); } #ifndef NDEBUG template <class config_t> void writeback_tmpl_t<config_t>::deadlock_debug() { printf("\n----- Writeback -----\n"); const char *st_name; switch(state) { case state_none: st_name = "state_none"; break; case state_locking: st_name = "state_locking"; break; case state_locked: st_name = "state_locked"; break; case state_write_bufs: st_name = "state_write_bufs"; break; default: st_name = "<invalid state>"; break; } printf("state = %s\n", st_name); } #endif template <class config_t> void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) { // 'super' is actually 'this', but as a buf_t* instead of a local_buf_t* if(!dirty) { // Mark block as dirty if it hasn't been already dirty = true; writeback->dirty_bufs.push_back(super); } } template <class config_t> void writeback_tmpl_t<config_t>::flush_timer_callback(void *ctx) { writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx); self->flush_timer = NULL; self->sync(NULL); } template <class config_t> void writeback_tmpl_t<config_t>::on_lock_available() { assert(state == state_locking); if (state == state_locking) { state = state_locked; writeback(NULL); } } template <class config_t> void writeback_tmpl_t<config_t>::writeback(buf_t *buf) { //printf("Writeback being called, state %d\n", state); if (state == state_none) { assert(buf == NULL); /* Start a read transaction so we can request bufs. */ assert(transaction == NULL); if (shutdown_callback) // Backdoor around "no new transactions" assert. transaction_backdoor = true; transaction = cache->begin_transaction(rwi_read, NULL); transaction_backdoor = false; assert(transaction != NULL); // Read txns always start immediately. /* Request exclusive flush_lock, forcing all write txns to complete. */ state = state_locking; bool locked = flush_lock->lock(rwi_write, this); if (locked) { state = state_locked; } } if (state == state_locked) { assert(buf == NULL); assert(flush_bufs.empty()); assert(current_sync_callbacks.empty()); current_sync_callbacks.append_and_clear(&sync_callbacks); /* Request read locks on all of the blocks we need to flush. */ // TODO: optimize away dynamic allocation typename serializer_t::write *writes = (typename serializer_t::write*)calloc(dirty_bufs.size(), sizeof *writes); int i; typename intrusive_list_t<buf_t>::iterator it; for (it = dirty_bufs.begin(), i = 0; it != dirty_bufs.end(); it++, i++) { buf_t *_buf = &*it; // Acquire the blocks buf_t *buf = transaction->acquire(_buf->get_block_id(), rwi_read, NULL); assert(buf); // Acquire must succeed since we hold the flush_lock. assert(buf == _buf); // Acquire should return the same buf we stored earlier. // Fill the serializer structure writes[i].block_id = buf->get_block_id(); writes[i].buf = buf->ptr(); writes[i].callback = buf; #ifndef NDEBUG buf->active_callback_count ++; #endif } flush_bufs.append_and_clear(&dirty_bufs); flush_lock->unlock(); // Write transactions can now proceed again. /* Start writing all the dirty bufs down, as a transaction. */ // TODO(NNW): Now that the serializer/aio-system breaks writes up into // chunks, we may want to worry about submitting more heavily contended // bufs earlier in the process so more write FSMs can proceed sooner. if (flush_bufs.size()) cache->do_write(get_cpu_context()->event_queue, writes, flush_bufs.size()); free(writes); state = state_write_bufs; } if (state == state_write_bufs) { if (buf) { flush_bufs.remove(buf); buf->set_clean(); buf->release(); } if (flush_bufs.empty()) { /* We are done writing all of the buffers */ bool committed __attribute__((unused)) = transaction->commit(NULL); assert(committed); // Read-only transactions commit immediately. transaction = NULL; while (!current_sync_callbacks.empty()) { sync_callback_t *cb = current_sync_callbacks.head(); current_sync_callbacks.remove(cb); cb->on_sync(); } state = state_none; if (start_next_sync_immediately) { start_next_sync_immediately = false; writeback(NULL); } } } } #endif // __BUFFER_CACHE_WRITEBACK_TCC__ <commit_msg>Put back the cancellation of the flush timer and added a comment to explain why it is necessary.<commit_after> #ifndef __BUFFER_CACHE_WRITEBACK_TCC__ #define __BUFFER_CACHE_WRITEBACK_TCC__ template <class config_t> writeback_tmpl_t<config_t>::writeback_tmpl_t( cache_t *cache, bool wait_for_flush, unsigned int flush_timer_ms, unsigned int flush_threshold) : flush_timer(NULL), wait_for_flush(wait_for_flush), flush_timer_ms(flush_timer_ms), flush_threshold(flush_threshold), cache(cache), num_txns(0), start_next_sync_immediately(false), shutdown_callback(NULL), in_shutdown_sync(false), transaction_backdoor(false), state(state_none), transaction(NULL) { } template <class config_t> writeback_tmpl_t<config_t>::~writeback_tmpl_t() { gdelete(flush_lock); } template <class config_t> void writeback_tmpl_t<config_t>::start() { flush_lock = gnew<rwi_lock_t>(&get_cpu_context()->event_queue->message_hub, get_cpu_context()->event_queue->queue_id); } template <class config_t> void writeback_tmpl_t<config_t>::shutdown(sync_callback_t *callback) { assert(shutdown_callback == NULL); shutdown_callback = callback; if (!num_txns) // If num_txns, commit() will do this sync(callback); } template <class config_t> void writeback_tmpl_t<config_t>::sync(sync_callback_t *callback) { if (callback) sync_callbacks.push_back(callback); // TODO: If state == state_locking, we could probably still join the current writeback rather // than waiting for the next one. if (state == state_none) { /* Start the writeback process immediately */ writeback(NULL); } else { /* There is a writeback currently in progress, but sync() has been called, so there is more data that needs to be flushed that didn't become part of the current sync. So we start another sync right after this one. */ start_next_sync_immediately = true; } } template <class config_t> bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) { assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write); // TODO(NNW): If there's ever any asynchrony between socket reads and // begin_transaction, we'll need a better check here. assert(shutdown_callback == NULL || transaction_backdoor); num_txns++; if (txn->get_access() == rwi_read) return true; bool locked = flush_lock->lock(rwi_read, txn); return locked; } template <class config_t> bool writeback_tmpl_t<config_t>::commit(transaction_t *txn) { num_txns --; if (txn->get_access() == rwi_write) { flush_lock -> unlock(); } if (num_txns == 0 && shutdown_callback != NULL && !in_shutdown_sync) { // All txns shut down, start final sync. // So we don't do this again when the final sync's transaction commits in_shutdown_sync = true; sync(shutdown_callback); } if (txn->get_access() == rwi_write) { /* At the end of every write transaction, check if the number of dirty blocks exceeds the threshold to force writeback to start. */ if (num_dirty_blocks() > flush_threshold) { sync(NULL); } /* Otherwise, start the flush timer so that the modified data doesn't sit in memory for too long without being written to disk. */ else if (!flush_timer && flush_timer_ms != NEVER_FLUSH) { flush_timer = get_cpu_context()->event_queue-> fire_timer_once(flush_timer_ms, flush_timer_callback, this); } } if (txn->get_access() == rwi_write && wait_for_flush) { /* Push the callback in manually rather than calling sync(); we will patiently wait for the next sync to come naturally. */ sync_callbacks.push_back(txn); return false; } else { return true; } } template <class config_t> void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) { if (written) writeback(buf); } template <class config_t> unsigned int writeback_tmpl_t<config_t>::num_dirty_blocks() { return dirty_bufs.size(); } #ifndef NDEBUG template <class config_t> void writeback_tmpl_t<config_t>::deadlock_debug() { printf("\n----- Writeback -----\n"); const char *st_name; switch(state) { case state_none: st_name = "state_none"; break; case state_locking: st_name = "state_locking"; break; case state_locked: st_name = "state_locked"; break; case state_write_bufs: st_name = "state_write_bufs"; break; default: st_name = "<invalid state>"; break; } printf("state = %s\n", st_name); } #endif template <class config_t> void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) { // 'super' is actually 'this', but as a buf_t* instead of a local_buf_t* if(!dirty) { // Mark block as dirty if it hasn't been already dirty = true; writeback->dirty_bufs.push_back(super); } } template <class config_t> void writeback_tmpl_t<config_t>::flush_timer_callback(void *ctx) { writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx); self->flush_timer = NULL; self->sync(NULL); } template <class config_t> void writeback_tmpl_t<config_t>::on_lock_available() { assert(state == state_locking); if (state == state_locking) { state = state_locked; writeback(NULL); } } template <class config_t> void writeback_tmpl_t<config_t>::writeback(buf_t *buf) { //printf("Writeback being called, state %d\n", state); if (state == state_none) { assert(buf == NULL); // Cancel the flush timer because we're doing writeback now, so we don't need it to remind // us later. This happens only if the flush timer is running, and writeback starts for some // other reason before the flush timer goes off; if this writeback had been started by the // flush timer, then flush_timer would be NULL here, because flush_timer_callback sets it // to NULL. if (flush_timer) { get_cpu_context()->event_queue->cancel_timer(flush_timer); flush_timer = NULL; } /* Start a read transaction so we can request bufs. */ assert(transaction == NULL); if (shutdown_callback) // Backdoor around "no new transactions" assert. transaction_backdoor = true; transaction = cache->begin_transaction(rwi_read, NULL); transaction_backdoor = false; assert(transaction != NULL); // Read txns always start immediately. /* Request exclusive flush_lock, forcing all write txns to complete. */ state = state_locking; bool locked = flush_lock->lock(rwi_write, this); if (locked) { state = state_locked; } } if (state == state_locked) { assert(buf == NULL); assert(flush_bufs.empty()); assert(current_sync_callbacks.empty()); current_sync_callbacks.append_and_clear(&sync_callbacks); /* Request read locks on all of the blocks we need to flush. */ // TODO: optimize away dynamic allocation typename serializer_t::write *writes = (typename serializer_t::write*)calloc(dirty_bufs.size(), sizeof *writes); int i; typename intrusive_list_t<buf_t>::iterator it; for (it = dirty_bufs.begin(), i = 0; it != dirty_bufs.end(); it++, i++) { buf_t *_buf = &*it; // Acquire the blocks buf_t *buf = transaction->acquire(_buf->get_block_id(), rwi_read, NULL); assert(buf); // Acquire must succeed since we hold the flush_lock. assert(buf == _buf); // Acquire should return the same buf we stored earlier. // Fill the serializer structure writes[i].block_id = buf->get_block_id(); writes[i].buf = buf->ptr(); writes[i].callback = buf; #ifndef NDEBUG buf->active_callback_count ++; #endif } flush_bufs.append_and_clear(&dirty_bufs); flush_lock->unlock(); // Write transactions can now proceed again. /* Start writing all the dirty bufs down, as a transaction. */ // TODO(NNW): Now that the serializer/aio-system breaks writes up into // chunks, we may want to worry about submitting more heavily contended // bufs earlier in the process so more write FSMs can proceed sooner. if (flush_bufs.size()) cache->do_write(get_cpu_context()->event_queue, writes, flush_bufs.size()); free(writes); state = state_write_bufs; } if (state == state_write_bufs) { if (buf) { flush_bufs.remove(buf); buf->set_clean(); buf->release(); } if (flush_bufs.empty()) { /* We are done writing all of the buffers */ bool committed __attribute__((unused)) = transaction->commit(NULL); assert(committed); // Read-only transactions commit immediately. transaction = NULL; while (!current_sync_callbacks.empty()) { sync_callback_t *cb = current_sync_callbacks.head(); current_sync_callbacks.remove(cb); cb->on_sync(); } state = state_none; if (start_next_sync_immediately) { start_next_sync_immediately = false; writeback(NULL); } } } } #endif // __BUFFER_CACHE_WRITEBACK_TCC__ <|endoftext|>
<commit_before>// Implementation for Touch_Buttons // // attention, to be fast, this needs the -O3 compiler option to be set! // // author: ulno // created: 2016-03-01 #include <Arduino.h> #include "Touch_Buttons.h" #define ulno_do_2x(exp) {exp;exp;} #define ulno_do_5x(exp) {exp;exp;exp;exp;exp;} #define ulno_do_10x(exp) {ulno_do_2x(ulno_do_5x(exp))} void Touch_Buttons::init(int threshold, int debounce, int discharge_delay_ms, bool internal_pullup, bool chargedelay ) { // threshold = 108; // 1/2mOhm resistor + graphite + scotch tape // threshold = 400; // > 50000 with 1MOhm //threshold = 4;// internal resistor (set to 20 to see speed) this->default_threshold = threshold; this->debounce_value = debounce*2; // reasonable is 5 this->use_internal_pullup = internal_pullup; // we use it in the simplest version to not have external resistors this->measure_chargedelay = chargedelay; // true should be used when using internal pullup _size = 0; initial_wait = discharge_delay_ms; for(int i=0; i < MAX_BUTTONS * 2; i++) { button_array[i] = 0; } for(int i=0; i < MAX_BUTTONS; i++) { debouncer[i] = 0; } debug(0,0); // no debugging by default } void Touch_Buttons::debug( int level, int count ) { // debug level: 0=off, 1=info, 2=all; count: <0: never, n: every n calls this->debug_level = level; this->debug_count = count; debug_frame = 0; } Touch_Buttons::Touch_Buttons(int threshold, int debounce, int discharge_delay_ms, bool internal_pullup, bool chargedelay ) { init( threshold, debounce, discharge_delay_ms, internal_pullup, chargedelay); } Touch_Buttons::Touch_Buttons() { init( 9, 5, 1, true, true); } static void pull_down( int gpio ) { pinMode(gpio, OUTPUT); digitalWrite(gpio, LOW); } void Touch_Buttons::pull_down_all() { // pull all buttons down for(int b=0; b<_size; b++) { int gpio = button_gpio[b]; pull_down(gpio); } } /*void Touch_Buttons::set_input_all() { // pull all buttons down for(int b=0; b<_size; b++) { int gpio = button_gpio[b]; if( use_internal_pullup ) pinMode(gpio, INPUT_PULLUP); else pinMode(gpio, INPUT); } } too slow */ void Touch_Buttons::add_button(int id, int gpio_pin, int _threshold) { if(_size < MAX_BUTTONS ) { set_button_id(_size, id); set_button_state(_size, -1); button_gpio[_size] = gpio_pin; threshold[_size] = _threshold; _size ++; // needs to be pulled down by default to be discharged pull_down(gpio_pin); } else { Serial.println("Maximum numbers of buttons defined, not adding new one.\n"); } } void Touch_Buttons::add_button(int id, int gpio_pin) { add_button(id,gpio_pin,default_threshold); } bool Touch_Buttons::check() { const int MAX_DIRECT_READS = 100; // this is a fixed constant reflecting the up to 100 single reads in this function uint32_t regcache[MAX_DIRECT_READS]; int_fast16_t timer = 0; bool one_pressed = false; /* //PIN_PULLUP_DIS(PERIPHS_IO_MUX_GPIO5_U); //GPIO_OUTPUT_SET(gpio, 0); // pull down pinMode(gpio, OUTPUT); digitalWrite(gpio, LOW); //os_delay_us(500); //os_delay_us(100); delay(1);*/ pull_down_all(); delay(initial_wait); for(int b=_size-1; b>=0; b--) { int gpio = button_gpio[b]; // (GPIO_REG_READ(GPIO_IN_ADDRESS) = READ_PERI_REG(PERIPHS_GPIO_BASEADDR + GPIO_IN_ADDRESS) //volatile uint32_t *gpio_ports = (volatile uint32_t *)(PERIPHS_GPIO_BASEADDR + GPIO_IN_ADDRESS); slower than fixed address uint32_t bitmask = 1 << gpio; uint32_t *regcache_writer = regcache; //GPIO_DIS_OUTPUT(gpio); //PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO5_U); int pullup_mode = use_internal_pullup?INPUT_PULLUP:INPUT; int_fast16_t threshold_left = threshold[b]; int_fast16_t threshold_10steps = threshold_left / 10; if(threshold_10steps>9) threshold_10steps = 9; threshold_10steps ++; uint16_t direct_reads = threshold_10steps * 10; threshold_left -= direct_reads; // the following is extremely time critical as the recharging is pretty fast // read directly to be maximum fast switch(threshold_10steps) { case 1: pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 2: pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 3: pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 4: pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 5: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); break; case 6: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 7: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 8: pinMode(gpio, pullup_mode); ulno_do_2x(ulno_do_2x(ulno_do_2x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)))); break; case 9: pinMode(gpio, pullup_mode); ulno_do_2x(ulno_do_2x(ulno_do_2x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 10: pinMode(gpio, pullup_mode); ulno_do_10x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); break; } // read the potential rest a little slower //while (!(gpio_input_get()&(1<<gpio)) && (riseTime < threshold)) { // slow? //while (!(gpio_input_get()&32) && (riseTime < threshold)) { // slow? //while (!(*gpio_ports&32) && (timer > 0)) { // slower than fixed address while ((threshold_left > 0) && !(GPIO_REG_READ(GPIO_IN_ADDRESS)&bitmask)) { --threshold_left; } pull_down(gpio); // needs to be pulled down as early as possible to not acumulate too much charge threshold_left = threshold[b] - (threshold_10steps*10) - threshold_left; // adjust by the fast read direct accesses int timer2 = 0; for(int i=0; i<direct_reads; i++) { if(regcache[i]&bitmask) { break; } timer2++; } if( timer2 < direct_reads) timer = timer2; else timer += direct_reads; button_time[b] = timer; // save time for this button if (timer < threshold[b]) { if(measure_chargedelay) { // in this case being under the time means, no human touched the wire -> it is untouched decrease_debouncer(b); } else { increase_debouncer(b); } } else { if(measure_chargedelay) { // in this case being under the time means, a human touched the wire -> it is touched increase_debouncer(b); } else { decrease_debouncer(b); } } if(update_state(b)) one_pressed = true; // if only on epressed change to true /* debug */ if(debug_level>=1 && debug_frame >= debug_count) { Serial.print("I"); Serial.print(get_button_id(b)); Serial.print(" P"); Serial.print(gpio); Serial.print(" T"); Serial.print(timer); Serial.print(" TT"); Serial.print(timer2); Serial.print(" D"); Serial.print(debouncer[b]); Serial.print(" "); } } // end of loop through all buttons if(debug_level>=1) { if(debug_frame >= debug_count) { debug_frame = 0; Serial.println(); } debug_frame ++; } return one_pressed; } int Touch_Buttons::get_button(int id) { // find button id for(int b=_size-1; b>=0; b--) { if(get_button_id(b) == id) return get_button_state(b); } return -1; } <commit_msg>small bugfix with first timer<commit_after>// Implementation for Touch_Buttons // // attention, to be fast, this needs the -O3 compiler option to be set! // // author: ulno // created: 2016-03-01 #include <Arduino.h> #include "Touch_Buttons.h" #define ulno_do_2x(exp) {exp;exp;} #define ulno_do_5x(exp) {exp;exp;exp;exp;exp;} #define ulno_do_10x(exp) {ulno_do_2x(ulno_do_5x(exp))} void Touch_Buttons::init(int threshold, int debounce, int discharge_delay_ms, bool internal_pullup, bool chargedelay ) { // threshold = 108; // 1/2mOhm resistor + graphite + scotch tape // threshold = 400; // > 50000 with 1MOhm //threshold = 4;// internal resistor (set to 20 to see speed) this->default_threshold = threshold; this->debounce_value = debounce*2; // reasonable is 5 this->use_internal_pullup = internal_pullup; // we use it in the simplest version to not have external resistors this->measure_chargedelay = chargedelay; // true should be used when using internal pullup _size = 0; initial_wait = discharge_delay_ms; for(int i=0; i < MAX_BUTTONS * 2; i++) { button_array[i] = 0; } for(int i=0; i < MAX_BUTTONS; i++) { debouncer[i] = 0; } debug(0,0); // no debugging by default } void Touch_Buttons::debug( int level, int count ) { // debug level: 0=off, 1=info, 2=all; count: <0: never, n: every n calls this->debug_level = level; this->debug_count = count; debug_frame = 0; } Touch_Buttons::Touch_Buttons(int threshold, int debounce, int discharge_delay_ms, bool internal_pullup, bool chargedelay ) { init( threshold, debounce, discharge_delay_ms, internal_pullup, chargedelay); } Touch_Buttons::Touch_Buttons() { init( 9, 5, 1, true, true); } static void pull_down( int gpio ) { pinMode(gpio, OUTPUT); digitalWrite(gpio, LOW); } void Touch_Buttons::pull_down_all() { // pull all buttons down for(int b=0; b<_size; b++) { int gpio = button_gpio[b]; pull_down(gpio); } } /*void Touch_Buttons::set_input_all() { // pull all buttons down for(int b=0; b<_size; b++) { int gpio = button_gpio[b]; if( use_internal_pullup ) pinMode(gpio, INPUT_PULLUP); else pinMode(gpio, INPUT); } } too slow */ void Touch_Buttons::add_button(int id, int gpio_pin, int _threshold) { if(_size < MAX_BUTTONS ) { set_button_id(_size, id); set_button_state(_size, -1); button_gpio[_size] = gpio_pin; threshold[_size] = _threshold; _size ++; // needs to be pulled down by default to be discharged pull_down(gpio_pin); } else { Serial.println("Maximum numbers of buttons defined, not adding new one.\n"); } } void Touch_Buttons::add_button(int id, int gpio_pin) { add_button(id,gpio_pin,default_threshold); } bool Touch_Buttons::check() { const int MAX_DIRECT_READS = 100; // this is a fixed constant reflecting the up to 100 single reads in this function uint32_t regcache[MAX_DIRECT_READS]; int_fast16_t threshold_left; bool one_pressed = false; /* //PIN_PULLUP_DIS(PERIPHS_IO_MUX_GPIO5_U); //GPIO_OUTPUT_SET(gpio, 0); // pull down pinMode(gpio, OUTPUT); digitalWrite(gpio, LOW); //os_delay_us(500); //os_delay_us(100); delay(1);*/ pull_down_all(); delay(initial_wait); for(int b=_size-1; b>=0; b--) { int gpio = button_gpio[b]; // (GPIO_REG_READ(GPIO_IN_ADDRESS) = READ_PERI_REG(PERIPHS_GPIO_BASEADDR + GPIO_IN_ADDRESS) //volatile uint32_t *gpio_ports = (volatile uint32_t *)(PERIPHS_GPIO_BASEADDR + GPIO_IN_ADDRESS); slower than fixed address uint32_t bitmask = 1 << gpio; uint32_t *regcache_writer = regcache; //GPIO_DIS_OUTPUT(gpio); //PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO5_U); int pullup_mode = use_internal_pullup?INPUT_PULLUP:INPUT; threshold_left = threshold[b]; int_fast16_t threshold_10steps = (threshold_left - 1)/ 10; if(threshold_10steps>9) threshold_10steps = 9; else if(threshold_10steps<0) threshold_10steps = 0; threshold_10steps ++; // so 0-10: 1 | 11-20: 2 | 21-30: 3 | ... 91-100: 10 uint16_t direct_reads = threshold_10steps * 10; threshold_left -= direct_reads; // the following is extremely time critical as the recharging is pretty fast // read directly to be maximum fast switch(threshold_10steps) { case 1: // 0-10 -> 10 steps pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 2: // 11-20 -> 20 steps pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 3: // 21-30 -> 30 steps pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 4: pinMode(gpio, pullup_mode); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 5: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); break; case 6: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 7: pinMode(gpio, pullup_mode); ulno_do_5x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 8: pinMode(gpio, pullup_mode); ulno_do_2x(ulno_do_2x(ulno_do_2x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)))); break; case 9: pinMode(gpio, pullup_mode); ulno_do_2x(ulno_do_2x(ulno_do_2x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)))); ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS)); break; case 10: pinMode(gpio, pullup_mode); ulno_do_10x(ulno_do_10x(*((regcache_writer) ++) = GPIO_REG_READ(GPIO_IN_ADDRESS))); break; } // read the potential rest a little slower //while (!(gpio_input_get()&(1<<gpio)) && (riseTime < threshold)) { // slow? //while (!(gpio_input_get()&32) && (riseTime < threshold)) { // slow? //while (!(*gpio_ports&32) && (timer > 0)) { // slower than fixed address while ((threshold_left > 0) && !(GPIO_REG_READ(GPIO_IN_ADDRESS)&bitmask)) { --threshold_left; } pull_down(gpio); // needs to be pulled down as early as possible to not acumulate too much charge threshold_left = threshold[b] - (threshold_10steps*10) - threshold_left; // adjust by the fast read direct accesses int timer2 = 0; for(int i=0; i<direct_reads; i++) { if(regcache[i]&bitmask) { break; } timer2++; } if( timer2 < direct_reads) threshold_left = timer2; else threshold_left += direct_reads; button_time[b] = threshold_left; // save time for this button if (threshold_left < threshold[b]) { if(measure_chargedelay) { // in this case being under the time means, no human touched the wire -> it is untouched decrease_debouncer(b); } else { increase_debouncer(b); } } else { if(measure_chargedelay) { // in this case being under the time means, a human touched the wire -> it is touched increase_debouncer(b); } else { decrease_debouncer(b); } } if(update_state(b)) one_pressed = true; // if only on epressed change to true /* debug */ if(debug_level>=1 && debug_frame >= debug_count) { Serial.print("I"); Serial.print(get_button_id(b)); Serial.print(" P"); Serial.print(gpio); Serial.print(" T"); Serial.print(threshold_left); Serial.print(" TT"); Serial.print(timer2); Serial.print(" D"); Serial.print(debouncer[b]); Serial.print(" "); } } // end of loop through all buttons if(debug_level>=1) { if(debug_frame >= debug_count) { debug_frame = 0; Serial.println(); } debug_frame ++; } return one_pressed; } int Touch_Buttons::get_button(int id) { // find button id for(int b=_size-1; b>=0; b--) { if(get_button_id(b) == id) return get_button_state(b); } return -1; } <|endoftext|>
<commit_before>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * ******************************************************************************* * Copyright (c) 2022, Patrick Fedick <[email protected]> * 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 HOLDER 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 HOLDER AND 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 "prolog_ppl7.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STDARG_H #include <stdarg.h> #endif #include "ppl7.h" #include "ppl7-grafix.h" #include "ppl7-tk.h" namespace ppl7::tk { RadioButton::RadioButton() : ppl7::tk::Label() { ischecked=false; } RadioButton::RadioButton(int x, int y, int width, int height, const ppl7::String& text, bool checked) // @suppress("Class members should be properly initialized") : ppl7::tk::Label(x, y, width, height, text) { ischecked=checked; } RadioButton::~RadioButton() { } ppl7::String RadioButton::widgetType() const { return ppl7::String("RadioButton"); } bool RadioButton::checked() const { return ischecked; } void RadioButton::setChecked(bool checked) { bool laststate=ischecked; ischecked=checked; needsRedraw(); // uncheck all other RadioButtons in Parent-Widget if (checked == true && this->getParent()) { Widget* parent=this->getParent(); std::list<Widget*>::iterator it; for (it=parent->childsBegin(); it != parent->childsEnd();++it) { if (typeid(*it) == typeid(RadioButton) && *it != this) { ((RadioButton*)(*it))->setChecked(false); } } } ppl7::tk::Event ev(ppl7::tk::Event::Toggled); ev.setWidget(this); if (checked != laststate) { toggledEvent(&ev, checked); } } void RadioButton::paint(ppl7::grafix::Drawable& draw) { const ppl7::tk::WidgetStyle& style=ppl7::tk::GetWidgetStyle(); ppl7::grafix::Drawable d=draw.getDrawable(16, 0, draw.width() - 16, draw.height()); Label::paint(d); int y1=draw.height() / 2; draw.circle(9, y1, 7, style.frameBorderColorLight); draw.circle(9, y1, 6, style.frameBorderColorLight); if (ischecked) draw.floodFill(9, y1, this->color(), style.frameBorderColorLight); } void RadioButton::mouseDownEvent(ppl7::tk::MouseEvent* event) { setChecked(true); } } //EOF namespace <commit_msg>fixed radio button<commit_after>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * ******************************************************************************* * Copyright (c) 2022, Patrick Fedick <[email protected]> * 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 HOLDER 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 HOLDER AND 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 "prolog_ppl7.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STDARG_H #include <stdarg.h> #endif #include "ppl7.h" #include "ppl7-grafix.h" #include "ppl7-tk.h" namespace ppl7::tk { RadioButton::RadioButton() : ppl7::tk::Label() { ischecked=false; } RadioButton::RadioButton(int x, int y, int width, int height, const ppl7::String& text, bool checked) // @suppress("Class members should be properly initialized") : ppl7::tk::Label(x, y, width, height, text) { ischecked=checked; } RadioButton::~RadioButton() { } ppl7::String RadioButton::widgetType() const { return ppl7::String("RadioButton"); } bool RadioButton::checked() const { return ischecked; } void RadioButton::setChecked(bool checked) { bool laststate=ischecked; ischecked=checked; needsRedraw(); // uncheck all other RadioButtons in Parent-Widget if (checked == true && this->getParent()) { Widget* parent=this->getParent(); std::list<Widget*>::iterator it; for (it=parent->childsBegin(); it != parent->childsEnd();++it) { if (typeid(**it) == typeid(RadioButton) && *it != this) { ((RadioButton*)(*it))->setChecked(false); } } } ppl7::tk::Event ev(ppl7::tk::Event::Toggled); ev.setWidget(this); if (checked != laststate) { toggledEvent(&ev, checked); } } void RadioButton::paint(ppl7::grafix::Drawable& draw) { const ppl7::tk::WidgetStyle& style=ppl7::tk::GetWidgetStyle(); ppl7::grafix::Drawable d=draw.getDrawable(16, 0, draw.width() - 16, draw.height()); Label::paint(d); int y1=draw.height() / 2; draw.circle(9, y1, 7, style.frameBorderColorLight); draw.circle(9, y1, 6, style.frameBorderColorLight); if (ischecked) draw.floodFill(9, y1, this->color(), style.frameBorderColorLight); } void RadioButton::mouseDownEvent(ppl7::tk::MouseEvent* event) { setChecked(true); } } //EOF namespace <|endoftext|>
<commit_before>#include "../core_include/api.h" #include "../core_include/rect.h" #include "../core_include/resource.h" #include "../core_include/theme.h" static const FONT_INFO* s_font_map[FONT_MAX]; static const BITMAP_INFO* s_bmp_map[BITMAP_MAX]; static unsigned int s_color_map[COLOR_MAX]; int c_theme::add_font(FONT_TYPE index, const FONT_INFO* font) { if (index >= FONT_MAX) { ASSERT(false); return -1; } s_font_map[index] = font; return 0; } const FONT_INFO* c_theme::get_font(FONT_TYPE index) { if (index >= FONT_MAX) { ASSERT(false); return 0; } return s_font_map[index]; } int c_theme::add_bitmap(BITMAP_TYPE index, const BITMAP_INFO* bmp) { if (index >= BITMAP_MAX) { ASSERT(false); return -1; } s_bmp_map[index] = bmp; return 0; } const BITMAP_INFO* c_theme::get_bmp(BITMAP_TYPE index) { if (index >= BITMAP_MAX) { ASSERT(false); return 0; } return s_bmp_map[index]; } int c_theme::add_color(COLOR_TYPE index, const unsigned int color) { if (index >= COLOR_MAX) { ASSERT(false); return -1; } s_color_map[index] = color; return 0; } const unsigned int c_theme::get_color(COLOR_TYPE index) { if (index >= COLOR_MAX) { ASSERT(false); return 0; } return s_color_map[index]; }<commit_msg>add end line for theme.cpp<commit_after>#include "../core_include/api.h" #include "../core_include/rect.h" #include "../core_include/resource.h" #include "../core_include/theme.h" static const FONT_INFO* s_font_map[FONT_MAX]; static const BITMAP_INFO* s_bmp_map[BITMAP_MAX]; static unsigned int s_color_map[COLOR_MAX]; int c_theme::add_font(FONT_TYPE index, const FONT_INFO* font) { if (index >= FONT_MAX) { ASSERT(false); return -1; } s_font_map[index] = font; return 0; } const FONT_INFO* c_theme::get_font(FONT_TYPE index) { if (index >= FONT_MAX) { ASSERT(false); return 0; } return s_font_map[index]; } int c_theme::add_bitmap(BITMAP_TYPE index, const BITMAP_INFO* bmp) { if (index >= BITMAP_MAX) { ASSERT(false); return -1; } s_bmp_map[index] = bmp; return 0; } const BITMAP_INFO* c_theme::get_bmp(BITMAP_TYPE index) { if (index >= BITMAP_MAX) { ASSERT(false); return 0; } return s_bmp_map[index]; } int c_theme::add_color(COLOR_TYPE index, const unsigned int color) { if (index >= COLOR_MAX) { ASSERT(false); return -1; } s_color_map[index] = color; return 0; } const unsigned int c_theme::get_color(COLOR_TYPE index) { if (index >= COLOR_MAX) { ASSERT(false); return 0; } return s_color_map[index]; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; string S, T; int main () { cin >> S >> T; int N = S.size(); int M = T.size(); vector<string> V; for (auto i = 0; i < N - M; ++i) { string X = S; for (auto j = 0; j < M; ++j) { X[i + j] = T[j]; } for (auto i = 0; i < N; ++i) { if (X[i] == '?') X[i] = 'a'; } // cerr << X << endl; V.push_back(X); } sort(V.begin(), V.end()); for (auto X : V) { bool ok = true; for (auto i = 0; i < N; ++i) { if (S[i] != '?' && S[i] != X[i]) ok = false; } if (ok) { cout << X << endl; return 0; } } cout << "UNRESTORABLE" << endl; } <commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; string S, T; int main () { cin >> S >> T; int N = S.size(); int M = T.size(); vector<string> V; for (auto i = 0; i < N - M; ++i) { string X = S; for (auto j = 0; j < M; ++j) { X[i + j] = T[j]; } for (auto i = 0; i < N; ++i) { if (X[i] == '?') X[i] = 'a'; } cerr << X << endl; V.push_back(X); } sort(V.begin(), V.end()); for (auto X : V) { bool ok = true; for (auto i = 0; i < N; ++i) { if (S[i] != '?' && S[i] != X[i]) ok = false; } if (ok) { cout << X << endl; return 0; } } cout << "UNRESTORABLE" << endl; } <|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 "chrome/browser/dom_ui/clear_browser_data_handler.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" ClearBrowserDataHandler::ClearBrowserDataHandler() { } ClearBrowserDataHandler::~ClearBrowserDataHandler() { } void ClearBrowserDataHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString(L"clearBrowsingDataTitle", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_TITLE)); localized_strings->SetString(L"clearBrowsingDataLabel", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_LABEL)); localized_strings->SetString(L"clearBrowsingDataTimeLabel", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_TIME_LABEL)); localized_strings->SetString(L"deleteBrowsingHistoryCheckbox", l10n_util::GetString(IDS_DEL_BROWSING_HISTORY_CHKBOX)); localized_strings->SetString(L"deleteDownloadHistoryCheckbox", l10n_util::GetString(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX)); localized_strings->SetString(L"deleteCacheCheckbox", l10n_util::GetString(IDS_DEL_CACHE_CHKBOX)); localized_strings->SetString(L"deleteCookiesCheckbox", l10n_util::GetString(IDS_DEL_COOKIES_CHKBOX)); localized_strings->SetString(L"deletePasswordsCheckbox", l10n_util::GetString(IDS_DEL_PASSWORDS_CHKBOX)); localized_strings->SetString(L"deleteFormDataCheckbox", l10n_util::GetString(IDS_DEL_FORM_DATA_CHKBOX)); localized_strings->SetString(L"clearBrowsingDataCommit", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_COMMIT)); localized_strings->SetString(L"flashStorageSettings", l10n_util::GetString(IDS_FLASH_STORAGE_SETTINGS)); localized_strings->SetString(L"flash_storage_url", l10n_util::GetString(IDS_FLASH_STORAGE_URL)); localized_strings->SetString(L"clearDataDeleting", l10n_util::GetString(IDS_CLEAR_DATA_DELETING)); ListValue* time_list = new ListValue; for (int i = 0; i < 5; i++) { std::wstring label_string; switch (i) { case 0: label_string = l10n_util::GetString(IDS_CLEAR_DATA_HOUR); break; case 1: label_string = l10n_util::GetString(IDS_CLEAR_DATA_DAY); break; case 2: label_string = l10n_util::GetString(IDS_CLEAR_DATA_WEEK); break; case 3: label_string = l10n_util::GetString(IDS_CLEAR_DATA_4WEEKS); break; case 4: label_string = l10n_util::GetString(IDS_CLEAR_DATA_EVERYTHING); break; } ListValue* option = new ListValue(); option->Append(Value::CreateIntegerValue(i)); option->Append(Value::CreateStringValue(label_string)); time_list->Append(option); } localized_strings->Set(L"clearBrowsingDataTimeList", time_list); } void ClearBrowserDataHandler::RegisterMessages() { // Setup handlers specific to this panel. DCHECK(dom_ui_); dom_ui_->RegisterMessageCallback("performClearBrowserData", NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData)); } void ClearBrowserDataHandler::HandleClearBrowserData(const Value* value) { Profile *profile = dom_ui_->GetProfile(); PrefService *prefs = profile->GetPrefs(); int remove_mask = 0; if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory)) remove_mask |= BrowsingDataRemover::REMOVE_HISTORY; if (prefs->GetBoolean(prefs::kDeleteDownloadHistory)) remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (prefs->GetBoolean(prefs::kDeleteCache)) remove_mask |= BrowsingDataRemover::REMOVE_CACHE; if (prefs->GetBoolean(prefs::kDeleteCookies)) remove_mask |= BrowsingDataRemover::REMOVE_COOKIES; if (prefs->GetBoolean(prefs::kDeletePasswords)) remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS; if (prefs->GetBoolean(prefs::kDeleteFormData)) remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA; int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod); FundamentalValue state(true); dom_ui_->CallJavascriptFunction(L"clearBrowserDataSetClearingState", state); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->AddObserver(this); remover_->Remove(remove_mask); } void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() { // No need to remove ourselves as an observer as BrowsingDataRemover deletes // itself after we return. remover_ = NULL; DCHECK(dom_ui_); dom_ui_->CallJavascriptFunction(L"clearBrowserDataDismiss"); } <commit_msg>Remove observer from BrowsingDataRemover on destruct.<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 "chrome/browser/dom_ui/clear_browser_data_handler.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" ClearBrowserDataHandler::ClearBrowserDataHandler() : remover_(NULL) { } ClearBrowserDataHandler::~ClearBrowserDataHandler() { if (remover_) { remover_->RemoveObserver(this); } } void ClearBrowserDataHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString(L"clearBrowsingDataTitle", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_TITLE)); localized_strings->SetString(L"clearBrowsingDataLabel", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_LABEL)); localized_strings->SetString(L"clearBrowsingDataTimeLabel", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_TIME_LABEL)); localized_strings->SetString(L"deleteBrowsingHistoryCheckbox", l10n_util::GetString(IDS_DEL_BROWSING_HISTORY_CHKBOX)); localized_strings->SetString(L"deleteDownloadHistoryCheckbox", l10n_util::GetString(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX)); localized_strings->SetString(L"deleteCacheCheckbox", l10n_util::GetString(IDS_DEL_CACHE_CHKBOX)); localized_strings->SetString(L"deleteCookiesCheckbox", l10n_util::GetString(IDS_DEL_COOKIES_CHKBOX)); localized_strings->SetString(L"deletePasswordsCheckbox", l10n_util::GetString(IDS_DEL_PASSWORDS_CHKBOX)); localized_strings->SetString(L"deleteFormDataCheckbox", l10n_util::GetString(IDS_DEL_FORM_DATA_CHKBOX)); localized_strings->SetString(L"clearBrowsingDataCommit", l10n_util::GetString(IDS_CLEAR_BROWSING_DATA_COMMIT)); localized_strings->SetString(L"flashStorageSettings", l10n_util::GetString(IDS_FLASH_STORAGE_SETTINGS)); localized_strings->SetString(L"flash_storage_url", l10n_util::GetString(IDS_FLASH_STORAGE_URL)); localized_strings->SetString(L"clearDataDeleting", l10n_util::GetString(IDS_CLEAR_DATA_DELETING)); ListValue* time_list = new ListValue; for (int i = 0; i < 5; i++) { std::wstring label_string; switch (i) { case 0: label_string = l10n_util::GetString(IDS_CLEAR_DATA_HOUR); break; case 1: label_string = l10n_util::GetString(IDS_CLEAR_DATA_DAY); break; case 2: label_string = l10n_util::GetString(IDS_CLEAR_DATA_WEEK); break; case 3: label_string = l10n_util::GetString(IDS_CLEAR_DATA_4WEEKS); break; case 4: label_string = l10n_util::GetString(IDS_CLEAR_DATA_EVERYTHING); break; } ListValue* option = new ListValue(); option->Append(Value::CreateIntegerValue(i)); option->Append(Value::CreateStringValue(label_string)); time_list->Append(option); } localized_strings->Set(L"clearBrowsingDataTimeList", time_list); } void ClearBrowserDataHandler::RegisterMessages() { // Setup handlers specific to this panel. DCHECK(dom_ui_); dom_ui_->RegisterMessageCallback("performClearBrowserData", NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData)); } void ClearBrowserDataHandler::HandleClearBrowserData(const Value* value) { Profile *profile = dom_ui_->GetProfile(); PrefService *prefs = profile->GetPrefs(); int remove_mask = 0; if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory)) remove_mask |= BrowsingDataRemover::REMOVE_HISTORY; if (prefs->GetBoolean(prefs::kDeleteDownloadHistory)) remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (prefs->GetBoolean(prefs::kDeleteCache)) remove_mask |= BrowsingDataRemover::REMOVE_CACHE; if (prefs->GetBoolean(prefs::kDeleteCookies)) remove_mask |= BrowsingDataRemover::REMOVE_COOKIES; if (prefs->GetBoolean(prefs::kDeletePasswords)) remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS; if (prefs->GetBoolean(prefs::kDeleteFormData)) remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA; int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod); FundamentalValue state(true); dom_ui_->CallJavascriptFunction(L"clearBrowserDataSetClearingState", state); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->AddObserver(this); remover_->Remove(remove_mask); } void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() { // No need to remove ourselves as an observer as BrowsingDataRemover deletes // itself after we return. remover_ = NULL; DCHECK(dom_ui_); dom_ui_->CallJavascriptFunction(L"clearBrowserDataDismiss"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Matias Fontanini * 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. * * 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. * */ #ifdef _WIN32 #define NOMINMAX #endif // _WIN32 #include <iostream> #include <mutex> #include <chrono> #include <map> #include <thread> #include <algorithm> #include <tins/tins.h> using namespace Tins; // Holds the DNS response time statistics. The response time is // represented using the Duration template parameter. template<typename Duration> class statistics { public: using duration_type = Duration; using locker_type = std::lock_guard<std::mutex>; struct information { duration_type average, worst; size_t count; }; statistics() : m_duration(), m_worst(duration_type::min()), m_count() { } void add_response_time(const duration_type& duration) { locker_type _(m_lock); m_duration += duration; m_count++; m_worst = std::max(m_worst, duration); } information get_information() const { locker_type _(m_lock); if(m_count == 0) return { }; else return { m_duration / m_count, m_worst, m_count }; }; private: duration_type m_duration, m_worst; size_t m_count; mutable std::mutex m_lock; }; // Sniffs and tracks DNS queries. When a matching DNS response is found, // the response time is added to a statistics object. // // This class performs *no cleanup* on data associated with queries that // weren't answered. class dns_monitor { public: // The response times are measured in milliseconds using duration_type = std::chrono::milliseconds; // The statistics type used. using statistics_type = statistics<duration_type>; void run(BaseSniffer& sniffer); const statistics_type& stats() const { return m_stats; } private: using packet_info = std::tuple<IPv4Address, IPv4Address, uint16_t>; using clock_type = std::chrono::system_clock; using time_point_type = clock_type::time_point; bool callback(const PDU& pdu); static packet_info make_packet_info(const PDU& pdu, const DNS& dns); statistics_type m_stats; std::map<packet_info, time_point_type> m_packet_info; }; void dns_monitor::run(BaseSniffer& sniffer) { sniffer.sniff_loop( std::bind( &dns_monitor::callback, this, std::placeholders::_1 ) ); } bool dns_monitor::callback(const PDU& pdu) { auto now = clock_type::now(); auto dns = pdu.rfind_pdu<RawPDU>().to<DNS>(); auto info = make_packet_info(pdu, dns); // If it's a query, add the sniff time to our map. if(dns.type() == DNS::QUERY) { m_packet_info.insert( std::make_pair(info, now) ); } else { // It's a response, we need to find the query in our map. auto iter = m_packet_info.find(info); if(iter != m_packet_info.end()) { // We found the query, let's add the response time to the // statistics object. m_stats.add_response_time( std::chrono::duration_cast<duration_type>(now - iter->second) ); // Forget about the query. m_packet_info.erase(iter); } } return true; } // It is required that we can identify packets sent and received that // hold the same DNS id as belonging to the same query. // // This function retrieves a tuple (addr, addr, id) that will achieve it. auto dns_monitor::make_packet_info(const PDU& pdu, const DNS& dns) -> packet_info { const auto& ip = pdu.rfind_pdu<IP>(); return std::make_tuple( // smallest address first std::min(ip.src_addr(), ip.dst_addr()), // largest address second std::max(ip.src_addr(), ip.dst_addr()), dns.id() ); } int main(int argc, char *argv[]) { std::string iface; if (argc == 2) { // Use the provided interface iface = argv[1]; } else { // Use the default interface iface = NetworkInterface::default_interface().name(); } try { SnifferConfiguration config; config.set_promisc_mode(true); config.set_filter("udp and port 53"); Sniffer sniffer(iface, config); dns_monitor monitor; std::thread thread( [&]() { monitor.run(sniffer); } ); while(true) { auto info = monitor.stats().get_information(); std::cout << "\rAverage " << info.average.count() << "ms. Worst: " << info.worst.count() << "ms. Count: " << info.count; std::cout.flush(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } catch(std::exception& ex) { std::cout << "[-] Error: " << ex.what() << std::endl; } } <commit_msg>Add padding at the end of the line on dns_stats<commit_after>/* * Copyright (c) 2014, Matias Fontanini * 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. * * 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. * */ #ifdef _WIN32 #define NOMINMAX #endif // _WIN32 #include <iostream> #include <mutex> #include <chrono> #include <map> #include <thread> #include <algorithm> #include <tins/tins.h> using namespace Tins; // Holds the DNS response time statistics. The response time is // represented using the Duration template parameter. template<typename Duration> class statistics { public: using duration_type = Duration; using locker_type = std::lock_guard<std::mutex>; struct information { duration_type average, worst; size_t count; }; statistics() : m_duration(), m_worst(duration_type::min()), m_count() { } void add_response_time(const duration_type& duration) { locker_type _(m_lock); m_duration += duration; m_count++; m_worst = std::max(m_worst, duration); } information get_information() const { locker_type _(m_lock); if(m_count == 0) return { }; else return { m_duration / m_count, m_worst, m_count }; }; private: duration_type m_duration, m_worst; size_t m_count; mutable std::mutex m_lock; }; // Sniffs and tracks DNS queries. When a matching DNS response is found, // the response time is added to a statistics object. // // This class performs *no cleanup* on data associated with queries that // weren't answered. class dns_monitor { public: // The response times are measured in milliseconds using duration_type = std::chrono::milliseconds; // The statistics type used. using statistics_type = statistics<duration_type>; void run(BaseSniffer& sniffer); const statistics_type& stats() const { return m_stats; } private: using packet_info = std::tuple<IPv4Address, IPv4Address, uint16_t>; using clock_type = std::chrono::system_clock; using time_point_type = clock_type::time_point; bool callback(const PDU& pdu); static packet_info make_packet_info(const PDU& pdu, const DNS& dns); statistics_type m_stats; std::map<packet_info, time_point_type> m_packet_info; }; void dns_monitor::run(BaseSniffer& sniffer) { sniffer.sniff_loop( std::bind( &dns_monitor::callback, this, std::placeholders::_1 ) ); } bool dns_monitor::callback(const PDU& pdu) { auto now = clock_type::now(); auto dns = pdu.rfind_pdu<RawPDU>().to<DNS>(); auto info = make_packet_info(pdu, dns); // If it's a query, add the sniff time to our map. if(dns.type() == DNS::QUERY) { m_packet_info.insert( std::make_pair(info, now) ); } else { // It's a response, we need to find the query in our map. auto iter = m_packet_info.find(info); if(iter != m_packet_info.end()) { // We found the query, let's add the response time to the // statistics object. m_stats.add_response_time( std::chrono::duration_cast<duration_type>(now - iter->second) ); // Forget about the query. m_packet_info.erase(iter); } } return true; } // It is required that we can identify packets sent and received that // hold the same DNS id as belonging to the same query. // // This function retrieves a tuple (addr, addr, id) that will achieve it. auto dns_monitor::make_packet_info(const PDU& pdu, const DNS& dns) -> packet_info { const auto& ip = pdu.rfind_pdu<IP>(); return std::make_tuple( // smallest address first std::min(ip.src_addr(), ip.dst_addr()), // largest address second std::max(ip.src_addr(), ip.dst_addr()), dns.id() ); } int main(int argc, char *argv[]) { std::string iface; if (argc == 2) { // Use the provided interface iface = argv[1]; } else { // Use the default interface iface = NetworkInterface::default_interface().name(); } try { SnifferConfiguration config; config.set_promisc_mode(true); config.set_filter("udp and port 53"); Sniffer sniffer(iface, config); dns_monitor monitor; std::thread thread( [&]() { monitor.run(sniffer); } ); while(true) { auto info = monitor.stats().get_information(); std::cout << "\rAverage " << info.average.count() << "ms. Worst: " << info.worst.count() << "ms. Count: " << info.count << " "; std::cout.flush(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } catch(std::exception& ex) { std::cout << "[-] Error: " << ex.what() << std::endl; } } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <algorithm> #include <list> #include <map> #include <set> #include <string> #include <vector> #include <process/collect.hpp> #include <process/defer.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <stout/error.hpp> #include <stout/foreach.hpp> #include <stout/hashmap.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/try.hpp> #include "linux/cgroups.hpp" #include "slave/flags.hpp" #include "slave/containerizer/containerizer.hpp" #include "slave/containerizer/mesos/isolator.hpp" #include "slave/containerizer/mesos/isolators/gpu/allocator.hpp" #include "slave/containerizer/mesos/isolators/gpu/isolator.hpp" #include "slave/containerizer/mesos/isolators/gpu/nvml.hpp" using cgroups::devices::Entry; using docker::spec::v1::ImageManifest; using mesos::slave::ContainerConfig; using mesos::slave::ContainerLaunchInfo; using mesos::slave::ContainerLimitation; using mesos::slave::ContainerState; using mesos::slave::Isolator; using process::defer; using process::Failure; using process::Future; using process::PID; using std::list; using std::map; using std::set; using std::string; using std::vector; namespace mesos { namespace internal { namespace slave { NvidiaGpuIsolatorProcess::NvidiaGpuIsolatorProcess( const Flags& _flags, const string& _hierarchy, const NvidiaGpuAllocator& _allocator, const NvidiaVolume& _volume, const map<Path, cgroups::devices::Entry>& _controlDeviceEntries) : ProcessBase(process::ID::generate("mesos-nvidia-gpu-isolator")), flags(_flags), hierarchy(_hierarchy), allocator(_allocator), volume(_volume), controlDeviceEntries(_controlDeviceEntries) {} Try<Isolator*> NvidiaGpuIsolatorProcess::create( const Flags& flags, const NvidiaComponents& components) { // Make sure the 'cgroups/devices' isolator is present and // precedes the GPU isolator. vector<string> tokens = strings::tokenize(flags.isolation, ","); auto gpuIsolator = std::find(tokens.begin(), tokens.end(), "gpu/nvidia"); auto devicesIsolator = std::find(tokens.begin(), tokens.end(), "cgroups/devices"); CHECK(gpuIsolator != tokens.end()); if (devicesIsolator == tokens.end()) { return Error("The 'cgroups/devices' isolator must be enabled in" " order to use the 'gpu/nvidia' isolator"); } if (devicesIsolator > gpuIsolator) { return Error("'cgroups/devices' must precede 'gpu/nvidia'" " in the --isolation flag"); } // Retrieve the cgroups devices hierarchy. Result<string> hierarchy = cgroups::hierarchy("devices"); if (hierarchy.isError()) { return Error( "Error retrieving the 'devices' subsystem hierarchy: " + hierarchy.error()); } // Create device entries for `/dev/nvidiactl` and // `/dev/nvidia-uvm`. Optionally create a device entry for // `/dev/nvidia-uvm-tools` if it exists. map<Path, cgroups::devices::Entry> deviceEntries; Try<dev_t> device = os::stat::rdev("/dev/nvidiactl"); if (device.isError()) { return Error("Failed to obtain device ID for '/dev/nvidiactl': " + device.error()); } cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidiactl")] = entry; device = os::stat::rdev("/dev/nvidia-uvm"); if (device.isError()) { return Error("Failed to obtain device ID for '/dev/nvidia-uvm': " + device.error()); } entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidia-uvm")] = entry; device = os::stat::rdev("/dev/nvidia-uvm-tools"); if (device.isSome()) { entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidia-uvm-tools")] = entry; } process::Owned<MesosIsolatorProcess> process( new NvidiaGpuIsolatorProcess( flags, hierarchy.get(), components.allocator, components.volume, deviceEntries)); return new MesosIsolator(process); } Future<Nothing> NvidiaGpuIsolatorProcess::recover( const list<ContainerState>& states, const hashset<ContainerID>& orphans) { list<Future<Nothing>> futures; foreach (const ContainerState& state, states) { const ContainerID& containerId = state.container_id(); const string cgroup = path::join(flags.cgroups_root, containerId.value()); Try<bool> exists = cgroups::exists(hierarchy, cgroup); if (exists.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure("Failed to check cgroup for container '" + stringify(containerId) + "'"); } if (!exists.get()) { VLOG(1) << "Couldn't find cgroup for container " << containerId; // This may occur if the executor has exited and the isolator // has destroyed the cgroup but the slave dies before noticing // this. This will be detected when the containerizer tries to // monitor the executor's pid. continue; } infos[containerId] = new Info(containerId, cgroup); // Determine which GPUs are allocated to this container. Try<vector<cgroups::devices::Entry>> entries = cgroups::devices::list(hierarchy, cgroup); if (entries.isError()) { return Failure("Failed to obtain devices list for cgroup" " '" + cgroup + "': " + entries.error()); } const set<Gpu>& available = allocator.total(); set<Gpu> containerGpus; foreach (const cgroups::devices::Entry& entry, entries.get()) { foreach (const Gpu& gpu, available) { if (entry.selector.major == gpu.major && entry.selector.minor == gpu.minor) { containerGpus.insert(gpu); break; } } } futures.push_back(allocator.allocate(containerGpus) .then(defer(self(), [=]() -> Future<Nothing> { infos[containerId]->allocated = containerGpus; return Nothing(); }))); } return collect(futures).then([]() { return Nothing(); }); } Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::prepare( const ContainerID& containerId, const mesos::slave::ContainerConfig& containerConfig) { if (infos.contains(containerId)) { return Failure("Container has already been prepared"); } infos[containerId] = new Info( containerId, path::join(flags.cgroups_root, containerId.value())); // Grant access to all `controlDeviceEntries`. // // This allows standard NVIDIA tools like `nvidia-smi` to be // used within the container even if no GPUs are allocated. // Without these devices, these tools fail abnormally. foreachkey (const Path& devicePath, controlDeviceEntries) { Try<Nothing> allow = cgroups::devices::allow( hierarchy, infos[containerId]->cgroup, controlDeviceEntries.at(devicePath)); if (allow.isError()) { return Failure("Failed to grant cgroups access to" " '" + stringify(devicePath) + "': " + allow.error()); } } return update(containerId, containerConfig.executor_info().resources()) .then(defer(PID<NvidiaGpuIsolatorProcess>(this), &NvidiaGpuIsolatorProcess::_prepare, containerConfig)); } // If our `ContainerConfig` specifies a different `rootfs` than the // host file system, then we need to prepare a script to inject our // `NvidiaVolume` into the container (if required). Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::_prepare( const mesos::slave::ContainerConfig& containerConfig) { if (!containerConfig.has_rootfs()) { return None(); } // We only support docker containers at the moment. if (!containerConfig.has_docker()) { // TODO(klueska): Once ContainerConfig has // a type, include that in the error message. return Failure("Nvidia GPU isolator does not support non-Docker images"); } ContainerLaunchInfo launchInfo; launchInfo.set_namespaces(CLONE_NEWNS); // Inject the Nvidia volume into the container. // // TODO(klueska): Inject the Nvidia devices here as well once we // have a way to pass them to `fs:enter()` instead of hardcoding // them in `fs::createStandardDevices()`. if (!containerConfig.docker().has_manifest()) { return Failure("The 'ContainerConfig' for docker is missing a manifest"); } ImageManifest manifest = containerConfig.docker().manifest(); if (volume.shouldInject(manifest)) { const string target = path::join( containerConfig.rootfs(), volume.CONTAINER_PATH()); Try<Nothing> mkdir = os::mkdir(target); if (mkdir.isError()) { return Failure( "Failed to create the container directory at" " '" + target + "': " + mkdir.error()); } launchInfo.add_pre_exec_commands()->set_value( "mount --no-mtab --rbind --read-only " + volume.HOST_PATH() + " " + target); } return launchInfo; } Future<Nothing> NvidiaGpuIsolatorProcess::update( const ContainerID& containerId, const Resources& resources) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); Option<double> gpus = resources.gpus(); // Make sure that the `gpus` resource is not fractional. // We rely on scalar resources only having 3 digits of precision. if (static_cast<long long>(gpus.getOrElse(0.0) * 1000.0) % 1000 != 0) { return Failure("The 'gpus' resource must be an unsigned integer"); } size_t requested = static_cast<size_t>(resources.gpus().getOrElse(0.0)); // Update the GPU allocation to reflect the new total. if (requested > info->allocated.size()) { size_t additional = requested - info->allocated.size(); return allocator.allocate(additional) .then(defer(PID<NvidiaGpuIsolatorProcess>(this), &NvidiaGpuIsolatorProcess::_update, containerId, lambda::_1)); } else if (requested < info->allocated.size()) { size_t fewer = info->allocated.size() - requested; set<Gpu> deallocated; for (size_t i = 0; i < fewer; i++) { const auto gpu = info->allocated.begin(); cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = gpu->major; entry.selector.minor = gpu->minor; entry.access.read = true; entry.access.write = true; entry.access.mknod = true; Try<Nothing> deny = cgroups::devices::deny( hierarchy, info->cgroup, entry); if (deny.isError()) { return Failure("Failed to deny cgroups access to GPU device" " '" + stringify(entry) + "': " + deny.error()); } deallocated.insert(*gpu); info->allocated.erase(gpu); } return allocator.deallocate(deallocated); } return Nothing(); } Future<Nothing> NvidiaGpuIsolatorProcess::_update( const ContainerID& containerId, const set<Gpu>& allocation) { if (!infos.contains(containerId)) { return Failure("Failed to complete GPU allocation: unknown container"); } Info* info = CHECK_NOTNULL(infos.at(containerId)); foreach (const Gpu& gpu, allocation) { cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = gpu.major; entry.selector.minor = gpu.minor; entry.access.read = true; entry.access.write = true; entry.access.mknod = true; Try<Nothing> allow = cgroups::devices::allow( hierarchy, info->cgroup, entry); if (allow.isError()) { return Failure("Failed to grant cgroups access to GPU device" " '" + stringify(entry) + "': " + allow.error()); } } info->allocated = allocation; return Nothing(); } Future<ResourceStatistics> NvidiaGpuIsolatorProcess::usage( const ContainerID& containerId) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } // TODO(rtodd): Obtain usage information from NVML. ResourceStatistics result; return result; } Future<Nothing> NvidiaGpuIsolatorProcess::cleanup( const ContainerID& containerId) { // Multiple calls may occur during test clean up. if (!infos.contains(containerId)) { VLOG(1) << "Ignoring cleanup request for unknown container " << containerId; return Nothing(); } Info* info = CHECK_NOTNULL(infos.at(containerId)); // Make any remaining GPUs available. return allocator.deallocate(info->allocated) .then(defer(self(), [=]() -> Future<Nothing> { CHECK(infos.contains(containerId)); delete infos.at(containerId); infos.erase(containerId); return Nothing(); })); } } // namespace slave { } // namespace internal { } // namespace mesos { <commit_msg>Updated the 'gpu/nvidia' isolator to be nested container aware.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <algorithm> #include <list> #include <map> #include <set> #include <string> #include <vector> #include <process/collect.hpp> #include <process/defer.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <stout/error.hpp> #include <stout/foreach.hpp> #include <stout/hashmap.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/try.hpp> #include "linux/cgroups.hpp" #include "slave/flags.hpp" #include "slave/containerizer/containerizer.hpp" #include "slave/containerizer/mesos/isolator.hpp" #include "slave/containerizer/mesos/isolators/cgroups/constants.hpp" #include "slave/containerizer/mesos/isolators/gpu/allocator.hpp" #include "slave/containerizer/mesos/isolators/gpu/isolator.hpp" #include "slave/containerizer/mesos/isolators/gpu/nvml.hpp" using cgroups::devices::Entry; using docker::spec::v1::ImageManifest; using mesos::slave::ContainerConfig; using mesos::slave::ContainerLaunchInfo; using mesos::slave::ContainerLimitation; using mesos::slave::ContainerState; using mesos::slave::Isolator; using process::defer; using process::Failure; using process::Future; using process::PID; using std::list; using std::map; using std::set; using std::string; using std::vector; namespace mesos { namespace internal { namespace slave { NvidiaGpuIsolatorProcess::NvidiaGpuIsolatorProcess( const Flags& _flags, const string& _hierarchy, const NvidiaGpuAllocator& _allocator, const NvidiaVolume& _volume, const map<Path, cgroups::devices::Entry>& _controlDeviceEntries) : ProcessBase(process::ID::generate("mesos-nvidia-gpu-isolator")), flags(_flags), hierarchy(_hierarchy), allocator(_allocator), volume(_volume), controlDeviceEntries(_controlDeviceEntries) {} Try<Isolator*> NvidiaGpuIsolatorProcess::create( const Flags& flags, const NvidiaComponents& components) { // Make sure the 'cgroups/devices' isolator is present and // precedes the GPU isolator. vector<string> tokens = strings::tokenize(flags.isolation, ","); auto gpuIsolator = std::find(tokens.begin(), tokens.end(), "gpu/nvidia"); auto devicesIsolator = std::find(tokens.begin(), tokens.end(), "cgroups/devices"); CHECK(gpuIsolator != tokens.end()); if (devicesIsolator == tokens.end()) { return Error("The 'cgroups/devices' isolator must be enabled in" " order to use the 'gpu/nvidia' isolator"); } if (devicesIsolator > gpuIsolator) { return Error("'cgroups/devices' must precede 'gpu/nvidia'" " in the --isolation flag"); } // Retrieve the cgroups devices hierarchy. Result<string> hierarchy = cgroups::hierarchy(CGROUP_SUBSYSTEM_DEVICES_NAME); if (hierarchy.isError()) { return Error( "Error retrieving the 'devices' subsystem hierarchy: " + hierarchy.error()); } // Create device entries for `/dev/nvidiactl` and // `/dev/nvidia-uvm`. Optionally create a device entry for // `/dev/nvidia-uvm-tools` if it exists. map<Path, cgroups::devices::Entry> deviceEntries; Try<dev_t> device = os::stat::rdev("/dev/nvidiactl"); if (device.isError()) { return Error("Failed to obtain device ID for '/dev/nvidiactl': " + device.error()); } cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidiactl")] = entry; device = os::stat::rdev("/dev/nvidia-uvm"); if (device.isError()) { return Error("Failed to obtain device ID for '/dev/nvidia-uvm': " + device.error()); } entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidia-uvm")] = entry; device = os::stat::rdev("/dev/nvidia-uvm-tools"); if (device.isSome()) { entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = major(device.get()); entry.selector.minor = minor(device.get()); entry.access.read = true; entry.access.write = true; entry.access.mknod = true; deviceEntries[Path("/dev/nvidia-uvm-tools")] = entry; } process::Owned<MesosIsolatorProcess> process( new NvidiaGpuIsolatorProcess( flags, hierarchy.get(), components.allocator, components.volume, deviceEntries)); return new MesosIsolator(process); } Future<Nothing> NvidiaGpuIsolatorProcess::recover( const list<ContainerState>& states, const hashset<ContainerID>& orphans) { list<Future<Nothing>> futures; foreach (const ContainerState& state, states) { const ContainerID& containerId = state.container_id(); // If we are a nested container, we skip the recover because our // root ancestor will recover the GPU state from the cgroup for us. if (containerId.has_parent()) { continue; } const string cgroup = path::join(flags.cgroups_root, containerId.value()); Try<bool> exists = cgroups::exists(hierarchy, cgroup); if (exists.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure( "Failed to check the existence of the cgroup " "'" + cgroup + "' in hierarchy '" + hierarchy + "' " "for container " + stringify(containerId) + ": " + exists.error()); } if (!exists.get()) { // This may occur if the executor has exited and the isolator // has destroyed the cgroup but the slave dies before noticing // this. This will be detected when the containerizer tries to // monitor the executor's pid. LOG(WARNING) << "Couldn't find the cgroup '" << cgroup << "' " << "in hierarchy '" << hierarchy << "' " << "for container " << containerId; continue; } infos[containerId] = new Info(containerId, cgroup); // Determine which GPUs are allocated to this container. Try<vector<cgroups::devices::Entry>> entries = cgroups::devices::list(hierarchy, cgroup); if (entries.isError()) { return Failure("Failed to obtain devices list for cgroup" " '" + cgroup + "': " + entries.error()); } const set<Gpu>& available = allocator.total(); set<Gpu> containerGpus; foreach (const cgroups::devices::Entry& entry, entries.get()) { foreach (const Gpu& gpu, available) { if (entry.selector.major == gpu.major && entry.selector.minor == gpu.minor) { containerGpus.insert(gpu); break; } } } futures.push_back(allocator.allocate(containerGpus) .then(defer(self(), [=]() -> Future<Nothing> { infos[containerId]->allocated = containerGpus; return Nothing(); }))); } return collect(futures).then([]() { return Nothing(); }); } Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::prepare( const ContainerID& containerId, const mesos::slave::ContainerConfig& containerConfig) { // If we are a nested container, we don't need to maintain an `Info()` // struct about the container since we don't allocate GPUs to it // directly (we only allocate GPUs to top-level containers, and they // automatically get shared by nested containers). However, we do // still need to mount the necessary Nvidia libraries into the // container. We call `_prepare()` directly to do this for us. if (containerId.has_parent()) { return _prepare(containerConfig); } if (infos.contains(containerId)) { return Failure("Container has already been prepared"); } infos[containerId] = new Info( containerId, path::join(flags.cgroups_root, containerId.value())); // Grant access to all `controlDeviceEntries`. // // This allows standard NVIDIA tools like `nvidia-smi` to be // used within the container even if no GPUs are allocated. // Without these devices, these tools fail abnormally. foreachkey (const Path& devicePath, controlDeviceEntries) { Try<Nothing> allow = cgroups::devices::allow( hierarchy, infos[containerId]->cgroup, controlDeviceEntries.at(devicePath)); if (allow.isError()) { return Failure("Failed to grant cgroups access to" " '" + stringify(devicePath) + "': " + allow.error()); } } return update(containerId, containerConfig.executor_info().resources()) .then(defer(PID<NvidiaGpuIsolatorProcess>(this), &NvidiaGpuIsolatorProcess::_prepare, containerConfig)); } // If our `ContainerConfig` specifies a different `rootfs` than the // host file system, then we need to prepare a script to inject our // `NvidiaVolume` into the container (if required). Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::_prepare( const mesos::slave::ContainerConfig& containerConfig) { if (!containerConfig.has_rootfs()) { return None(); } // We only support docker containers at the moment. if (!containerConfig.has_docker()) { // TODO(klueska): Once ContainerConfig has // a type, include that in the error message. return Failure("Nvidia GPU isolator does not support non-Docker images"); } ContainerLaunchInfo launchInfo; launchInfo.set_namespaces(CLONE_NEWNS); // Inject the Nvidia volume into the container. // // TODO(klueska): Inject the Nvidia devices here as well once we // have a way to pass them to `fs:enter()` instead of hardcoding // them in `fs::createStandardDevices()`. if (!containerConfig.docker().has_manifest()) { return Failure("The 'ContainerConfig' for docker is missing a manifest"); } ImageManifest manifest = containerConfig.docker().manifest(); if (volume.shouldInject(manifest)) { const string target = path::join( containerConfig.rootfs(), volume.CONTAINER_PATH()); Try<Nothing> mkdir = os::mkdir(target); if (mkdir.isError()) { return Failure( "Failed to create the container directory at" " '" + target + "': " + mkdir.error()); } launchInfo.add_pre_exec_commands()->set_value( "mount --no-mtab --rbind --read-only " + volume.HOST_PATH() + " " + target); } return launchInfo; } Future<Nothing> NvidiaGpuIsolatorProcess::update( const ContainerID& containerId, const Resources& resources) { if (containerId.has_parent()) { return Failure("Not supported for nested containers"); } if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); Option<double> gpus = resources.gpus(); // Make sure that the `gpus` resource is not fractional. // We rely on scalar resources only having 3 digits of precision. if (static_cast<long long>(gpus.getOrElse(0.0) * 1000.0) % 1000 != 0) { return Failure("The 'gpus' resource must be an unsigned integer"); } size_t requested = static_cast<size_t>(resources.gpus().getOrElse(0.0)); // Update the GPU allocation to reflect the new total. if (requested > info->allocated.size()) { size_t additional = requested - info->allocated.size(); return allocator.allocate(additional) .then(defer(PID<NvidiaGpuIsolatorProcess>(this), &NvidiaGpuIsolatorProcess::_update, containerId, lambda::_1)); } else if (requested < info->allocated.size()) { size_t fewer = info->allocated.size() - requested; set<Gpu> deallocated; for (size_t i = 0; i < fewer; i++) { const auto gpu = info->allocated.begin(); cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = gpu->major; entry.selector.minor = gpu->minor; entry.access.read = true; entry.access.write = true; entry.access.mknod = true; Try<Nothing> deny = cgroups::devices::deny( hierarchy, info->cgroup, entry); if (deny.isError()) { return Failure("Failed to deny cgroups access to GPU device" " '" + stringify(entry) + "': " + deny.error()); } deallocated.insert(*gpu); info->allocated.erase(gpu); } return allocator.deallocate(deallocated); } return Nothing(); } Future<Nothing> NvidiaGpuIsolatorProcess::_update( const ContainerID& containerId, const set<Gpu>& allocation) { if (!infos.contains(containerId)) { return Failure("Failed to complete GPU allocation: unknown container"); } Info* info = CHECK_NOTNULL(infos.at(containerId)); foreach (const Gpu& gpu, allocation) { cgroups::devices::Entry entry; entry.selector.type = Entry::Selector::Type::CHARACTER; entry.selector.major = gpu.major; entry.selector.minor = gpu.minor; entry.access.read = true; entry.access.write = true; entry.access.mknod = true; Try<Nothing> allow = cgroups::devices::allow( hierarchy, info->cgroup, entry); if (allow.isError()) { return Failure("Failed to grant cgroups access to GPU device" " '" + stringify(entry) + "': " + allow.error()); } } info->allocated = allocation; return Nothing(); } Future<ResourceStatistics> NvidiaGpuIsolatorProcess::usage( const ContainerID& containerId) { if (containerId.has_parent()) { return Failure("Not supported for nested containers"); } if (!infos.contains(containerId)) { return Failure("Unknown container"); } // TODO(rtodd): Obtain usage information from NVML. ResourceStatistics result; return result; } Future<Nothing> NvidiaGpuIsolatorProcess::cleanup( const ContainerID& containerId) { // If we are a nested container, we don't have an `Info()` struct to // cleanup, so we just return immediately. if (containerId.has_parent()) { return Nothing(); } // Multiple calls may occur during test clean up. if (!infos.contains(containerId)) { VLOG(1) << "Ignoring cleanup request for unknown container " << containerId; return Nothing(); } Info* info = CHECK_NOTNULL(infos.at(containerId)); // Make any remaining GPUs available. return allocator.deallocate(info->allocated) .then(defer(self(), [=]() -> Future<Nothing> { CHECK(infos.contains(containerId)); delete infos.at(containerId); infos.erase(containerId); return Nothing(); })); } } // namespace slave { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* tweenerhandler.cpp - Negociation with Passport to get the login ticket. Copyright (c) 2006 by Michaël Larouche <[email protected]> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "tweenerhandler.h" // Qt includes #include <QtDebug> #include <QtCore/QRegExp> #include <QtCore/QUrl> #include <QtNetwork/QHttpHeader> #include <QtNetwork/QHttpRequestHeader> #include <QtNetwork/QHttpResponseHeader> // Papillon includes #include "securestream.h" namespace Papillon { class TweenerHandler::Private { public: Private() : stream(0), success(false) {} ~Private() { delete stream; } QString tweener; QString passportId; QString password; QString ticket; QString loginUrl; SecureStream *stream; bool success; TweenerHandler::TweenerState state; }; TweenerHandler::TweenerHandler(SecureStream *stream) : QObject(0), d(new Private) { d->stream = stream; connect(d->stream, SIGNAL(connected()), this, SLOT(slotConnected())); connect(d->stream, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); } TweenerHandler::~TweenerHandler() { delete d; } void TweenerHandler::setLoginInformation(const QString &tweener, const QString &passportId, const QString &password) { d->tweener = tweener; d->passportId = passportId; d->password = password; } void TweenerHandler::start() { qDebug() << PAPILLON_FUNCINFO << "Begin tweener ticket negociation."; Q_ASSERT( !d->tweener.isEmpty() ); Q_ASSERT( !d->passportId.isEmpty() ); Q_ASSERT( !d->password.isEmpty() ); d->state = TwnGetServer; d->stream->connectToServer("nexus.passport.com"); } void TweenerHandler::slotConnected() { qDebug() << PAPILLON_FUNCINFO << "We are connected"; switch(d->state) { case TwnGetServer: { qDebug() << PAPILLON_FUNCINFO << "Getting real login server host..."; QHttpRequestHeader getLoginServer( QLatin1String("GET"), QLatin1String("/rdr/pprdr.asp"), 1, 0 ); sendRequest(getLoginServer); break; } case TwnAuth: { qDebug() << PAPILLON_FUNCINFO << "Sending auth..."; QHttpRequestHeader login( QLatin1String("GET"), d->loginUrl ); login.setValue( QLatin1String("Host"), QLatin1String("login.passport.com") ); QString authRequest = QLatin1String("Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=") + QUrl::toPercentEncoding(d->passportId) + QLatin1String(",pwd=") + QUrl::toPercentEncoding(d->password ).replace(',',"%2C") + QLatin1String(",") + d->tweener; login.setValue( QLatin1String("Authorization"), authRequest ); sendRequest(login); break; } default: break; } } void TweenerHandler::slotReadyRead() { QByteArray read = d->stream->read(); QString temp(read); QHttpResponseHeader httpHeader( temp ); if( !httpHeader.isValid() ) qDebug() << PAPILLON_FUNCINFO << "QHttpResponseHeader is not valid !"; // Handle Redirection(302) if( httpHeader.statusCode() == 302 ) { QString location = httpHeader.value( QLatin1String("location") ); QString loginServer = location.section("/", 0, 0); d->loginUrl = QLatin1String("/") + location.section("/", 1); qDebug() << PAPILLON_FUNCINFO << "Redirect to" << location; changeServer(loginServer); } // Handle failure(401 Unauthorized) else if( httpHeader.statusCode() == 401 ) { qDebug() << PAPILLON_FUNCINFO << "Passport refused the password."; emitResult(false); } else if( httpHeader.statusCode() == 400 ) { qDebug() << PAPILLON_FUNCINFO << "DEBUG: Bad request."; } // 200 OK, do the result parsing else if( httpHeader.statusCode() == 200 ) { switch(d->state) { case TwnGetServer: { // Retrieve login url from resulting HTTP header. QString passportUrls = httpHeader.value( QLatin1String("passporturls") ); QRegExp rx("DARealm=(.*),DALogin=(.*),DAReg="); rx.search(passportUrls); QString login = rx.cap(2); QString loginServer = login.section("/", 0, 0); d->loginUrl = QLatin1String("/") + login.section("/", 1); // Change state of negociation process. d->state = TwnAuth; qDebug() << PAPILLON_FUNCINFO << "Connecting to auth server. Server:" << login; // Connect to given URL. changeServer(loginServer); break; } case TwnAuth: { QString authInfo = httpHeader.value( QLatin1String("authentication-info") ); QRegExp rx("from-PP='(.*)'"); rx.search(authInfo); d->ticket = rx.cap(1); d->stream->disconnectFromServer(); emitResult(true); break; } default: break; } } } void TweenerHandler::changeServer(const QString &host) { d->stream->disconnectFromServer(); d->stream->connectToServer(host); } void TweenerHandler::sendRequest(const QHttpRequestHeader &httpHeader) { // qDebug() << PAPILLON_FUNCINFO << "Sending: " << httpHeader.toString().replace("\r", "(r)").replace("\n", "(n)"); QByteArray data; data += httpHeader.toString().toUtf8(); // Insert empty body. data += "\r\n"; d->stream->write( data ); } bool TweenerHandler::success() const { return d->success; } QString TweenerHandler::ticket() const { return d->ticket; } void TweenerHandler::emitResult(bool success) { d->stream->disconnectFromServer(); d->success = success; emit result(this); } } #include "tweenerhandler.moc" <commit_msg>Use Qt4 API for QRegExp, not qt3support method (that's a shame for a new Qt4 library :P)<commit_after>/* tweenerhandler.cpp - Negociation with Passport to get the login ticket. Copyright (c) 2006 by Michaël Larouche <[email protected]> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "tweenerhandler.h" // Qt includes #include <QtDebug> #include <QtCore/QRegExp> #include <QtCore/QUrl> #include <QtNetwork/QHttpHeader> #include <QtNetwork/QHttpRequestHeader> #include <QtNetwork/QHttpResponseHeader> // Papillon includes #include "securestream.h" namespace Papillon { class TweenerHandler::Private { public: Private() : stream(0), success(false) {} ~Private() { delete stream; } QString tweener; QString passportId; QString password; QString ticket; QString loginUrl; SecureStream *stream; bool success; TweenerHandler::TweenerState state; }; TweenerHandler::TweenerHandler(SecureStream *stream) : QObject(0), d(new Private) { d->stream = stream; connect(d->stream, SIGNAL(connected()), this, SLOT(slotConnected())); connect(d->stream, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); } TweenerHandler::~TweenerHandler() { delete d; } void TweenerHandler::setLoginInformation(const QString &tweener, const QString &passportId, const QString &password) { d->tweener = tweener; d->passportId = passportId; d->password = password; } void TweenerHandler::start() { qDebug() << PAPILLON_FUNCINFO << "Begin tweener ticket negociation."; Q_ASSERT( !d->tweener.isEmpty() ); Q_ASSERT( !d->passportId.isEmpty() ); Q_ASSERT( !d->password.isEmpty() ); d->state = TwnGetServer; d->stream->connectToServer("nexus.passport.com"); } void TweenerHandler::slotConnected() { qDebug() << PAPILLON_FUNCINFO << "We are connected"; switch(d->state) { case TwnGetServer: { qDebug() << PAPILLON_FUNCINFO << "Getting real login server host..."; QHttpRequestHeader getLoginServer( QLatin1String("GET"), QLatin1String("/rdr/pprdr.asp"), 1, 0 ); sendRequest(getLoginServer); break; } case TwnAuth: { qDebug() << PAPILLON_FUNCINFO << "Sending auth..."; QHttpRequestHeader login( QLatin1String("GET"), d->loginUrl ); login.setValue( QLatin1String("Host"), QLatin1String("login.passport.com") ); QString authRequest = QLatin1String("Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=") + QUrl::toPercentEncoding(d->passportId) + QLatin1String(",pwd=") + QUrl::toPercentEncoding(d->password ).replace(',',"%2C") + QLatin1String(",") + d->tweener; login.setValue( QLatin1String("Authorization"), authRequest ); sendRequest(login); break; } default: break; } } void TweenerHandler::slotReadyRead() { QByteArray read = d->stream->read(); QString temp(read); QHttpResponseHeader httpHeader( temp ); if( !httpHeader.isValid() ) qDebug() << PAPILLON_FUNCINFO << "QHttpResponseHeader is not valid !"; // Handle Redirection(302) if( httpHeader.statusCode() == 302 ) { QString location = httpHeader.value( QLatin1String("location") ); QString loginServer = location.section("/", 0, 0); d->loginUrl = QLatin1String("/") + location.section("/", 1); qDebug() << PAPILLON_FUNCINFO << "Redirect to" << location; changeServer(loginServer); } // Handle failure(401 Unauthorized) else if( httpHeader.statusCode() == 401 ) { qDebug() << PAPILLON_FUNCINFO << "Passport refused the password."; emitResult(false); } else if( httpHeader.statusCode() == 400 ) { qDebug() << PAPILLON_FUNCINFO << "DEBUG: Bad request."; } // 200 OK, do the result parsing else if( httpHeader.statusCode() == 200 ) { switch(d->state) { case TwnGetServer: { // Retrieve login url from resulting HTTP header. QString passportUrls = httpHeader.value( QLatin1String("passporturls") ); QRegExp rx("DARealm=(.*),DALogin=(.*),DAReg="); rx.indexIn(passportUrls); QString login = rx.cap(2); QString loginServer = login.section("/", 0, 0); d->loginUrl = QLatin1String("/") + login.section("/", 1); // Change state of negociation process. d->state = TwnAuth; qDebug() << PAPILLON_FUNCINFO << "Connecting to auth server. Server:" << login; // Connect to given URL. changeServer(loginServer); break; } case TwnAuth: { QString authInfo = httpHeader.value( QLatin1String("authentication-info") ); QRegExp rx("from-PP='(.*)'"); rx.indexIn(authInfo); d->ticket = rx.cap(1); d->stream->disconnectFromServer(); emitResult(true); break; } default: break; } } } void TweenerHandler::changeServer(const QString &host) { d->stream->disconnectFromServer(); d->stream->connectToServer(host); } void TweenerHandler::sendRequest(const QHttpRequestHeader &httpHeader) { // qDebug() << PAPILLON_FUNCINFO << "Sending: " << httpHeader.toString().replace("\r", "(r)").replace("\n", "(n)"); QByteArray data; data += httpHeader.toString().toUtf8(); // Insert empty body. data += "\r\n"; d->stream->write( data ); } bool TweenerHandler::success() const { return d->success; } QString TweenerHandler::ticket() const { return d->ticket; } void TweenerHandler::emitResult(bool success) { d->stream->disconnectFromServer(); d->success = success; emit result(this); } } #include "tweenerhandler.moc" <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <chartsql/runtime/ScalarExpression.h> #include <fnord/inspect.h> using namespace fnord; namespace csql { ScalarExpression::ScalarExpression( Instruction* expr, size_t scratchpad_size) : expr_(expr), scratchpad_size_(scratchpad_size) {} ScalarExpression::~ScalarExpression() { // FIXPAUL free instructions... } ScalarExpression::Instance ScalarExpression::allocInstance( ScratchMemory* scratch) const { Instance that; that.scratch = scratch->alloc(scratchpad_size_); fnord::iputs("init scratch @ $0", (uint64_t) that.scratch); init(expr_, &that); return that; } void ScalarExpression::freeInstance(Instance* instance) const { free(expr_, instance); } void ScalarExpression::reset(Instance* instance) const { reset(expr_, instance); } void ScalarExpression::init(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: if (e->vtable.t_aggregate.init) { e->vtable.t_aggregate.init( (char *) instance->scratch + (size_t) e->arg0); } break; default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { init(cur, instance); } } void ScalarExpression::free(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: if (e->vtable.t_aggregate.free) { e->vtable.t_aggregate.free( (char *) instance->scratch + (size_t) e->arg0); } break; case X_LITERAL: fnord::iputs("free literal: $0", (uint64_t) e); default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { free(cur, instance); } } void ScalarExpression::reset(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: e->vtable.t_aggregate.reset( (char *) instance->scratch + (size_t) e->arg0); break; default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { reset(cur, instance); } } void ScalarExpression::evaluate( Instance* instance, int argc, const SValue* argv, SValue* out) const { return evaluate(instance, expr_, argc, argv, out); } void ScalarExpression::accumulate( Instance* instance, int argc, const SValue* argv) const { return accumulate(instance, expr_, argc, argv); } void ScalarExpression::evaluate( Instance* instance, Instruction* expr, int argc, const SValue* argv, SValue* out) const { /* execute expression */ switch (expr->type) { case X_CALL_PURE: { SValue* stackv = nullptr; auto stackn = expr->argn; if (stackn > 0) { stackv = reinterpret_cast<SValue*>( alloca(sizeof(SValue) * expr->argn)); for (int i = 0; i < stackn; ++i) { new (stackv + i) SValue(); } auto stackp = stackv; for (auto cur = expr->child; cur != nullptr; cur = cur->next) { evaluate( instance, cur, argc, argv, stackp++); } } expr->vtable.t_pure.call(stackn, stackv, out); return; } case X_CALL_AGGREGATE: { auto scratch = (char *) instance->scratch + (size_t) expr->arg0; expr->vtable.t_aggregate.get(scratch, out); return; } case X_LITERAL: { *out = *static_cast<SValue*>(expr->arg0); return; } case X_INPUT: { auto index = reinterpret_cast<uint64_t>(expr->arg0); if (index >= argc) { RAISE(kRuntimeError, "invalid row index %i", index); } *out = argv[index]; return; } } } void ScalarExpression::accumulate( Instance* instance, Instruction* expr, int argc, const SValue* argv) const { switch (expr->type) { case X_CALL_AGGREGATE: { SValue* stackv = nullptr; auto stackn = expr->argn; if (stackn > 0) { stackv = reinterpret_cast<SValue*>( alloca(sizeof(SValue) * expr->argn)); for (int i = 0; i < stackn; ++i) { new (stackv + i) SValue(); } auto stackp = stackv; for (auto cur = expr->child; cur != nullptr; cur = cur->next) { evaluate( instance, cur, argc, argv, stackp++); } } auto scratch = (char *) instance->scratch + (size_t) expr->arg0; expr->vtable.t_aggregate.accumulate(scratch, stackn, stackv); return; } default: { for (auto cur = expr->child; cur != nullptr; cur = cur->next) { accumulate(instance, cur, argc, argv); } return; } } } } <commit_msg>ScalarExpression::evaluateStatic<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <chartsql/runtime/ScalarExpression.h> #include <fnord/inspect.h> using namespace fnord; namespace csql { ScalarExpression::ScalarExpression( Instruction* expr, size_t scratchpad_size) : expr_(expr), scratchpad_size_(scratchpad_size) {} ScalarExpression::~ScalarExpression() { // FIXPAUL free instructions... } ScalarExpression::Instance ScalarExpression::allocInstance( ScratchMemory* scratch) const { Instance that; that.scratch = scratch->alloc(scratchpad_size_); fnord::iputs("init scratch @ $0", (uint64_t) that.scratch); init(expr_, &that); return that; } void ScalarExpression::freeInstance(Instance* instance) const { free(expr_, instance); } void ScalarExpression::reset(Instance* instance) const { reset(expr_, instance); } void ScalarExpression::init(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: if (e->vtable.t_aggregate.init) { e->vtable.t_aggregate.init( (char *) instance->scratch + (size_t) e->arg0); } break; default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { init(cur, instance); } } void ScalarExpression::free(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: if (e->vtable.t_aggregate.free) { e->vtable.t_aggregate.free( (char *) instance->scratch + (size_t) e->arg0); } break; case X_LITERAL: fnord::iputs("free literal: $0", (uint64_t) e); default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { free(cur, instance); } } void ScalarExpression::reset(Instruction* e, Instance* instance) const { switch (e->type) { case X_CALL_AGGREGATE: e->vtable.t_aggregate.reset( (char *) instance->scratch + (size_t) e->arg0); break; default: break; } for (auto cur = e->child; cur != nullptr; cur = cur->next) { reset(cur, instance); } } void ScalarExpression::evaluate( Instance* instance, int argc, const SValue* argv, SValue* out) const { return evaluate(instance, expr_, argc, argv, out); } void ScalarExpression::evaluateStatic( int argc, const SValue* argv, SValue* out) const { return evaluate(nullptr, expr_, argc, argv, out); } void ScalarExpression::accumulate( Instance* instance, int argc, const SValue* argv) const { return accumulate(instance, expr_, argc, argv); } void ScalarExpression::evaluate( Instance* instance, Instruction* expr, int argc, const SValue* argv, SValue* out) const { /* execute expression */ switch (expr->type) { case X_CALL_PURE: { SValue* stackv = nullptr; auto stackn = expr->argn; if (stackn > 0) { stackv = reinterpret_cast<SValue*>( alloca(sizeof(SValue) * expr->argn)); for (int i = 0; i < stackn; ++i) { new (stackv + i) SValue(); } auto stackp = stackv; for (auto cur = expr->child; cur != nullptr; cur = cur->next) { evaluate( instance, cur, argc, argv, stackp++); } } expr->vtable.t_pure.call(stackn, stackv, out); return; } case X_CALL_AGGREGATE: { if (!instance) { RAISE( kIllegalArgumentError, "non-static expression called without instance pointer"); } auto scratch = (char *) instance->scratch + (size_t) expr->arg0; expr->vtable.t_aggregate.get(scratch, out); return; } case X_LITERAL: { *out = *static_cast<SValue*>(expr->arg0); return; } case X_INPUT: { auto index = reinterpret_cast<uint64_t>(expr->arg0); if (index >= argc) { RAISE(kRuntimeError, "invalid row index %i", index); } *out = argv[index]; return; } } } void ScalarExpression::accumulate( Instance* instance, Instruction* expr, int argc, const SValue* argv) const { switch (expr->type) { case X_CALL_AGGREGATE: { SValue* stackv = nullptr; auto stackn = expr->argn; if (stackn > 0) { stackv = reinterpret_cast<SValue*>( alloca(sizeof(SValue) * expr->argn)); for (int i = 0; i < stackn; ++i) { new (stackv + i) SValue(); } auto stackp = stackv; for (auto cur = expr->child; cur != nullptr; cur = cur->next) { evaluate( instance, cur, argc, argv, stackp++); } } auto scratch = (char *) instance->scratch + (size_t) expr->arg0; expr->vtable.t_aggregate.accumulate(scratch, stackn, stackv); return; } default: { for (auto cur = expr->child; cur != nullptr; cur = cur->next) { accumulate(instance, cur, argc, argv); } return; } } } } <|endoftext|>
<commit_before>/* * Restructuring Shogun's statistical hypothesis testing framework. * Copyright (C) 2014 Soumyajit De * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http:/www.gnu.org/licenses/>. */ #include <shogun/statistical_testing/internals/InitPerFeature.h> #include <shogun/statistical_testing/internals/DataFetcher.h> #include <shogun/statistical_testing/internals/DataFetcherFactory.h> #include <shogun/features/Features.h> using namespace shogun; using namespace internal; InitPerFeature::InitPerFeature(std::unique_ptr<DataFetcher>& fetcher) : m_fetcher(fetcher) { } InitPerFeature::~InitPerFeature() { } InitPerFeature& InitPerFeature::operator=(CFeatures* feats) { m_fetcher = std::unique_ptr<DataFetcher>(DataFetcherFactory::get_instance(feats)); return *this; } InitPerFeature::operator const CFeatures*() const { return m_fetcher->m_samples.get(); } <commit_msg>removed shared ptr from init per feature<commit_after>/* * Restructuring Shogun's statistical hypothesis testing framework. * Copyright (C) 2014 Soumyajit De * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http:/www.gnu.org/licenses/>. */ #include <shogun/statistical_testing/internals/InitPerFeature.h> #include <shogun/statistical_testing/internals/DataFetcher.h> #include <shogun/statistical_testing/internals/DataFetcherFactory.h> #include <shogun/features/Features.h> using namespace shogun; using namespace internal; InitPerFeature::InitPerFeature(std::unique_ptr<DataFetcher>& fetcher) : m_fetcher(fetcher) { } InitPerFeature::~InitPerFeature() { } InitPerFeature& InitPerFeature::operator=(CFeatures* feats) { m_fetcher = std::unique_ptr<DataFetcher>(DataFetcherFactory::get_instance(feats)); return *this; } InitPerFeature::operator const CFeatures*() const { return m_fetcher->m_samples; } <|endoftext|>
<commit_before>/* * TTBlue 3rd order Butterworth Lowpass Filter Object * Copyright © 2008, Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTLowpassButterworth3.h" #define thisTTClass TTLowpassButterworth3 #define thisTTClassName "lowpass.butterworth.3" #define thisTTClassTags "audio, processor, filter, lowpass, butterworth" TT_AUDIO_CONSTRUCTOR { // register attributes addAttributeWithSetter(Frequency, kTypeFloat64); addAttributeProperty(Frequency, range, TTValue(10.0, sr*0.475)); addAttributeProperty(Frequency, rangeChecking, TT("clip")); // register for notifications from the parent class so we can allocate memory as required registerMessageWithArgument(updateMaxNumChannels); // register for notifications from the parent class so we can recalculate coefficients as required addMessage(updateSr); // make the clear method available to the outside world addMessage(Clear); // Set Defaults... setAttributeValue(TT("MaxNumChannels"), arguments); // This attribute is inherited setAttributeValue(TT("Frequency"), 1000.0); setProcessMethod(processAudio); setCalculateMethod(calculateValue); } TTLowpassButterworth3::~TTLowpassButterworth3() { ; } TTErr TTLowpassButterworth3::updateMaxNumChannels(const TTValue& oldMaxNumChannels) { mX1.resize(maxNumChannels); mX2.resize(maxNumChannels); mX3.resize(maxNumChannels); mY1.resize(maxNumChannels); mY2.resize(maxNumChannels); mY3.resize(maxNumChannels); Clear(); return kTTErrNone; } TTErr TTLowpassButterworth3::updateSr() { TTValue v(mFrequency); return setFrequency(v); } TTErr TTLowpassButterworth3::Clear() { mX1.assign(maxNumChannels, 0.0); mX2.assign(maxNumChannels, 0.0); mX3.assign(maxNumChannels, 0.0); mY1.assign(maxNumChannels, 0.0); mY2.assign(maxNumChannels, 0.0); mY3.assign(maxNumChannels, 0.0); return kTTErrNone; } TTErr TTLowpassButterworth3::setFrequency(const TTValue& newValue) { mFrequency = newValue; mRadians = kTTTwoPi*mFrequency; mRadiansSquared = mRadians * mRadians; mRadiansCubic = mRadiansSquared * mRadians; mK = mRadians/tan(kTTPi*mFrequency/sr); // kTTTwoPi*frequency/tan(kTTPi*frequency/sr); mKSquared = mK * mK; mKCubic = mKSquared * mK; calculateCoefficients(); return kTTErrNone; } void TTLowpassButterworth3::calculateCoefficients() //TODO: with a little bit of thinking, this can be optimized { TTFloat64 temp1; temp1 = (mRadiansCubic + mKCubic + 2*mRadiansSquared*mK + 2*mRadians*mKSquared); mA0 = (mRadiansCubic) / temp1; mA1 = (3*mRadiansCubic) / temp1; //mA2 = mA1; //mA2 = (3*mRadiansCubic) / temp1; //mA3 = mA0; //mA3 = (mRadiansCubic) / temp1; mB1 = (3*mRadiansCubic - 3*mKCubic + 2*mRadiansSquared*mK - 2*mRadians*mKSquared) / temp1; mB2 = (3*mRadiansCubic + 3*mKCubic - 2*mRadiansSquared*mK - 2*mRadians*mKSquared) / temp1; mB3 = (mRadiansCubic - mKCubic - 2*mRadiansSquared*mK + 2*mRadians*mKSquared) / temp1; } inline TTErr TTLowpassButterworth3::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt channel) { //y = TTAntiDenormal(mA0*x + mA1*mX1[channel] + mA2*mX2[channel] + mA3*mX3[channel] - mB1*mY1[channel] - mB2*mY2[channel] -mB3*mY3[channel]); // since mA2 = mA1 and mA3 = mA0, we can write y = mA0*(x +mX3[channel]) + mA1*(mX1[channel] + mX2[channel]) - mB1*mY1[channel] - mB2*mY2[channel] -mB3*mY3[channel]; TTZeroDenormal(y); mX3[channel] = mX2[channel]; mX2[channel] = mX1[channel]; mX1[channel] = x; mY3[channel] = mY2[channel]; mY2[channel] = mY1[channel]; mY1[channel] = y; return kTTErrNone; } TTErr TTLowpassButterworth3::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); } <commit_msg>TTLowpassButterworth3: assigning values to a1 and a2 -- even if we are optimizing them out in the process method, it is better to see legit values in the debugger than totally bogus uninitialized memory.<commit_after>/* * TTBlue 3rd order Butterworth Lowpass Filter Object * Copyright © 2008, Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTLowpassButterworth3.h" #define thisTTClass TTLowpassButterworth3 #define thisTTClassName "lowpass.butterworth.3" #define thisTTClassTags "audio, processor, filter, lowpass, butterworth" TT_AUDIO_CONSTRUCTOR { // register attributes addAttributeWithSetter(Frequency, kTypeFloat64); addAttributeProperty(Frequency, range, TTValue(10.0, sr*0.475)); addAttributeProperty(Frequency, rangeChecking, TT("clip")); // register for notifications from the parent class so we can allocate memory as required registerMessageWithArgument(updateMaxNumChannels); // register for notifications from the parent class so we can recalculate coefficients as required addMessage(updateSr); // make the clear method available to the outside world addMessage(Clear); // Set Defaults... setAttributeValue(TT("MaxNumChannels"), arguments); // This attribute is inherited setAttributeValue(TT("Frequency"), 1000.0); setProcessMethod(processAudio); setCalculateMethod(calculateValue); } TTLowpassButterworth3::~TTLowpassButterworth3() { ; } TTErr TTLowpassButterworth3::updateMaxNumChannels(const TTValue& oldMaxNumChannels) { mX1.resize(maxNumChannels); mX2.resize(maxNumChannels); mX3.resize(maxNumChannels); mY1.resize(maxNumChannels); mY2.resize(maxNumChannels); mY3.resize(maxNumChannels); Clear(); return kTTErrNone; } TTErr TTLowpassButterworth3::updateSr() { TTValue v(mFrequency); return setFrequency(v); } TTErr TTLowpassButterworth3::Clear() { mX1.assign(maxNumChannels, 0.0); mX2.assign(maxNumChannels, 0.0); mX3.assign(maxNumChannels, 0.0); mY1.assign(maxNumChannels, 0.0); mY2.assign(maxNumChannels, 0.0); mY3.assign(maxNumChannels, 0.0); return kTTErrNone; } TTErr TTLowpassButterworth3::setFrequency(const TTValue& newValue) { mFrequency = newValue; mRadians = kTTTwoPi*mFrequency; mRadiansSquared = mRadians * mRadians; mRadiansCubic = mRadiansSquared * mRadians; mK = mRadians/tan(kTTPi*mFrequency/sr); // kTTTwoPi*frequency/tan(kTTPi*frequency/sr); mKSquared = mK * mK; mKCubic = mKSquared * mK; calculateCoefficients(); return kTTErrNone; } void TTLowpassButterworth3::calculateCoefficients() //TODO: with a little bit of thinking, this can be optimized { TTFloat64 temp1; temp1 = (mRadiansCubic + mKCubic + 2*mRadiansSquared*mK + 2*mRadians*mKSquared); mA0 = (mRadiansCubic) / temp1; mA1 = (3*mRadiansCubic) / temp1; mA2 = mA1; //mA2 = (3*mRadiansCubic) / temp1; mA3 = mA0; //mA3 = (mRadiansCubic) / temp1; mB1 = (3*mRadiansCubic - 3*mKCubic + 2*mRadiansSquared*mK - 2*mRadians*mKSquared) / temp1; mB2 = (3*mRadiansCubic + 3*mKCubic - 2*mRadiansSquared*mK - 2*mRadians*mKSquared) / temp1; mB3 = (mRadiansCubic - mKCubic - 2*mRadiansSquared*mK + 2*mRadians*mKSquared) / temp1; } inline TTErr TTLowpassButterworth3::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt channel) { //y = TTAntiDenormal(mA0*x + mA1*mX1[channel] + mA2*mX2[channel] + mA3*mX3[channel] - mB1*mY1[channel] - mB2*mY2[channel] -mB3*mY3[channel]); // since mA2 = mA1 and mA3 = mA0, we can write y = mA0*(x +mX3[channel]) + mA1*(mX1[channel] + mX2[channel]) - mB1*mY1[channel] - mB2*mY2[channel] -mB3*mY3[channel]; TTZeroDenormal(y); mX3[channel] = mX2[channel]; mX2[channel] = mX1[channel]; mX1[channel] = x; mY3[channel] = mY2[channel]; mY2[channel] = mY1[channel]; mY1[channel] = y; return kTTErrNone; } TTErr TTLowpassButterworth3::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); } <|endoftext|>
<commit_before>/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/net_http.h" #include "config/timing.h" #include "config/sdcard.h" #include "config/filesystem.h" #include "MyHttpConnection.h" using namespace stm32plus; using namespace stm32plus::net; /** * This demo brings together a number of the stm32plus components, namely * the network stack, the RTC, the SD card and the FAT16/32 filesystem * to build a simple web server that listens on port 80. * * Files are served starting from the root directory on the SD card. HTTP GET * is the only action supported. A number of content-type mappings are supported * and may be extended by amending MyHttpConnection.h accordingly. The client URI * must match a physical file on the card. e.g. http://yourserver/foo/bar.html * expects to find a file called /foo/bar.html on the SD card. The server supports * HTTP/1.1 persistent connections. * * +----------------------------+ * APPLICATION: | DhcpClient | * +------+---------------------+ * TRANSPORT: | Tcp | Udp | Icmp | * +-----++---------------------+ * NETWORK | DefaultIp | Arp | * +-----+----------------+-----+ * DATALINK: | DefaultRmiiInterface | Mac | * +----------------------+-----+ * PHYSICAL: | DP83848C | * +----------------------------+ * * This example is only compatible with the F4 because it requires the SDIO * peripheral to be able to talk to the SD card. * * Tested on devices: * STM32F407VGT6 */ class NetHttpServerTest { public: /** * Types that define the network stack */ typedef PhysicalLayer<DP83848C> MyPhysicalLayer; typedef DatalinkLayer<MyPhysicalLayer,DefaultRmiiInterface,Mac> MyDatalinkLayer; typedef NetworkLayer<MyDatalinkLayer,DefaultIp,Arp> MyNetworkLayer; typedef TransportLayer<MyNetworkLayer,Icmp,Udp,Tcp> MyTransportLayer; typedef ApplicationLayer<MyTransportLayer,DhcpClient> MyApplicationLayer; typedef NetworkStack<MyApplicationLayer> MyNetworkStack; /* * The network stack, sdio and filesystem objects that we'll need for this demo */ MyNetworkStack *_net; SdioDmaSdCard *_sdcard; FileSystem *_fs; RtcTimeProvider *_timeProvider; /* * Run the test */ void run() { // declare the RTC that that stack requires. it's used for cache timeouts, DHCP lease expiry // and such like so it does not have to be calibrated for accuracy. A few seconds here or there // over a 24 hour period isn't going to make any difference. Start it ticking at zero which is // some way back in 2000 but that doesn't matter to us Rtc<RtcLsiClockFeature<Rtc32kHzLsiFrequencyProvider>,RtcSecondInterruptFeature> rtc; rtc.setTick(0); // create the RTC time provider for the file system. if writes are made to the card then // this provider will be used to timestamp them. _timeProvider=new RtcTimeProvider(rtc); // declare the SD card and check for error. the card must be inserted at this point _sdcard=new SdioDmaSdCard; if(errorProvider.hasError()) error(); // initialise a file system for the card. FAT16 and FAT32 are supported. the card must // already be formatted. if(!FileSystem::getInstance(*_sdcard,*_timeProvider,_fs)) error(); // declare an instance of the network stack MyNetworkStack::Parameters params; _net=new MyNetworkStack; // the stack requires the RTC params.base_rtc=&rtc; // It's nice to give the DHCP client a host name because then it'll show up in DHCP // 'active leases' page. In a home router this is often called 'attached devices' params.dhcp_hostname="stm32plus"; // increase the number of connections per server params.tcp_maxConnectionsPerServer=10; // Initialise the stack. This will reset the PHY, initialise the MAC // and attempt to create a link to our link partner. Ensure your cable // is plugged in when you run this or be prepared to handle the error if(!_net->initialise(params)) error(); // start the ethernet MAC Tx/Rx DMA channels // this will trigger the DHCP transaction if(!_net->startup()) error(); // create an HTTP server on port 80 (our HTTP operates over TCP (the most common case)) // Here we take advantage of the second template parameter to the TcpServer template to // pass in a user-defined type to the constructor of MyHttpConnection. We use it to pass // in a pointer to the filesystem object that holds the web documents. TcpServer<MyHttpConnection,FileSystem> *httpServer; if(!_net->tcpCreateServer(80,httpServer,_fs)) error(); // create an array to hold the active connections and configure it to // automatically receive connections as they arrive. It will also // automatically remove connections as they are closed. TcpConnectionArray<MyHttpConnection> connections(*httpServer); // now all the plumbing is in place, open up the server to start // accepting connection requests httpServer->start(); // loop forever servicing connections via their handleXXX() methods connections.wait(TcpWaitState::WRITE | TcpWaitState::READ | TcpWaitState::CLOSED,0); } void error() { for(;;); } }; /* * Main entry point */ int main() { // interrupts Nvic::initialise(); // set up SysTick at 1ms resolution MillisecondTimer::initialise(); NetHttpServerTest test; test.run(); // not reached return 0; } <commit_msg>explanation of supplied site<commit_after>/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/net_http.h" #include "config/timing.h" #include "config/sdcard.h" #include "config/filesystem.h" #include "MyHttpConnection.h" using namespace stm32plus; using namespace stm32plus::net; /** * This demo brings together a number of the stm32plus components, namely * the network stack, the RTC, the SD card and the FAT16/32 filesystem * to build a simple web server that listens on port 80. * * Files are served starting from the root directory on the SD card. HTTP GET * is the only action supported. A number of content-type mappings are supported * and may be extended by amending MyHttpConnection.h accordingly. The client URI * must match a physical file on the card. e.g. http://yourserver/foo/bar.html * expects to find a file called /foo/bar.html on the SD card. The server supports * HTTP/1.1 persistent connections. * * +----------------------------+ * APPLICATION: | DhcpClient | * +------+---------------------+ * TRANSPORT: | Tcp | Udp | Icmp | * +-----++---------------------+ * NETWORK | DefaultIp | Arp | * +-----+----------------+-----+ * DATALINK: | DefaultRmiiInterface | Mac | * +----------------------+-----+ * PHYSICAL: | DP83848C | * +----------------------------+ * * This example is only compatible with the F4 because it requires the SDIO * peripheral to be able to talk to the SD card. * * An example website is included in the 'www' subdirectory of this card. To use, * copy 'www' to the root directory of your SD card, run this example and then * retrieve it from your web browser at "http://<your-dhcp-ip>/www/index.html" * * Tested on devices: * STM32F407VGT6 */ class NetHttpServerTest { public: /** * Types that define the network stack */ typedef PhysicalLayer<DP83848C> MyPhysicalLayer; typedef DatalinkLayer<MyPhysicalLayer,DefaultRmiiInterface,Mac> MyDatalinkLayer; typedef NetworkLayer<MyDatalinkLayer,DefaultIp,Arp> MyNetworkLayer; typedef TransportLayer<MyNetworkLayer,Icmp,Udp,Tcp> MyTransportLayer; typedef ApplicationLayer<MyTransportLayer,DhcpClient> MyApplicationLayer; typedef NetworkStack<MyApplicationLayer> MyNetworkStack; /* * The network stack, sdio and filesystem objects that we'll need for this demo */ MyNetworkStack *_net; SdioDmaSdCard *_sdcard; FileSystem *_fs; RtcTimeProvider *_timeProvider; /* * Run the test */ void run() { // declare the RTC that that stack requires. it's used for cache timeouts, DHCP lease expiry // and such like so it does not have to be calibrated for accuracy. A few seconds here or there // over a 24 hour period isn't going to make any difference. Start it ticking at zero which is // some way back in 2000 but that doesn't matter to us Rtc<RtcLsiClockFeature<Rtc32kHzLsiFrequencyProvider>,RtcSecondInterruptFeature> rtc; rtc.setTick(0); // create the RTC time provider for the file system. if writes are made to the card then // this provider will be used to timestamp them. _timeProvider=new RtcTimeProvider(rtc); // declare the SD card and check for error. the card must be inserted at this point _sdcard=new SdioDmaSdCard; if(errorProvider.hasError()) error(); // initialise a file system for the card. FAT16 and FAT32 are supported. the card must // already be formatted. if(!FileSystem::getInstance(*_sdcard,*_timeProvider,_fs)) error(); // declare an instance of the network stack MyNetworkStack::Parameters params; _net=new MyNetworkStack; // the stack requires the RTC params.base_rtc=&rtc; // It's nice to give the DHCP client a host name because then it'll show up in DHCP // 'active leases' page. In a home router this is often called 'attached devices' params.dhcp_hostname="stm32plus"; // increase the number of connections per server params.tcp_maxConnectionsPerServer=10; // Initialise the stack. This will reset the PHY, initialise the MAC // and attempt to create a link to our link partner. Ensure your cable // is plugged in when you run this or be prepared to handle the error if(!_net->initialise(params)) error(); // start the ethernet MAC Tx/Rx DMA channels // this will trigger the DHCP transaction if(!_net->startup()) error(); // create an HTTP server on port 80 (our HTTP operates over TCP (the most common case)) // Here we take advantage of the second template parameter to the TcpServer template to // pass in a user-defined type to the constructor of MyHttpConnection. We use it to pass // in a pointer to the filesystem object that holds the web documents. TcpServer<MyHttpConnection,FileSystem> *httpServer; if(!_net->tcpCreateServer(80,httpServer,_fs)) error(); // create an array to hold the active connections and configure it to // automatically receive connections as they arrive. It will also // automatically remove connections as they are closed. TcpConnectionArray<MyHttpConnection> connections(*httpServer); // now all the plumbing is in place, open up the server to start // accepting connection requests httpServer->start(); // loop forever servicing connections via their handleXXX() methods connections.wait(TcpWaitState::WRITE | TcpWaitState::READ | TcpWaitState::CLOSED,0); } void error() { for(;;); } }; /* * Main entry point */ int main() { // interrupts Nvic::initialise(); // set up SysTick at 1ms resolution MillisecondTimer::initialise(); NetHttpServerTest test; test.run(); // not reached return 0; } <|endoftext|>
<commit_before>#include "ShowText.h" #include "loadLibrary.hpp" #include "GdiplusInitializer.hpp" #include "BitmapLockWrapper.hpp" #include <algorithm> #include <vector> #include <memory> #include <atlstr.h> #pragma comment(lib, "gdiplus.lib") namespace { void DrawChar(Gdiplus::Bitmap * canvas, WCHAR chr) { Gdiplus::Graphics g(canvas); Gdiplus::Font font(L"CI", canvas->GetWidth() / 2); Gdiplus::SolidBrush brush(Gdiplus::Color(0xFF, 0xFF, 0xFF)); Gdiplus::RectF rc(0, 0, canvas->GetWidth(), canvas->GetHeight()); Gdiplus::StringFormat format; g.DrawString(CString(chr), canvas->GetWidth(), &font, rc, &format, &brush); } void SetCharFromBitmap(int x, int y, int z, BitmapLockWrapper * lock) { if (x <= -LED_WIDTH || LED_WIDTH <= x){ return; } if (y <= -LED_WIDTH || LED_HEIGHT <= y){ return; } if (z < 0 || LED_DEPTH <= z){ return; } for (int xx = 0; xx < LED_WIDTH; ++xx){ for (int yy = 0; yy < LED_WIDTH; ++yy){ int x2 = x + xx; int y2 = y + yy; byte v = *(static_cast<byte*>(lock->Get()->Scan0) + xx * 3 + yy * lock->Get()->Stride); SetLed(x2, y2, z, v); } } } } void Initialize(const char * dll, int argc, const char* argv[]) { static GdiplusInitializer init; loadLibrary(dll); if (1 < argc){ SetUrl(argv[1]); } } void ShowText(CStringW const & text) { typedef std::shared_ptr<Gdiplus::Bitmap> BitmapPtr; typedef std::shared_ptr<BitmapLockWrapper> LockPtr; auto imgs = [text](){ std::vector<std::pair<BitmapPtr, LockPtr>> dst; for (int i = 0; i < text.GetLength(); ++i){ BitmapPtr bmp = std::make_shared<Gdiplus::Bitmap>(LED_WIDTH, LED_WIDTH, PixelFormat24bppRGB); DrawChar(bmp.get(), text[i]); LockPtr lock = std::make_shared<BitmapLockWrapper>(bmp.get()); dst.push_back({ bmp, lock }); } return dst; }(); int limit = -(LED_WIDTH * imgs.size()); for (int y = LED_HEIGHT; limit < y; --y){ Clear(); for (size_t i = 0; i < imgs.size(); ++i){ int y2 = y + i * LED_WIDTH; SetCharFromBitmap(0, y2, 0, imgs[i].second.get()); } Show(); Wait(30); } } <commit_msg>ShowText.cpp is complete<commit_after>#include "ShowText.h" #include "loadLibrary.hpp" #include "GdiplusInitializer.hpp" #include "BitmapLockWrapper.hpp" #include <vector> #include <memory> # include <random> #pragma comment(lib, "gdiplus.lib") namespace { int newColor() { auto gem = [](double a) -> double { while (6 < a) a -= 6.0; if (a < 1) return a; if (a < 3) return 1; if (a < 4) return 4 - a; return 0; }; std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<double> score(0, 6.0); double a = score(mt); byte r = static_cast<byte>(gem(a + 0) * 255); byte g = static_cast<byte>(gem(a + 2) * 255); byte b = static_cast<byte>(gem(a + 4) * 255); return r * 0x10000 + g * 0x100 + b; } int modBrightness(int rgb, byte v) { byte r = ((rgb >> 16) & 0xFF) * v / 0xFF; byte g = ((rgb >> 8) & 0xFF) * v / 0xFF; byte b = ((rgb >> 0) & 0xFF) * v / 0xFF; return r * 0x10000 + g * 0x100 + b; } void DrawChar(Gdiplus::Bitmap * canvas, WCHAR chr) { Gdiplus::Graphics g(canvas); Gdiplus::Font font(L"CI", canvas->GetWidth() / 2); Gdiplus::SolidBrush brush(Gdiplus::Color(0xFF, 0xFF, 0xFF)); Gdiplus::RectF rc(0, 0, canvas->GetWidth(), canvas->GetHeight()); Gdiplus::StringFormat format; g.DrawString(CString(chr), canvas->GetWidth(), &font, rc, &format, &brush); } void SetCharFromBitmap(int x, int y, int z, int rgb, BitmapLockWrapper * lock) { if (x <= -LED_WIDTH || LED_WIDTH <= x){ return; } if (y <= -LED_WIDTH || LED_HEIGHT <= y){ return; } if (z < 0 || LED_DEPTH <= z){ return; } for (int xx = 0; xx < LED_WIDTH; ++xx){ for (int yy = 0; yy < LED_WIDTH; ++yy){ int x2 = x + xx; int y2 = y + yy; byte v = *(static_cast<byte*>(lock->Get()->Scan0) + xx * 3 + yy * lock->Get()->Stride); SetLed(x2, y2, z, modBrightness(rgb, v)); } } } } void Initialize(const char * dll, int argc, const char* argv[]) { static GdiplusInitializer init; loadLibrary(dll); if (1 < argc){ SetUrl(argv[1]); } } void ShowText(CStringW const & text) { typedef std::shared_ptr<Gdiplus::Bitmap> BitmapPtr; typedef std::shared_ptr<BitmapLockWrapper> LockPtr; auto imgs = [text](){ std::vector<std::pair<BitmapPtr, LockPtr>> dst; for (int i = 0; i < text.GetLength(); ++i){ BitmapPtr bmp = std::make_shared<Gdiplus::Bitmap>(LED_WIDTH, LED_WIDTH, PixelFormat24bppRGB); DrawChar(bmp.get(), text[i]); LockPtr lock = std::make_shared<BitmapLockWrapper>(bmp.get()); dst.push_back({ bmp, lock }); } return dst; }(); int rgb = newColor(); int limit = -(LED_WIDTH * imgs.size()); for (int y = LED_HEIGHT; limit < y; --y){ Clear(); for (size_t i = 0; i < imgs.size(); ++i){ int y2 = y + i * LED_WIDTH; SetCharFromBitmap(0, y2, rand() % 2, rgb, imgs[i].second.get()); } Show(); Wait(30); } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of duihome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <cmath> #include <QTimer> #include <QGraphicsSceneMouseEvent> #include "mainwindow.h" #include <QApplication> #include <QX11Info> #include <QPainter> #include <DuiScalableImage> #include <DuiCancelEvent> #include <DuiSceneManager> #include "switcherbuttonview.h" #include "switcherbutton.h" #ifdef Q_WS_X11 bool SwitcherButtonView::badMatchOccurred = false; #endif SwitcherButtonView::SwitcherButtonView(SwitcherButton *button) : DuiWidgetView(button), controller(button), xWindowPixmap(0), xWindowPixmapDamage(0) { // Configure timers windowCloseTimer.setSingleShot(true); connect(&windowCloseTimer, SIGNAL(timeout()), this, SLOT(resetState())); // Connect to the windowVisibilityChanged signal of the HomeApplication to get information about window visiblity changes connect(qApp, SIGNAL(windowVisibilityChanged(Window)), this, SLOT(windowVisibilityChanged(Window))); // Show interest in X pixmap change signals connect(qApp, SIGNAL(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)), this, SLOT(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &))); } SwitcherButtonView::~SwitcherButtonView() { #ifdef Q_WS_X11 if (xWindowPixmapDamage != 0) { // Unregister the pixmap from XDamage events X11Wrapper::XDamageDestroy(QX11Info::display(), xWindowPixmapDamage); } if (xWindowPixmap != 0) { // Dereference the old pixmap ID X11Wrapper::XFreePixmap(QX11Info::display(), xWindowPixmap); } #endif } void SwitcherButtonView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { // Store the painter state painter->save(); QPoint pos = style()->iconPosition().toPoint(); QSize size = style()->iconSize(); QRect target(pos, size); // Do the actual drawing backendSpecificDrawBackground(painter, option, target); // Restore the painter state painter->restore(); } void SwitcherButtonView::backendSpecificDrawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option, const QRect& target) const { Q_UNUSED(painter); Q_UNUSED(option); Q_UNUSED(target); } void SwitcherButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *) const { // Store the painter state painter->save(); // Draw the container const DuiScalableImage *container = style()->containerImage(); if (container != NULL) { container->draw(QRect(QPoint(0, 0), size().toSize()), painter); } // Draw text const QString text(controller->text()); if (!text.isEmpty() && controller->isTextVisible()) { QFont font = style()->font(); painter->setFont(font); painter->setPen(style()->textColor()); painter->setOpacity(style()->textOpacity()); painter->drawText(titleRect(), Qt::AlignLeft | Qt::ElideRight, text); } // Draw a close image at top right corner, at the moment it is assumed that // the close button is square!! if (style()->closeImage()) { painter->setOpacity(1.0f); QRectF title = titleRect(); QRectF rect = buttonRect(); rect.setTopLeft(QPointF(rect.right() - title.height(), title.y())); rect.setWidth(title.height()); rect.setHeight(title.height()); style()->closeImage()->draw(rect.x(), rect.y(), rect.width(), rect.height(), painter); } // Restore the painter state painter->restore(); } QRectF SwitcherButtonView::buttonRect() const { QRectF rect(QPointF(), size()); return rect; } QRectF SwitcherButtonView::titleRect() const { QRectF rect = buttonRect(); QRectF close = closeRect(); QFontMetrics fm(style()->font()); rect.setTopLeft(rect.topLeft() - QPointF(0, fm.height())); rect.setBottomRight(rect.topRight() + QPointF(-(close.width() + 2 * style()->textMarginLeft()), fm.height())); rect.translate(style()->textMarginLeft(), -style()->textMarginBottom()); return rect; } QRectF SwitcherButtonView::closeRect() const { QRectF rect = buttonRect(); if (style()->closeImage()) { const QPixmap* closeImage = style()->closeImage()->pixmap(); // calculate the rect for the close button alone rect.setBottomLeft(rect.topRight() - QPointF(closeImage->width() * 0.5f, 0)); rect.setTopRight(rect.topRight() - QPointF(0, closeImage->height() * 0.5f)); rect.setWidth(closeImage->width()); rect.setHeight(closeImage->height()); } else { // HACK: specify a fake 1x1 rectagle at the top-right corner of the button rect.setBottomLeft(rect.topRight() - QPointF(1, -1)); } return rect; } QRectF SwitcherButtonView::boundingRect() const { return buttonRect().united(closeRect()); } void SwitcherButtonView::applyStyle() { DuiWidgetView::applyStyle(); updateThumbnail(); } void SwitcherButtonView::setupModel() { DuiWidgetView::setupModel(); if (model()->xWindow() != 0) { updateXWindowPixmap(); updateThumbnail(); } updateViewMode(); } void SwitcherButtonView::updateViewMode() { switch (model()->viewMode()) { case SwitcherButtonModel::Small: style().setModeSmall(); break; case SwitcherButtonModel::Medium: style().setModeMedium(); break; case SwitcherButtonModel::Large: style().setModeLarge(); break; case SwitcherButtonModel::UnSpecified: break; } // When the style mode changes, the style is not automatically applied -> call it explicitly applyStyle(); } void SwitcherButtonView::updateData(const QList<const char *>& modifications) { DuiWidgetView::updateData(modifications); const char *member; foreach(member, modifications) { if (member == SwitcherButtonModel::XWindow && model()->xWindow() != 0) { updateXWindowPixmap(); updateThumbnail(); } if (member == SwitcherButtonModel::ViewMode) { updateViewMode(); } } } void SwitcherButtonView::resetState() { controller->setVisible(true); controller->prepareGeometryChange(); } void SwitcherButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (!model()->down()) { model()->setDown(true); if (closeRect().contains(event->pos())) { model()->setPressed(SwitcherButtonModel::ClosePressed); } else if (buttonRect().contains(event->pos())) { model()->setPressed(SwitcherButtonModel::ButtonPressed); } else { model()->setPressed(SwitcherButtonModel::NonePressed); } event->accept(); } } void SwitcherButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (model()->down()) { model()->setDown(false); if (closeRect().contains(event->pos())) { if (model()->pressed() == SwitcherButtonModel::ClosePressed) { // Close icon clicked, send the close signal and hide // the button controller->close(); controller->setVisible(false); windowCloseTimer.start(5000); } } else if (buttonRect().contains(event->pos())) { if (model()->pressed() == SwitcherButtonModel::ButtonPressed) { // Switcher button clicked, let the controller know that // the window should be brought to front model()->click(); controller->switchToWindow(); update(); } } model()->setPressed(SwitcherButtonModel::NonePressed); event->accept(); } } void SwitcherButtonView::cancelEvent(DuiCancelEvent *event) { if (model()->down()) { model()->setDown(false); model()->setPressed(SwitcherButtonModel::NonePressed); event->accept(); } } void SwitcherButtonView::updateXWindowPixmap() { #ifdef Q_WS_X11 if (xWindowPixmapDamage != 0) { // Unregister the old pixmap from XDamage events X11Wrapper::XDamageDestroy(QX11Info::display(), xWindowPixmapDamage); xWindowPixmapDamage = 0; } if (xWindowPixmap != 0) { // Dereference the old pixmap ID X11Wrapper::XFreePixmap(QX11Info::display(), xWindowPixmap); xWindowPixmap = 0; } // It is possible that the window is not redirected so check for errors XErrorHandler errh = X11Wrapper::XSetErrorHandler(handleXError); // Get the pixmap ID of the X window xWindowPixmap = X11Wrapper::XCompositeNameWindowPixmap(QX11Info::display(), model()->xWindow()); X11Wrapper::XSync(QX11Info::display(), FALSE); // If a BadMatch error occurred set the window pixmap ID to 0 if (badMatchOccurred) { xWindowPixmap = 0; badMatchOccurred = false; } // Reset the error handler X11Wrapper::XSetErrorHandler(errh); if (xWindowPixmap != 0) { // Register the pixmap for XDamage events xWindowPixmapDamage = X11Wrapper::XDamageCreate(QX11Info::display(), xWindowPixmap, XDamageReportNonEmpty); backendSpecificUpdateXWindowPixmap(); } #endif } void SwitcherButtonView::backendSpecificUpdateXWindowPixmap() { } void SwitcherButtonView::updateThumbnail() { // Redraw update(); } #ifdef Q_WS_X11 int SwitcherButtonView::handleXError(Display *, XErrorEvent *event) { if (event->error_code == BadMatch) { badMatchOccurred = true; } return 0; } #endif void SwitcherButtonView::windowVisibilityChanged(Window window) { if (window == model()->xWindow()) { updateXWindowPixmap(); updateThumbnail(); } } void SwitcherButtonView::damageEvent(Qt::HANDLE &damage, short &x, short &y, unsigned short &width, unsigned short &height) { Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(width); Q_UNUSED(height); if (xWindowPixmapDamage == damage) { update(); } } DUI_REGISTER_VIEW_NEW(SwitcherButtonView, SwitcherButton) <commit_msg>Revert "Changes: The switcher buttons do not need to be rotated any more"<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of duihome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <cmath> #include <QTimer> #include <QGraphicsSceneMouseEvent> #include "mainwindow.h" #include <QApplication> #include <QX11Info> #include <QPainter> #include <DuiScalableImage> #include <DuiCancelEvent> #include <DuiSceneManager> #include "switcherbuttonview.h" #include "switcherbutton.h" #ifdef Q_WS_X11 bool SwitcherButtonView::badMatchOccurred = false; #endif SwitcherButtonView::SwitcherButtonView(SwitcherButton *button) : DuiWidgetView(button), controller(button), xWindowPixmap(0), xWindowPixmapDamage(0) { // Configure timers windowCloseTimer.setSingleShot(true); connect(&windowCloseTimer, SIGNAL(timeout()), this, SLOT(resetState())); // Connect to the windowVisibilityChanged signal of the HomeApplication to get information about window visiblity changes connect(qApp, SIGNAL(windowVisibilityChanged(Window)), this, SLOT(windowVisibilityChanged(Window))); // Show interest in X pixmap change signals connect(qApp, SIGNAL(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)), this, SLOT(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &))); } SwitcherButtonView::~SwitcherButtonView() { #ifdef Q_WS_X11 if (xWindowPixmapDamage != 0) { // Unregister the pixmap from XDamage events X11Wrapper::XDamageDestroy(QX11Info::display(), xWindowPixmapDamage); } if (xWindowPixmap != 0) { // Dereference the old pixmap ID X11Wrapper::XFreePixmap(QX11Info::display(), xWindowPixmap); } #endif } void SwitcherButtonView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { // Store the painter state painter->save(); // Rotate the thumbnails and adjust their size if the screen // has been rotated DuiSceneManager *manager = MainWindow::instance()->sceneManager(); QPoint pos = style()->iconPosition().toPoint(); QSize size = style()->iconSize(); if (manager->orientation() == Dui::Portrait) { size.transpose(); } switch (manager->orientationAngle()) { case Dui::Angle90: pos -= QPoint(size.width(), 0); break; case Dui::Angle180: pos -= QPoint(size.width(), size.height()); break; case Dui::Angle270: pos -= QPoint(0, size.height()); break; default: break; } painter->rotate(-manager->orientationAngle()); QRect target(pos, size); // Do the actual drawing backendSpecificDrawBackground(painter, option, target); // Restore the painter state painter->restore(); } void SwitcherButtonView::backendSpecificDrawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option, const QRect& target) const { Q_UNUSED(painter); Q_UNUSED(option); Q_UNUSED(target); } void SwitcherButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *) const { // Store the painter state painter->save(); // Draw the container const DuiScalableImage *container = style()->containerImage(); if (container != NULL) { container->draw(QRect(QPoint(0, 0), size().toSize()), painter); } // Draw text const QString text(controller->text()); if (!text.isEmpty() && controller->isTextVisible()) { QFont font = style()->font(); painter->setFont(font); painter->setPen(style()->textColor()); painter->setOpacity(style()->textOpacity()); painter->drawText(titleRect(), Qt::AlignLeft | Qt::ElideRight, text); } // Draw a close image at top right corner, at the moment it is assumed that // the close button is square!! if (style()->closeImage()) { painter->setOpacity(1.0f); QRectF title = titleRect(); QRectF rect = buttonRect(); rect.setTopLeft(QPointF(rect.right() - title.height(), title.y())); rect.setWidth(title.height()); rect.setHeight(title.height()); style()->closeImage()->draw(rect.x(), rect.y(), rect.width(), rect.height(), painter); } // Restore the painter state painter->restore(); } QRectF SwitcherButtonView::buttonRect() const { QRectF rect(QPointF(), size()); return rect; } QRectF SwitcherButtonView::titleRect() const { QRectF rect = buttonRect(); QRectF close = closeRect(); QFontMetrics fm(style()->font()); rect.setTopLeft(rect.topLeft() - QPointF(0, fm.height())); rect.setBottomRight(rect.topRight() + QPointF(-(close.width() + 2 * style()->textMarginLeft()), fm.height())); rect.translate(style()->textMarginLeft(), -style()->textMarginBottom()); return rect; } QRectF SwitcherButtonView::closeRect() const { QRectF rect = buttonRect(); if (style()->closeImage()) { const QPixmap* closeImage = style()->closeImage()->pixmap(); // calculate the rect for the close button alone rect.setBottomLeft(rect.topRight() - QPointF(closeImage->width() * 0.5f, 0)); rect.setTopRight(rect.topRight() - QPointF(0, closeImage->height() * 0.5f)); rect.setWidth(closeImage->width()); rect.setHeight(closeImage->height()); } else { // HACK: specify a fake 1x1 rectagle at the top-right corner of the button rect.setBottomLeft(rect.topRight() - QPointF(1, -1)); } return rect; } QRectF SwitcherButtonView::boundingRect() const { return buttonRect().united(closeRect()); } void SwitcherButtonView::applyStyle() { DuiWidgetView::applyStyle(); updateThumbnail(); } void SwitcherButtonView::setupModel() { DuiWidgetView::setupModel(); if (model()->xWindow() != 0) { updateXWindowPixmap(); updateThumbnail(); } updateViewMode(); } void SwitcherButtonView::updateViewMode() { switch (model()->viewMode()) { case SwitcherButtonModel::Small: style().setModeSmall(); break; case SwitcherButtonModel::Medium: style().setModeMedium(); break; case SwitcherButtonModel::Large: style().setModeLarge(); break; case SwitcherButtonModel::UnSpecified: break; } // When the style mode changes, the style is not automatically applied -> call it explicitly applyStyle(); } void SwitcherButtonView::updateData(const QList<const char *>& modifications) { DuiWidgetView::updateData(modifications); const char *member; foreach(member, modifications) { if (member == SwitcherButtonModel::XWindow && model()->xWindow() != 0) { updateXWindowPixmap(); updateThumbnail(); } if (member == SwitcherButtonModel::ViewMode) { updateViewMode(); } } } void SwitcherButtonView::resetState() { controller->setVisible(true); controller->prepareGeometryChange(); } void SwitcherButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (!model()->down()) { model()->setDown(true); if (closeRect().contains(event->pos())) { model()->setPressed(SwitcherButtonModel::ClosePressed); } else if (buttonRect().contains(event->pos())) { model()->setPressed(SwitcherButtonModel::ButtonPressed); } else { model()->setPressed(SwitcherButtonModel::NonePressed); } event->accept(); } } void SwitcherButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (model()->down()) { model()->setDown(false); if (closeRect().contains(event->pos())) { if (model()->pressed() == SwitcherButtonModel::ClosePressed) { // Close icon clicked, send the close signal and hide // the button controller->close(); controller->setVisible(false); windowCloseTimer.start(5000); } } else if (buttonRect().contains(event->pos())) { if (model()->pressed() == SwitcherButtonModel::ButtonPressed) { // Switcher button clicked, let the controller know that // the window should be brought to front model()->click(); controller->switchToWindow(); update(); } } model()->setPressed(SwitcherButtonModel::NonePressed); event->accept(); } } void SwitcherButtonView::cancelEvent(DuiCancelEvent *event) { if (model()->down()) { model()->setDown(false); model()->setPressed(SwitcherButtonModel::NonePressed); event->accept(); } } void SwitcherButtonView::updateXWindowPixmap() { #ifdef Q_WS_X11 if (xWindowPixmapDamage != 0) { // Unregister the old pixmap from XDamage events X11Wrapper::XDamageDestroy(QX11Info::display(), xWindowPixmapDamage); xWindowPixmapDamage = 0; } if (xWindowPixmap != 0) { // Dereference the old pixmap ID X11Wrapper::XFreePixmap(QX11Info::display(), xWindowPixmap); xWindowPixmap = 0; } // It is possible that the window is not redirected so check for errors XErrorHandler errh = X11Wrapper::XSetErrorHandler(handleXError); // Get the pixmap ID of the X window xWindowPixmap = X11Wrapper::XCompositeNameWindowPixmap(QX11Info::display(), model()->xWindow()); X11Wrapper::XSync(QX11Info::display(), FALSE); // If a BadMatch error occurred set the window pixmap ID to 0 if (badMatchOccurred) { xWindowPixmap = 0; badMatchOccurred = false; } // Reset the error handler X11Wrapper::XSetErrorHandler(errh); if (xWindowPixmap != 0) { // Register the pixmap for XDamage events xWindowPixmapDamage = X11Wrapper::XDamageCreate(QX11Info::display(), xWindowPixmap, XDamageReportNonEmpty); backendSpecificUpdateXWindowPixmap(); } #endif } void SwitcherButtonView::backendSpecificUpdateXWindowPixmap() { } void SwitcherButtonView::updateThumbnail() { // Redraw update(); } #ifdef Q_WS_X11 int SwitcherButtonView::handleXError(Display *, XErrorEvent *event) { if (event->error_code == BadMatch) { badMatchOccurred = true; } return 0; } #endif void SwitcherButtonView::windowVisibilityChanged(Window window) { if (window == model()->xWindow()) { updateXWindowPixmap(); updateThumbnail(); } } void SwitcherButtonView::damageEvent(Qt::HANDLE &damage, short &x, short &y, unsigned short &width, unsigned short &height) { Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(width); Q_UNUSED(height); if (xWindowPixmapDamage == damage) { update(); } } DUI_REGISTER_VIEW_NEW(SwitcherButtonView, SwitcherButton) <|endoftext|>
<commit_before>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/timer/Timer.h> #include <stingraykit/diagnostics/ExecutorsProfiler.h> #include <stingraykit/function/CancellableFunction.h> #include <stingraykit/function/bind.h> #include <stingraykit/function/function_name_getter.h> #include <stingraykit/log/Logger.h> #include <stingraykit/time/ElapsedTime.h> #include <stingraykit/FunctionToken.h> #include <stingraykit/TaskLifeToken.h> #include <list> #include <map> namespace stingray { class Timer::CallbackQueue { typedef std::list<CallbackInfoPtr> ContainerInternal; typedef std::map<TimeDuration, ContainerInternal> Container; private: Mutex _mutex; Container _container; public: typedef ContainerInternal::iterator iterator; inline Mutex& Sync() { return _mutex; } inline bool IsEmpty() const { MutexLock l(_mutex); return _container.empty(); } CallbackInfoPtr Top() const; void Push(const CallbackInfoPtr& ci); void Erase(const CallbackInfoPtr& ci); CallbackInfoPtr Pop(); }; class Timer::CallbackInfo { STINGRAYKIT_NONCOPYABLE(CallbackInfo); typedef function<void()> FuncT; typedef CallbackQueue::iterator QueueIterator; private: FuncT _func; TimeDuration _timeToTrigger; optional<TimeDuration> _period; TaskLifeToken _token; bool _erased; optional<QueueIterator> _iterator; private: friend class CallbackQueue; void SetIterator(const optional<QueueIterator>& it) { _iterator = it; } const optional<QueueIterator>& GetIterator() const { return _iterator; } void SetErased() { _erased = true; } bool IsErased() const { return _erased; } public: CallbackInfo(const FuncT& func, const TimeDuration& timeToTrigger, const optional<TimeDuration>& period, const TaskLifeToken& token) : _func(func), _timeToTrigger(timeToTrigger), _period(period), _token(token), _erased(false) { } const FuncT& GetFunc() const { return _func; } FutureExecutionTester GetExecutionTester() const { return _token.GetExecutionTester(); } void Release() { _token.Release(); } bool IsPeriodic() const { return _period.is_initialized(); } void Restart(const TimeDuration& currentTime) { STINGRAYKIT_CHECK(_period, "CallbackInfo::Restart internal error: _period is set!"); _timeToTrigger = currentTime + *_period; } TimeDuration GetTimeToTrigger() const { return _timeToTrigger; } }; Timer::CallbackInfoPtr Timer::CallbackQueue::Top() const { MutexLock l(_mutex); if (!_container.empty()) { const ContainerInternal& listForTop = _container.begin()->second; STINGRAYKIT_CHECK(!listForTop.empty(), "try to get callback from empty list"); return listForTop.front(); } else return null; } void Timer::CallbackQueue::Push(const CallbackInfoPtr& ci) { MutexLock l(_mutex); if (ci->IsErased()) return; ContainerInternal& listToInsert = _container[ci->GetTimeToTrigger()]; ci->SetIterator(listToInsert.insert(listToInsert.end(), ci)); } void Timer::CallbackQueue::Erase(const CallbackInfoPtr& ci) { MutexLock l(_mutex); ci->SetErased(); const optional<iterator>& it = ci->GetIterator(); if (!it) return; TimeDuration keyToErase = ci->GetTimeToTrigger(); ContainerInternal& listToErase = _container[keyToErase]; listToErase.erase(*it); if (listToErase.empty()) _container.erase(keyToErase); ci->SetIterator(null); } Timer::CallbackInfoPtr Timer::CallbackQueue::Pop() { MutexLock l(_mutex); STINGRAYKIT_CHECK(!_container.empty(), "popping callback from empty map"); ContainerInternal& listToPop = _container.begin()->second; STINGRAYKIT_CHECK(!listToPop.empty(), "popping callback from empty list"); CallbackInfoPtr ci = listToPop.front(); listToPop.pop_front(); if (listToPop.empty()) _container.erase(ci->GetTimeToTrigger()); ci->SetIterator(null); return ci; } STINGRAYKIT_DEFINE_NAMED_LOGGER(Timer); Timer::Timer(const std::string& timerName, const ExceptionHandler& exceptionHandler, bool profileCalls) : _timerName(timerName), _exceptionHandler(exceptionHandler), _profileCalls(profileCalls), _alive(true), _queue(make_shared<CallbackQueue>()), _worker(make_shared<Thread>(timerName, bind(&Timer::ThreadFunc, this, not_using(_1)))) { } Timer::~Timer() { { MutexLock l(_queue->Sync()); _alive = false; _cond.Broadcast(); } _worker.reset(); MutexLock l(_queue->Sync()); while(!_queue->IsEmpty()) { CallbackInfoPtr top = _queue->Pop(); MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); top.reset(); if (guard) { s_logger.Warning() << "killing timer " << _timerName << " which still has some functions to execute"; break; } } } Token Timer::SetTimeout(const TimeDuration& timeout, const function<void()>& func) { MutexLock l(_queue->Sync()); CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, null, TaskLifeToken()); _queue->Push(ci); _cond.Broadcast(); return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci)); } Token Timer::SetTimer(const TimeDuration& interval, const function<void()>& func) { return SetTimer(interval, interval, func); } Token Timer::SetTimer(const TimeDuration& timeout, const TimeDuration& interval, const function<void()>& func) { MutexLock l(_queue->Sync()); CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, interval, TaskLifeToken()); _queue->Push(ci); _cond.Broadcast(); return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci)); } void Timer::AddTask(const function<void()>& task, const FutureExecutionTester& tester) { MutexLock l(_queue->Sync()); CallbackInfoPtr ci = make_shared<CallbackInfo>(MakeCancellableFunction(task, tester), _monotonic.Elapsed(), null, TaskLifeToken::CreateDummyTaskToken()); _queue->Push(ci); _cond.Broadcast(); } void Timer::RemoveTask(const CallbackQueuePtr& queue, const CallbackInfoPtr& ci) { { MutexLock l(queue->Sync()); queue->Erase(ci); } ci->Release(); } std::string Timer::GetProfilerMessage(const function<void()>& func) { return StringBuilder() % get_function_name(func) % " in Timer '" % _timerName % "'"; } void Timer::ThreadFunc() { MutexLock l(_queue->Sync()); while (_alive) { if (_queue->IsEmpty()) { _cond.Wait(_queue->Sync()); continue; } CallbackInfoPtr top = _queue->Top(); if (top->GetTimeToTrigger() <= _monotonic.Elapsed()) { _queue->Pop(); { MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); if (!guard) { top.reset(); continue; } if (top->IsPeriodic()) top->Restart(_monotonic.Elapsed()); try { if (_profileCalls) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag()); (top->GetFunc())(); } else (top->GetFunc())(); } catch(const std::exception &ex) { _exceptionHandler(ex); } if (!top->IsPeriodic()) top.reset(); } if (top) _queue->Push(top); } else //top timer not triggered { const TimeDuration waitTime = top->GetTimeToTrigger() - _monotonic.Elapsed(); top.reset(); if (waitTime > TimeDuration()) _cond.TimedWait(_queue->Sync(), waitTime); } } const TimeDuration currentTime = _monotonic.Elapsed(); while (!_queue->IsEmpty()) { CallbackInfoPtr top = _queue->Pop(); if (top->GetTimeToTrigger() <= currentTime) break; MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); if (!guard) { top.reset(); continue; } try { if (_profileCalls) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag()); (top->GetFunc())(); } else (top->GetFunc())(); } catch(const std::exception &ex) { _exceptionHandler(ex); } top.reset(); } } void Timer::DefaultExceptionHandler(const std::exception& ex) { s_logger.Error() << "Timer func exception: " << ex; } } <commit_msg>Timer: minor reduce of mutex locking time<commit_after>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/timer/Timer.h> #include <stingraykit/diagnostics/ExecutorsProfiler.h> #include <stingraykit/function/CancellableFunction.h> #include <stingraykit/function/bind.h> #include <stingraykit/function/function_name_getter.h> #include <stingraykit/log/Logger.h> #include <stingraykit/time/ElapsedTime.h> #include <stingraykit/FunctionToken.h> #include <stingraykit/TaskLifeToken.h> #include <list> #include <map> namespace stingray { class Timer::CallbackQueue { typedef std::list<CallbackInfoPtr> ContainerInternal; typedef std::map<TimeDuration, ContainerInternal> Container; private: Mutex _mutex; Container _container; public: typedef ContainerInternal::iterator iterator; inline Mutex& Sync() { return _mutex; } inline bool IsEmpty() const { MutexLock l(_mutex); return _container.empty(); } CallbackInfoPtr Top() const; void Push(const CallbackInfoPtr& ci); void Erase(const CallbackInfoPtr& ci); CallbackInfoPtr Pop(); }; class Timer::CallbackInfo { STINGRAYKIT_NONCOPYABLE(CallbackInfo); typedef function<void()> FuncT; typedef CallbackQueue::iterator QueueIterator; private: FuncT _func; TimeDuration _timeToTrigger; optional<TimeDuration> _period; TaskLifeToken _token; bool _erased; optional<QueueIterator> _iterator; private: friend class CallbackQueue; void SetIterator(const optional<QueueIterator>& it) { _iterator = it; } const optional<QueueIterator>& GetIterator() const { return _iterator; } void SetErased() { _erased = true; } bool IsErased() const { return _erased; } public: CallbackInfo(const FuncT& func, const TimeDuration& timeToTrigger, const optional<TimeDuration>& period, const TaskLifeToken& token) : _func(func), _timeToTrigger(timeToTrigger), _period(period), _token(token), _erased(false) { } const FuncT& GetFunc() const { return _func; } FutureExecutionTester GetExecutionTester() const { return _token.GetExecutionTester(); } void Release() { _token.Release(); } bool IsPeriodic() const { return _period.is_initialized(); } void Restart(const TimeDuration& currentTime) { STINGRAYKIT_CHECK(_period, "CallbackInfo::Restart internal error: _period is set!"); _timeToTrigger = currentTime + *_period; } TimeDuration GetTimeToTrigger() const { return _timeToTrigger; } }; Timer::CallbackInfoPtr Timer::CallbackQueue::Top() const { MutexLock l(_mutex); if (!_container.empty()) { const ContainerInternal& listForTop = _container.begin()->second; STINGRAYKIT_CHECK(!listForTop.empty(), "try to get callback from empty list"); return listForTop.front(); } else return null; } void Timer::CallbackQueue::Push(const CallbackInfoPtr& ci) { MutexLock l(_mutex); if (ci->IsErased()) return; ContainerInternal& listToInsert = _container[ci->GetTimeToTrigger()]; ci->SetIterator(listToInsert.insert(listToInsert.end(), ci)); } void Timer::CallbackQueue::Erase(const CallbackInfoPtr& ci) { MutexLock l(_mutex); ci->SetErased(); const optional<iterator>& it = ci->GetIterator(); if (!it) return; TimeDuration keyToErase = ci->GetTimeToTrigger(); ContainerInternal& listToErase = _container[keyToErase]; listToErase.erase(*it); if (listToErase.empty()) _container.erase(keyToErase); ci->SetIterator(null); } Timer::CallbackInfoPtr Timer::CallbackQueue::Pop() { MutexLock l(_mutex); STINGRAYKIT_CHECK(!_container.empty(), "popping callback from empty map"); ContainerInternal& listToPop = _container.begin()->second; STINGRAYKIT_CHECK(!listToPop.empty(), "popping callback from empty list"); CallbackInfoPtr ci = listToPop.front(); listToPop.pop_front(); if (listToPop.empty()) _container.erase(ci->GetTimeToTrigger()); ci->SetIterator(null); return ci; } STINGRAYKIT_DEFINE_NAMED_LOGGER(Timer); Timer::Timer(const std::string& timerName, const ExceptionHandler& exceptionHandler, bool profileCalls) : _timerName(timerName), _exceptionHandler(exceptionHandler), _profileCalls(profileCalls), _alive(true), _queue(make_shared<CallbackQueue>()), _worker(make_shared<Thread>(timerName, bind(&Timer::ThreadFunc, this, not_using(_1)))) { } Timer::~Timer() { { MutexLock l(_queue->Sync()); _alive = false; _cond.Broadcast(); } _worker.reset(); MutexLock l(_queue->Sync()); while(!_queue->IsEmpty()) { CallbackInfoPtr top = _queue->Pop(); MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); top.reset(); if (guard) { s_logger.Warning() << "killing timer " << _timerName << " which still has some functions to execute"; break; } } } Token Timer::SetTimeout(const TimeDuration& timeout, const function<void()>& func) { const CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, null, TaskLifeToken()); { MutexLock l(_queue->Sync()); _queue->Push(ci); _cond.Broadcast(); } return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci)); } Token Timer::SetTimer(const TimeDuration& interval, const function<void()>& func) { return SetTimer(interval, interval, func); } Token Timer::SetTimer(const TimeDuration& timeout, const TimeDuration& interval, const function<void()>& func) { const CallbackInfoPtr ci = make_shared<CallbackInfo>(func, _monotonic.Elapsed() + timeout, interval, TaskLifeToken()); { MutexLock l(_queue->Sync()); _queue->Push(ci); _cond.Broadcast(); } return MakeToken<FunctionToken>(bind(&Timer::RemoveTask, _queue, ci)); } void Timer::AddTask(const function<void()>& task, const FutureExecutionTester& tester) { const CallbackInfoPtr ci = make_shared<CallbackInfo>(MakeCancellableFunction(task, tester), _monotonic.Elapsed(), null, TaskLifeToken::CreateDummyTaskToken()); MutexLock l(_queue->Sync()); _queue->Push(ci); _cond.Broadcast(); } void Timer::RemoveTask(const CallbackQueuePtr& queue, const CallbackInfoPtr& ci) { { MutexLock l(queue->Sync()); queue->Erase(ci); } ci->Release(); } std::string Timer::GetProfilerMessage(const function<void()>& func) { return StringBuilder() % get_function_name(func) % " in Timer '" % _timerName % "'"; } void Timer::ThreadFunc() { MutexLock l(_queue->Sync()); while (_alive) { if (_queue->IsEmpty()) { _cond.Wait(_queue->Sync()); continue; } CallbackInfoPtr top = _queue->Top(); if (top->GetTimeToTrigger() <= _monotonic.Elapsed()) { _queue->Pop(); { MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); if (!guard) { top.reset(); continue; } if (top->IsPeriodic()) top->Restart(_monotonic.Elapsed()); try { if (_profileCalls) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag()); (top->GetFunc())(); } else (top->GetFunc())(); } catch(const std::exception &ex) { _exceptionHandler(ex); } if (!top->IsPeriodic()) top.reset(); } if (top) _queue->Push(top); } else //top timer not triggered { const TimeDuration waitTime = top->GetTimeToTrigger() - _monotonic.Elapsed(); top.reset(); if (waitTime > TimeDuration()) _cond.TimedWait(_queue->Sync(), waitTime); } } const TimeDuration currentTime = _monotonic.Elapsed(); while (!_queue->IsEmpty()) { CallbackInfoPtr top = _queue->Pop(); if (top->GetTimeToTrigger() <= currentTime) break; MutexUnlock ul(l); LocalExecutionGuard guard(top->GetExecutionTester()); if (!guard) { top.reset(); continue; } try { if (_profileCalls) { AsyncProfiler::Session profiler_session(ExecutorsProfiler::Instance().GetProfiler(), bind(&Timer::GetProfilerMessage, this, ref(top->GetFunc())), 10000, AsyncProfiler::Session::NameGetterTag()); (top->GetFunc())(); } else (top->GetFunc())(); } catch(const std::exception &ex) { _exceptionHandler(ex); } top.reset(); } } void Timer::DefaultExceptionHandler(const std::exception& ex) { s_logger.Error() << "Timer func exception: " << ex; } } <|endoftext|>
<commit_before>/** * Copyright 2013 Da Zheng * * This file is part of SA-GraphLib. * * SA-GraphLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SA-GraphLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SA-GraphLib. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include "graph.h" #include "common.h" #include "native_file.h" size_t read_edge_list(const std::string &file, std::vector<edge> &edge_vector) { native_file local_f(file); ssize_t file_size = local_f.get_size(); assert(file_size > (ssize_t) sizeof(edge)); assert(file_size % sizeof(edge) == 0); int num_edges = file_size / sizeof(edge); edge *edges = new edge[num_edges]; FILE *f = fopen(file.c_str(), "r"); if (f == NULL) { perror("fopen"); assert(0); } size_t ret = fread(edges, file_size, 1, f); assert(ret == 1); fclose(f); edge_vector.assign(edges, edges + num_edges); delete [] edges; return edge_vector.size(); } size_t read_edge_list_text(const std::string &file, std::vector<edge> &edges) { FILE *f = fopen(file.c_str(), "r"); if (f == NULL) { perror("fopen"); assert(0); } ssize_t read; size_t len = 0; char *line = NULL; while ((read = getline(&line, &len, f)) != -1) { if (line[read - 1] == '\n') line[read - 1] = 0; if (line[read - 2] == '\r') line[read - 2] = 0; if (line[0] == '#') continue; char *second = strchr(line, '\t'); assert(second); *second = 0; second++; if (!isnumeric(line) || !isnumeric(second)) { printf("%s\t%s\n", line, second); continue; } vertex_id_t from = atol(line); vertex_id_t to = atol(second); edges.push_back(edge(from, to)); } fclose(f); return edges.size(); } static struct comp_edge { bool operator() (const edge &e1, const edge &e2) { if (e1.get_from() == e2.get_from()) return e1.get_to() < e2.get_to(); else return e1.get_from() < e2.get_from(); } } edge_comparator; undirected_graph *undirected_graph::create(edge edges[], size_t num_edges) { undirected_graph *g = new undirected_graph(); // Each edge appears twice and in different directions. // When we sort the edges with the first vertex id, we only need // a single scan to construct the graph in the form of // the adjacency list. edge *tmp = new edge[num_edges * 2]; for (size_t i = 0; i < num_edges; i++) { tmp[2 * i] = edges[i]; tmp[2 * i + 1] = edge(edges[i].get_to(), edges[i].get_from()); } edges = tmp; num_edges *= 2; std::sort(edges, edges + num_edges, edge_comparator); vertex_id_t curr = edges[0].get_from(); in_mem_undirected_vertex v(curr); for (size_t i = 0; i < num_edges; i++) { vertex_id_t id = edges[i].get_from(); if (curr == id) { // We have to make sure the edge doesn't exist. assert(!v.has_edge(edges[i].get_to())); v.add_edge(edges[i].get_to()); } else { g->add_vertex(v); vertex_id_t prev = curr + 1; curr = id; // The vertices without edges won't show up in the edge list, // but we need to fill the gap in the vertex Id space with empty // vertices. while (prev < curr) { v = in_mem_undirected_vertex(prev); prev++; g->add_vertex(v); } v = in_mem_undirected_vertex(curr); v.add_edge(edges[i].get_to()); } } g->add_vertex(v); delete [] edges; return g; } undirected_graph *undirected_graph::load_edge_list(const std::string &file) { std::vector<edge> edges; read_edge_list(file, edges); return create(edges.data(), edges.size()); } undirected_graph *undirected_graph::load_edge_list_text(const std::string &file) { std::vector<edge> edges; read_edge_list_text(file, edges); return create(edges.data(), edges.size()); } undirected_graph *undirected_graph::load_adjacency_list(const std::string &file) { assert(0); } vertex_index *undirected_graph::create_vertex_index() const { return vertex_index::create<in_mem_undirected_vertex>(vertices); } void undirected_graph::dump(const std::string &file) const { FILE *f = fopen(file.c_str(), "w"); if (f == NULL) { perror("fopen"); assert(0); } for (size_t i = 0; i < vertices.size(); i++) { int mem_size = vertices[i].get_serialize_size(); char *buf = new char[mem_size]; ext_mem_undirected_vertex::serialize(vertices[i], buf, mem_size); ssize_t ret = fwrite(buf, mem_size, 1, f); delete [] buf; assert(ret == 1); } fclose(f); } size_t undirected_graph::get_num_edges() const { size_t num_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_edges += vertices[i].get_num_edges(); return num_edges; } size_t undirected_graph::get_num_non_empty_vertices() const { size_t num_vertices = 0; for (size_t i = 0; i < vertices.size(); i++) if (vertices[i].get_num_edges() > 0) num_vertices++; return num_vertices; } static struct comp_in_edge { bool operator() (const edge &e1, const edge &e2) { if (e1.get_to() == e2.get_to()) return e1.get_from() < e2.get_from(); else return e1.get_to() < e2.get_to(); } } in_edge_comparator; directed_graph *directed_graph::create(edge edges[], size_t num_edges) { directed_graph *g = new directed_graph(); std::sort(edges, edges + num_edges, edge_comparator); edge *sorted_out_edges = edges; edge *copied_edges = new edge[num_edges]; memcpy(copied_edges, edges, num_edges * sizeof(edges[0])); std::sort(copied_edges, copied_edges + num_edges, in_edge_comparator); edge *sorted_in_edges = copied_edges; vertex_id_t curr = min(sorted_out_edges[0].get_from(), sorted_in_edges[0].get_to()); in_mem_directed_vertex v(curr); size_t out_idx = 0; size_t in_idx = 0; while (out_idx < num_edges && in_idx < num_edges) { while (sorted_out_edges[out_idx].get_from() == curr && out_idx < num_edges) { v.add_out_edge(sorted_out_edges[out_idx++].get_to()); } while (sorted_in_edges[in_idx].get_to() == curr && in_idx < num_edges) { v.add_in_edge(sorted_in_edges[in_idx++].get_from()); } g->add_vertex(v); vertex_id_t prev = curr + 1; if (out_idx < num_edges && in_idx < num_edges) curr = min(sorted_out_edges[out_idx].get_from(), sorted_in_edges[in_idx].get_to()); else if (out_idx < num_edges) curr = sorted_out_edges[out_idx].get_from(); else if (in_idx < num_edges) curr = sorted_in_edges[in_idx].get_to(); else break; // The vertices without edges won't show up in the edge list, // but we need to fill the gap in the vertex Id space with empty // vertices. while (prev < curr) { v = in_mem_directed_vertex(prev); prev++; g->add_vertex(v); } v = in_mem_directed_vertex(curr); } assert(g->get_num_in_edges() == num_edges); assert(g->get_num_out_edges() == num_edges); delete [] copied_edges; return g; } directed_graph *directed_graph::load_edge_list(const std::string &file) { std::vector<edge> edges; read_edge_list(file, edges); return create(edges.data(), edges.size()); } directed_graph *directed_graph::load_edge_list_text(const std::string &file) { std::vector<edge> edges; read_edge_list_text(file, edges); return create(edges.data(), edges.size()); } directed_graph *directed_graph::load_adjacency_list(const std::string &file) { assert(0); return NULL; } vertex_index *directed_graph::create_vertex_index() const { return vertex_index::create<in_mem_directed_vertex>(vertices); } void directed_graph::dump(const std::string &file) const { FILE *f = fopen(file.c_str(), "w"); if (f == NULL) { perror("fopen"); assert(0); } for (size_t i = 0; i < vertices.size(); i++) { int mem_size = vertices[i].get_serialize_size(); char *buf = new char[mem_size]; ext_mem_directed_vertex::serialize(vertices[i], buf, mem_size); ssize_t ret = fwrite(buf, mem_size, 1, f); delete [] buf; assert(ret == 1); } fclose(f); } size_t directed_graph::get_num_in_edges() const { size_t num_in_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_in_edges += vertices[i].get_num_in_edges(); return num_in_edges; } size_t directed_graph::get_num_out_edges() const { size_t num_out_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_out_edges += vertices[i].get_num_out_edges(); return num_out_edges; } size_t directed_graph::get_num_non_empty_vertices() const { size_t num_vertices = 0; for (size_t i = 0; i < vertices.size(); i++) if (vertices[i].get_num_in_edges() > 0 || vertices[i].get_num_out_edges() > 0) num_vertices++; return num_vertices; } <commit_msg>[Graph]: remove the code of reading binary edge lists.<commit_after>/** * Copyright 2013 Da Zheng * * This file is part of SA-GraphLib. * * SA-GraphLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SA-GraphLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SA-GraphLib. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include "graph.h" #include "common.h" #include "native_file.h" size_t read_edge_list_text(const std::string &file, std::vector<edge> &edges) { FILE *f = fopen(file.c_str(), "r"); if (f == NULL) { perror("fopen"); assert(0); } ssize_t read; size_t len = 0; char *line = NULL; while ((read = getline(&line, &len, f)) != -1) { if (line[read - 1] == '\n') line[read - 1] = 0; if (line[read - 2] == '\r') line[read - 2] = 0; if (line[0] == '#') continue; char *second = strchr(line, '\t'); assert(second); *second = 0; second++; if (!isnumeric(line) || !isnumeric(second)) { printf("%s\t%s\n", line, second); continue; } vertex_id_t from = atol(line); vertex_id_t to = atol(second); edges.push_back(edge(from, to)); } fclose(f); return edges.size(); } static struct comp_edge { bool operator() (const edge &e1, const edge &e2) { if (e1.get_from() == e2.get_from()) return e1.get_to() < e2.get_to(); else return e1.get_from() < e2.get_from(); } } edge_comparator; undirected_graph *undirected_graph::create(edge edges[], size_t num_edges) { undirected_graph *g = new undirected_graph(); // Each edge appears twice and in different directions. // When we sort the edges with the first vertex id, we only need // a single scan to construct the graph in the form of // the adjacency list. edge *tmp = new edge[num_edges * 2]; for (size_t i = 0; i < num_edges; i++) { tmp[2 * i] = edges[i]; tmp[2 * i + 1] = edge(edges[i].get_to(), edges[i].get_from()); } edges = tmp; num_edges *= 2; std::sort(edges, edges + num_edges, edge_comparator); vertex_id_t curr = edges[0].get_from(); in_mem_undirected_vertex v(curr); for (size_t i = 0; i < num_edges; i++) { vertex_id_t id = edges[i].get_from(); if (curr == id) { // We have to make sure the edge doesn't exist. assert(!v.has_edge(edges[i].get_to())); v.add_edge(edges[i].get_to()); } else { g->add_vertex(v); vertex_id_t prev = curr + 1; curr = id; // The vertices without edges won't show up in the edge list, // but we need to fill the gap in the vertex Id space with empty // vertices. while (prev < curr) { v = in_mem_undirected_vertex(prev); prev++; g->add_vertex(v); } v = in_mem_undirected_vertex(curr); v.add_edge(edges[i].get_to()); } } g->add_vertex(v); delete [] edges; return g; } undirected_graph *undirected_graph::load_edge_list_text(const std::string &file) { std::vector<edge> edges; read_edge_list_text(file, edges); return create(edges.data(), edges.size()); } undirected_graph *undirected_graph::load_adjacency_list(const std::string &file) { assert(0); } vertex_index *undirected_graph::create_vertex_index() const { return vertex_index::create<in_mem_undirected_vertex>(vertices); } void undirected_graph::dump(const std::string &file) const { FILE *f = fopen(file.c_str(), "w"); if (f == NULL) { perror("fopen"); assert(0); } for (size_t i = 0; i < vertices.size(); i++) { int mem_size = vertices[i].get_serialize_size(); char *buf = new char[mem_size]; ext_mem_undirected_vertex::serialize(vertices[i], buf, mem_size); ssize_t ret = fwrite(buf, mem_size, 1, f); delete [] buf; assert(ret == 1); } fclose(f); } size_t undirected_graph::get_num_edges() const { size_t num_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_edges += vertices[i].get_num_edges(); return num_edges; } size_t undirected_graph::get_num_non_empty_vertices() const { size_t num_vertices = 0; for (size_t i = 0; i < vertices.size(); i++) if (vertices[i].get_num_edges() > 0) num_vertices++; return num_vertices; } static struct comp_in_edge { bool operator() (const edge &e1, const edge &e2) { if (e1.get_to() == e2.get_to()) return e1.get_from() < e2.get_from(); else return e1.get_to() < e2.get_to(); } } in_edge_comparator; directed_graph *directed_graph::create(edge edges[], size_t num_edges) { directed_graph *g = new directed_graph(); std::sort(edges, edges + num_edges, edge_comparator); edge *sorted_out_edges = edges; edge *copied_edges = new edge[num_edges]; memcpy(copied_edges, edges, num_edges * sizeof(edges[0])); std::sort(copied_edges, copied_edges + num_edges, in_edge_comparator); edge *sorted_in_edges = copied_edges; vertex_id_t curr = min(sorted_out_edges[0].get_from(), sorted_in_edges[0].get_to()); in_mem_directed_vertex v(curr); size_t out_idx = 0; size_t in_idx = 0; while (out_idx < num_edges && in_idx < num_edges) { while (sorted_out_edges[out_idx].get_from() == curr && out_idx < num_edges) { v.add_out_edge(sorted_out_edges[out_idx++].get_to()); } while (sorted_in_edges[in_idx].get_to() == curr && in_idx < num_edges) { v.add_in_edge(sorted_in_edges[in_idx++].get_from()); } g->add_vertex(v); vertex_id_t prev = curr + 1; if (out_idx < num_edges && in_idx < num_edges) curr = min(sorted_out_edges[out_idx].get_from(), sorted_in_edges[in_idx].get_to()); else if (out_idx < num_edges) curr = sorted_out_edges[out_idx].get_from(); else if (in_idx < num_edges) curr = sorted_in_edges[in_idx].get_to(); else break; // The vertices without edges won't show up in the edge list, // but we need to fill the gap in the vertex Id space with empty // vertices. while (prev < curr) { v = in_mem_directed_vertex(prev); prev++; g->add_vertex(v); } v = in_mem_directed_vertex(curr); } assert(g->get_num_in_edges() == num_edges); assert(g->get_num_out_edges() == num_edges); delete [] copied_edges; return g; } directed_graph *directed_graph::load_edge_list_text(const std::string &file) { std::vector<edge> edges; read_edge_list_text(file, edges); return create(edges.data(), edges.size()); } directed_graph *directed_graph::load_adjacency_list(const std::string &file) { assert(0); return NULL; } vertex_index *directed_graph::create_vertex_index() const { return vertex_index::create<in_mem_directed_vertex>(vertices); } void directed_graph::dump(const std::string &file) const { FILE *f = fopen(file.c_str(), "w"); if (f == NULL) { perror("fopen"); assert(0); } for (size_t i = 0; i < vertices.size(); i++) { int mem_size = vertices[i].get_serialize_size(); char *buf = new char[mem_size]; ext_mem_directed_vertex::serialize(vertices[i], buf, mem_size); ssize_t ret = fwrite(buf, mem_size, 1, f); delete [] buf; assert(ret == 1); } fclose(f); } size_t directed_graph::get_num_in_edges() const { size_t num_in_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_in_edges += vertices[i].get_num_in_edges(); return num_in_edges; } size_t directed_graph::get_num_out_edges() const { size_t num_out_edges = 0; for (size_t i = 0; i < vertices.size(); i++) num_out_edges += vertices[i].get_num_out_edges(); return num_out_edges; } size_t directed_graph::get_num_non_empty_vertices() const { size_t num_vertices = 0; for (size_t i = 0; i < vertices.size(); i++) if (vertices[i].get_num_in_edges() > 0 || vertices[i].get_num_out_edges() > 0) num_vertices++; return num_vertices; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; ll x[2][100010]; typedef tuple<int, int> point; typedef tuple<ll, int, int> edge; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[0][i] >> x[1][i]; } vector<edge> V; for (auto k = 0; k < 2; ++k) { vector<point> W; for (auto i = 0; i < N; ++i) { W.push_back(point(x[k][i], i)); } sort(W.begin(), W.end()); for (auto i = 0; i < N-1; ++i) { int d0 = get<0>(W[i]); int p0 = get<1>(W[i+1]); int d1 = get<0>(W[i]); int p1 = get<1>(W[i+1]); V.push_back(edge(abs(d0 - d1), p0, p1)); } } sort(V.begin(), V.end()); int used = 0; ll ans = 0; bool visited[100010]; fill(visited, visited+100010, false); auto it = V.begin(); while (used < N) { ll cost = get<0>(*it); int p0 = get<1>(*it); int p1 = get<2>(*it); ++it; if (visited[p0] && visited[p1]) continue; if (!visited[p0]) { visited[p0] = true; ++used; } if (!visited[p1]) { visited[p1] = true; ++used; } ans += cost; } cout << ans << endl; } <commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; ll x[2][100010]; typedef tuple<int, int> point; typedef tuple<ll, int, int> edge; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[0][i] >> x[1][i]; } vector<edge> V; for (auto k = 0; k < 2; ++k) { vector<point> W; for (auto i = 0; i < N; ++i) { W.push_back(point(x[k][i], i)); } sort(W.begin(), W.end()); for (auto i = 0; i < N-1; ++i) { int d0 = get<0>(W[i]); int p0 = get<1>(W[i+1]); int d1 = get<0>(W[i]); int p1 = get<1>(W[i+1]); V.push_back(edge(abs(d0 - d1), p0, p1)); } } sort(V.begin(), V.end()); int used = 0; ll ans = 0; bool visited[100010]; fill(visited, visited+100010, false); auto it = V.begin(); while (used < N) { ll cost = get<0>(*it); int p0 = get<1>(*it); int p1 = get<2>(*it); cerr << "cost = " << cost << ", p0 = " << p0 << ", p1 = " << p1 << endl; ++it; if (visited[p0] && visited[p1]) continue; if (!visited[p0]) { visited[p0] = true; ++used; } if (!visited[p1]) { visited[p1] = true; ++used; } ans += cost; } cout << ans << endl; } <|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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views debug build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartHTTPServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_CaptureVisibleTabPng) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Broaden flakiness filter for ExtensionApiTest.Tabs as it now appears to fail on NDEBUG builds too.<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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartHTTPServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_CaptureVisibleTabPng) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>#include "a_star.h" using namespace std; /* Constructor */ AStar::AStar() { // TODO: throw error } AStar::AStar(State &init) { root_ = init; //solutionLeaf_ = NULL; debugLevel_ = 0; /* Initialize costs of root node */ root_.setGCost(0); root_.setHCost(root_.computeHCost()); root_.setFCost(root_.getGCost() + root_.getHCost()); /* Add initial state to queue */ open_.push(root_); openVector_.push_back(root_); //closed_.push_back(root_); } /* Destructor */ AStar::~AStar() { } /* Planning functions */ bool AStar::solve() { int pos, posi; /* Initialize closed list (open list initialized in constructor) */ closed_.clear(); while(!open_.empty()) { //for (int i = 0; i < 1500; i++) { /* Retrieve first element of queue and delete from queue */ State tmp = open_.top(); open_.pop(); /* Keep a copy of the priority queue as a vector, so we can * check if something is already in the open list */ //cout << " ############################" << endl; //cout << " Printing open before delete " << endl; //printOpen(); //cout << " ############################" << endl; isOpen(&tmp, &pos); openVector_.erase(openVector_.begin() + pos); //cout << " ############################" << endl; //cout << " Printing open after delete " << endl; //cout << " ############################" << endl; //printOpen(); //cout << " ############################" << endl; /* Add tmp to closed list */ if(!isClosed(&tmp, &pos)) { closed_.push_back(tmp); } /* Check if we have found the solution */ if(tmp.isGoal()) { cout << "AStar::solve(): Solution found" << endl; extractSolution(&tmp); //printSolution(); return true; } /* Compute neighboring states */ vector<State> neighbors = tmp.expandState(); //cout << " ###########################" << endl; //cout << " Printing closed list " << endl; //printClosed(); //printOpen(); //cout << " ###########################" << endl; cout << "!! Computed " << neighbors.size() << " neighbors !!" << endl; /* Iterate over neighboring states */ for (int i = 0; i < neighbors.size(); i++) { /* Compute tentative g-cost of neighbor * NOTE: the distance between a neigbhor and tmp is always * one move */ int tentative_g_score = tmp.getGCost() + 1; /* Check if neighbor is already in closed list */ if(isClosed(&neighbors.at(i), &pos)) { /* 1. compute g-cost of neighbor * 2. if g-cost is better than that of the state in the * closed_list, reopen the state (remove from closed, add to * open) */ //if(tentative_g_score < neighbors.at(i).getGCost()) { ///* Add to open list - i.e. reopen the node */ //open_.push(neighbors.at(i)); ///* Remove from closed list */ //closed_.erase(closed_.begin() + pos); //} else { //continue; //} continue; } else { /* 1. create new state based on parent tmp * 2. compute f, g, h costs (done in constructor) * 3. add to open_ list */ /* Only add to open list, if it was not already in there */ if(!isOpen(&neighbors.at(i), &posi)) { cout << "--- Adding the following neighbor to the open list ---" << endl; neighbors.at(i).printState(); open_.push(neighbors.at(i)); openVector_.push_back(neighbors.at(i)); } /* NOTE: technically we should check if the node is already * in the open list, but that's hard to do with a * priority queue. Instead we allow to add duplicates * to the open list and discard them on following iterations * (because they will be in closed list and discarded. */ } } cout << "--- End neighbor iteration ---" << endl; } /* If the while loop terminates without calling extractSolution, then no * solution has been found */ cout << "Error AStar: No solution has been found." << endl; return false; } void AStar::extractSolution(State* solutionLeaf) { State* tmp = solutionLeaf; /*while(tmp->getParent() != NULL) { tmp->printState(); solution_.push_back(*tmp); tmp = tmp->getParent(); }*/ vector<Direction> solution = solutionLeaf->getCommands(); cout << "Solution: "; for(unsigned int i = solution.size()-1; i >0; i--){ switch(solution[i]){ case LEFT: cout << "LEFT "; case RIGHT: cout << "RIGHT "; case UP: cout << "UP "; case DOWN: cout << "DOWN "; defualt: cout << "STAY "; } } cout << "End solution" << endl;; /* Since the solution goes from goal to initial state, reverse the vector * such that it goes from initial to final state */ reverse(solution_.begin(), solution_.end()); } bool AStar::isOpen(State* state, int *pos) { bool debug = false; if(debug) { cout << "AStar::isOpen: Size of open list: " << openVector_.size() << endl; cout << " Comparint state vs open list element" << endl; state->printState(); cout << "##### vs. ####" << endl; } for (int i = 0; i < openVector_.size(); i++) { if(debug) { openVector_.at(i).printState(); } if(*state == openVector_.at(i)) { if(debug) { cout << "state == openVector_.at(" << i << ")" << endl; } *pos = i; return true; } else { if(debug) { cout << "state != openVector_.at(" << i << ")" << endl; } } } return false; } bool AStar::isClosed(State* state, int *pos) { bool debug = false; if(debug) { cout << "AStar::isClosed: Size of closed list: " << closed_.size() << endl; cout << " Comparint state vs open list element" << endl; state->printState(); cout << "##### vs. ####" << endl; } for (int i = 0; i < closed_.size(); i++) { if(debug) { closed_.at(i).printState(); } if(*state == closed_.at(i)) { if(debug) { cout << "state == closed_.at(" << i << ")" << endl; } *pos = i; return true; } else { if(debug) { cout << "state != closed_.at(" << i << ")" << endl; } } } return false; } /* Display functions */ void AStar::printSolution() { for (int i = 0; i < solution_.size(); i++) { cout << solution_.at(i); for (int j = 0; j < solution_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } void AStar::printOpen() { /* Can't iterate over queue, therefore printing the open list is not * trivial and would involve creating a copy of the queue */ for (int i = 0; i < openVector_.size(); i++) { openVector_.at(i).printState(); for (int j = 0; j < openVector_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } void AStar::printClosed() { for (int i = 0; i < closed_.size(); i++) { closed_.at(i).printState(); for (int j = 0; j < closed_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } /* Get functions */ statePQ AStar::getOpen() { return open_; } std::vector<State> AStar::getClosed() { return closed_; } vector<State> AStar::getSolution() { return solution_; } <commit_msg>Properly prints solution<commit_after>#include "a_star.h" using namespace std; /* Constructor */ AStar::AStar() { // TODO: throw error } AStar::AStar(State &init) { root_ = init; //solutionLeaf_ = NULL; debugLevel_ = 0; /* Initialize costs of root node */ root_.setGCost(0); root_.setHCost(root_.computeHCost()); root_.setFCost(root_.getGCost() + root_.getHCost()); /* Add initial state to queue */ open_.push(root_); openVector_.push_back(root_); //closed_.push_back(root_); } /* Destructor */ AStar::~AStar() { } /* Planning functions */ bool AStar::solve() { int pos, posi; /* Initialize closed list (open list initialized in constructor) */ closed_.clear(); while(!open_.empty()) { //for (int i = 0; i < 1500; i++) { /* Retrieve first element of queue and delete from queue */ State tmp = open_.top(); open_.pop(); /* Keep a copy of the priority queue as a vector, so we can * check if something is already in the open list */ //cout << " ############################" << endl; //cout << " Printing open before delete " << endl; //printOpen(); //cout << " ############################" << endl; isOpen(&tmp, &pos); openVector_.erase(openVector_.begin() + pos); //cout << " ############################" << endl; //cout << " Printing open after delete " << endl; //cout << " ############################" << endl; //printOpen(); //cout << " ############################" << endl; /* Add tmp to closed list */ if(!isClosed(&tmp, &pos)) { closed_.push_back(tmp); } /* Check if we have found the solution */ if(tmp.isGoal()) { cout << "AStar::solve(): Solution found" << endl; extractSolution(&tmp); //printSolution(); return true; } /* Compute neighboring states */ vector<State> neighbors = tmp.expandState(); //cout << " ###########################" << endl; //cout << " Printing closed list " << endl; //printClosed(); //printOpen(); //cout << " ###########################" << endl; cout << "!! Computed " << neighbors.size() << " neighbors !!" << endl; /* Iterate over neighboring states */ for (int i = 0; i < neighbors.size(); i++) { /* Compute tentative g-cost of neighbor * NOTE: the distance between a neigbhor and tmp is always * one move */ int tentative_g_score = tmp.getGCost() + 1; /* Check if neighbor is already in closed list */ if(isClosed(&neighbors.at(i), &pos)) { /* 1. compute g-cost of neighbor * 2. if g-cost is better than that of the state in the * closed_list, reopen the state (remove from closed, add to * open) */ //if(tentative_g_score < neighbors.at(i).getGCost()) { ///* Add to open list - i.e. reopen the node */ //open_.push(neighbors.at(i)); ///* Remove from closed list */ //closed_.erase(closed_.begin() + pos); //} else { //continue; //} continue; } else { /* 1. create new state based on parent tmp * 2. compute f, g, h costs (done in constructor) * 3. add to open_ list */ /* Only add to open list, if it was not already in there */ if(!isOpen(&neighbors.at(i), &posi)) { cout << "--- Adding the following neighbor to the open list ---" << endl; neighbors.at(i).printState(); open_.push(neighbors.at(i)); openVector_.push_back(neighbors.at(i)); } /* NOTE: technically we should check if the node is already * in the open list, but that's hard to do with a * priority queue. Instead we allow to add duplicates * to the open list and discard them on following iterations * (because they will be in closed list and discarded. */ } } cout << "--- End neighbor iteration ---" << endl; } /* If the while loop terminates without calling extractSolution, then no * solution has been found */ cout << "Error AStar: No solution has been found." << endl; return false; } void AStar::extractSolution(State* solutionLeaf) { State* tmp = solutionLeaf; vector<Direction> solution = solutionLeaf->getCommands(); cout << "Solution: "; for(unsigned int i = solution.size()-1; i > 0; i--){ cout << i << " " << endl; cout << solution[i] << endl; switch(solution[i]){ case LEFT: cout << "LEFT "; break; case RIGHT: cout << "RIGHT "; break; case UP: cout << "UP "; break; case DOWN: cout << "DOWN "; break; default: cout << "STAY "; break; } } cout << "End solution" << endl;; /* Since the solution goes from goal to initial state, reverse the vector * such that it goes from initial to final state */ reverse(solution_.begin(), solution_.end()); } bool AStar::isOpen(State* state, int *pos) { bool debug = false; if(debug) { cout << "AStar::isOpen: Size of open list: " << openVector_.size() << endl; cout << " Comparint state vs open list element" << endl; state->printState(); cout << "##### vs. ####" << endl; } for (int i = 0; i < openVector_.size(); i++) { if(debug) { openVector_.at(i).printState(); } if(*state == openVector_.at(i)) { if(debug) { cout << "state == openVector_.at(" << i << ")" << endl; } *pos = i; return true; } else { if(debug) { cout << "state != openVector_.at(" << i << ")" << endl; } } } return false; } bool AStar::isClosed(State* state, int *pos) { bool debug = false; if(debug) { cout << "AStar::isClosed: Size of closed list: " << closed_.size() << endl; cout << " Comparint state vs open list element" << endl; state->printState(); cout << "##### vs. ####" << endl; } for (int i = 0; i < closed_.size(); i++) { if(debug) { closed_.at(i).printState(); } if(*state == closed_.at(i)) { if(debug) { cout << "state == closed_.at(" << i << ")" << endl; } *pos = i; return true; } else { if(debug) { cout << "state != closed_.at(" << i << ")" << endl; } } } return false; } /* Display functions */ void AStar::printSolution() { for (int i = 0; i < solution_.size(); i++) { cout << solution_.at(i); for (int j = 0; j < solution_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } void AStar::printOpen() { /* Can't iterate over queue, therefore printing the open list is not * trivial and would involve creating a copy of the queue */ for (int i = 0; i < openVector_.size(); i++) { openVector_.at(i).printState(); for (int j = 0; j < openVector_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } void AStar::printClosed() { for (int i = 0; i < closed_.size(); i++) { closed_.at(i).printState(); for (int j = 0; j < closed_.at(i).getWorld()->getSizeX() * 2; j++) { cout << "#"; } cout << endl; } } /* Get functions */ statePQ AStar::getOpen() { return open_; } std::vector<State> AStar::getClosed() { return closed_; } vector<State> AStar::getSolution() { return solution_; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlenums.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: mtg $ $Date: 2001-05-16 11:46:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLENUMS_HXX_ #define _XMLENUMS_HXX_ enum XMLForbiddenCharactersEnum { XML_FORBIDDEN_CHARACTER_LANGUAGE, XML_FORBIDDEN_CHARACTER_COUNTRY, XML_FORBIDDEN_CHARACTER_VARIANT, XML_FORBIDDEN_CHARACTER_BEGIN_LINE, XML_FORBIDDEN_CHARACTER_END_LINE, XML_FORBIDDEN_CHARACTER_MAX }; enum XMLSymbolDescriptorsEnum { XML_SYMBOL_DESCRIPTOR_NAME, XML_SYMBOL_DESCRIPTOR_EXPORT_NAME, XML_SYMBOL_DESCRIPTOR_SYMBOL_SET, XML_SYMBOL_DESCRIPTOR_CHARACTER, XML_SYMBOL_DESCRIPTOR_FONT_NAME, XML_SYMBOL_DESCRIPTOR_CHAR_SET, XML_SYMBOL_DESCRIPTOR_FAMILY, XML_SYMBOL_DESCRIPTOR_PITCH, XML_SYMBOL_DESCRIPTOR_WEIGHT, XML_SYMBOL_DESCRIPTOR_ITALIC, XML_SYMBOL_DESCRIPTOR_MAX }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.640); FILE MERGED 2005/09/05 14:38:36 rt 1.1.640.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlenums.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:36:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLENUMS_HXX_ #define _XMLENUMS_HXX_ enum XMLForbiddenCharactersEnum { XML_FORBIDDEN_CHARACTER_LANGUAGE, XML_FORBIDDEN_CHARACTER_COUNTRY, XML_FORBIDDEN_CHARACTER_VARIANT, XML_FORBIDDEN_CHARACTER_BEGIN_LINE, XML_FORBIDDEN_CHARACTER_END_LINE, XML_FORBIDDEN_CHARACTER_MAX }; enum XMLSymbolDescriptorsEnum { XML_SYMBOL_DESCRIPTOR_NAME, XML_SYMBOL_DESCRIPTOR_EXPORT_NAME, XML_SYMBOL_DESCRIPTOR_SYMBOL_SET, XML_SYMBOL_DESCRIPTOR_CHARACTER, XML_SYMBOL_DESCRIPTOR_FONT_NAME, XML_SYMBOL_DESCRIPTOR_CHAR_SET, XML_SYMBOL_DESCRIPTOR_FAMILY, XML_SYMBOL_DESCRIPTOR_PITCH, XML_SYMBOL_DESCRIPTOR_WEIGHT, XML_SYMBOL_DESCRIPTOR_ITALIC, XML_SYMBOL_DESCRIPTOR_MAX }; #endif <|endoftext|>
<commit_before>#include "Test.h" #include "SkPath.h" #include "SkParse.h" #include "SkSize.h" static void check_convex_bounds(skiatest::Reporter* reporter, const SkPath& p, const SkRect& bounds) { REPORTER_ASSERT(reporter, p.isConvex()); REPORTER_ASSERT(reporter, p.getBounds() == bounds); SkPath p2(p); REPORTER_ASSERT(reporter, p2.isConvex()); REPORTER_ASSERT(reporter, p2.getBounds() == bounds); SkPath other; other.swap(p2); REPORTER_ASSERT(reporter, other.isConvex()); REPORTER_ASSERT(reporter, other.getBounds() == bounds); } static void setFromString(SkPath* path, const char str[]) { bool first = true; while (str) { SkScalar x, y; str = SkParse::FindScalar(str, &x); if (NULL == str) { break; } str = SkParse::FindScalar(str, &y); SkASSERT(str); if (first) { path->moveTo(x, y); first = false; } else { path->lineTo(x, y); } } } static void test_convexity(skiatest::Reporter* reporter) { static const SkPath::Convexity U = SkPath::kUnknown_Convexity; static const SkPath::Convexity C = SkPath::kConcave_Convexity; static const SkPath::Convexity V = SkPath::kConvex_Convexity; SkPath path; REPORTER_ASSERT(reporter, U == SkPath::ComputeConvexity(path)); path.addCircle(0, 0, 10); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); path.addCircle(0, 0, 10); // 2nd circle REPORTER_ASSERT(reporter, C == SkPath::ComputeConvexity(path)); path.reset(); path.addRect(0, 0, 10, 10, SkPath::kCCW_Direction); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); path.reset(); path.addRect(0, 0, 10, 10, SkPath::kCW_Direction); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); static const struct { const char* fPathStr; SkPath::Convexity fExpectedConvexity; } gRec[] = { { "0 0", SkPath::kUnknown_Convexity }, { "0 0 10 10", SkPath::kUnknown_Convexity }, { "0 0 10 10 20 20 0 0 10 10", SkPath::kUnknown_Convexity }, { "0 0 10 10 10 20", SkPath::kConvex_Convexity }, { "0 0 10 10 10 0", SkPath::kConvex_Convexity }, { "0 0 10 10 10 0 0 10", SkPath::kConcave_Convexity }, { "0 0 10 0 0 10 -10 -10", SkPath::kConcave_Convexity }, }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) { SkPath path; setFromString(&path, gRec[i].fPathStr); SkPath::Convexity c = SkPath::ComputeConvexity(path); REPORTER_ASSERT(reporter, c == gRec[i].fExpectedConvexity); } } void TestPath(skiatest::Reporter* reporter); void TestPath(skiatest::Reporter* reporter) { { SkSize size; size.fWidth = 3.4f; size.width(); size = SkSize::Make(3,4); SkISize isize = SkISize::Make(3,4); } SkTSize<SkScalar>::Make(3,4); SkPath p, p2; SkRect bounds, bounds2; REPORTER_ASSERT(reporter, p.isEmpty()); REPORTER_ASSERT(reporter, !p.isConvex()); REPORTER_ASSERT(reporter, p.getFillType() == SkPath::kWinding_FillType); REPORTER_ASSERT(reporter, !p.isInverseFillType()); REPORTER_ASSERT(reporter, p == p2); REPORTER_ASSERT(reporter, !(p != p2)); REPORTER_ASSERT(reporter, p.getBounds().isEmpty()); bounds.set(0, 0, SK_Scalar1, SK_Scalar1); p.setIsConvex(false); p.addRoundRect(bounds, SK_Scalar1, SK_Scalar1); check_convex_bounds(reporter, p, bounds); p.reset(); p.setIsConvex(false); p.addOval(bounds); check_convex_bounds(reporter, p, bounds); p.reset(); p.setIsConvex(false); p.addRect(bounds); check_convex_bounds(reporter, p, bounds); REPORTER_ASSERT(reporter, p != p2); REPORTER_ASSERT(reporter, !(p == p2)); // does getPoints return the right result REPORTER_ASSERT(reporter, p.getPoints(NULL, 5) == 4); SkPoint pts[4]; int count = p.getPoints(pts, 4); REPORTER_ASSERT(reporter, count == 4); bounds2.set(pts, 4); REPORTER_ASSERT(reporter, bounds == bounds2); bounds.offset(SK_Scalar1*3, SK_Scalar1*4); p.offset(SK_Scalar1*3, SK_Scalar1*4); REPORTER_ASSERT(reporter, bounds == p.getBounds()); #if 0 // isRect needs to be implemented REPORTER_ASSERT(reporter, p.isRect(NULL)); bounds.setEmpty(); REPORTER_ASSERT(reporter, p.isRect(&bounds2)); REPORTER_ASSERT(reporter, bounds == bounds2); // now force p to not be a rect bounds.set(0, 0, SK_Scalar1/2, SK_Scalar1/2); p.addRect(bounds); REPORTER_ASSERT(reporter, !p.isRect(NULL)); #endif SkPoint pt; p.moveTo(SK_Scalar1, 0); p.getLastPt(&pt); REPORTER_ASSERT(reporter, pt.fX == SK_Scalar1); // check that reset and rewind clear the convex hint back to false p.setIsConvex(false); REPORTER_ASSERT(reporter, !p.isConvex()); p.setIsConvex(true); REPORTER_ASSERT(reporter, p.isConvex()); p.reset(); REPORTER_ASSERT(reporter, !p.isConvex()); p.setIsConvex(true); REPORTER_ASSERT(reporter, p.isConvex()); p.rewind(); REPORTER_ASSERT(reporter, !p.isConvex()); test_convexity(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Path", PathTestClass, TestPath) <commit_msg>migrate more tests from GrPath.cpp<commit_after>#include "Test.h" #include "SkPath.h" #include "SkParse.h" #include "SkSize.h" static void check_convexity(skiatest::Reporter* reporter, const SkPath& path, SkPath::Convexity expected) { SkPath::Convexity c = SkPath::ComputeConvexity(path); REPORTER_ASSERT(reporter, c == expected); } static void test_convexity2(skiatest::Reporter* reporter) { SkPath pt; pt.moveTo(0, 0); pt.close(); // check_convexity(reporter, pt, SkPath::kConvex_Convexity); check_convexity(reporter, pt, SkPath::kUnknown_Convexity); SkPath line; line.moveTo(12, 20); line.lineTo(-12, -20); line.close(); // check_convexity(reporter, pt, SkPath::kConvex_Convexity); check_convexity(reporter, pt, SkPath::kUnknown_Convexity); SkPath triLeft; triLeft.moveTo(0, 0); triLeft.lineTo(1, 0); triLeft.lineTo(1, 1); triLeft.close(); check_convexity(reporter, triLeft, SkPath::kConvex_Convexity); SkPath triRight; triRight.moveTo(0, 0); triRight.lineTo(-1, 0); triRight.lineTo(1, 1); triRight.close(); check_convexity(reporter, triRight, SkPath::kConvex_Convexity); SkPath square; square.moveTo(0, 0); square.lineTo(1, 0); square.lineTo(1, 1); square.lineTo(0, 1); square.close(); check_convexity(reporter, square, SkPath::kConvex_Convexity); SkPath redundantSquare; redundantSquare.moveTo(0, 0); redundantSquare.lineTo(0, 0); redundantSquare.lineTo(0, 0); redundantSquare.lineTo(1, 0); redundantSquare.lineTo(1, 0); redundantSquare.lineTo(1, 0); redundantSquare.lineTo(1, 1); redundantSquare.lineTo(1, 1); redundantSquare.lineTo(1, 1); redundantSquare.lineTo(0, 1); redundantSquare.lineTo(0, 1); redundantSquare.lineTo(0, 1); redundantSquare.close(); check_convexity(reporter, redundantSquare, SkPath::kConvex_Convexity); SkPath bowTie; bowTie.moveTo(0, 0); bowTie.lineTo(0, 0); bowTie.lineTo(0, 0); bowTie.lineTo(1, 1); bowTie.lineTo(1, 1); bowTie.lineTo(1, 1); bowTie.lineTo(1, 0); bowTie.lineTo(1, 0); bowTie.lineTo(1, 0); bowTie.lineTo(0, 1); bowTie.lineTo(0, 1); bowTie.lineTo(0, 1); bowTie.close(); check_convexity(reporter, bowTie, SkPath::kConcave_Convexity); SkPath spiral; spiral.moveTo(0, 0); spiral.lineTo(1, 0); spiral.lineTo(1, 1); spiral.lineTo(0, 1); spiral.lineTo(0,.5); spiral.lineTo(.5,.5); spiral.lineTo(.5,.75); spiral.close(); // check_convexity(reporter, spiral, SkPath::kConcave_Convexity); SkPath dent; dent.moveTo(0, 0); dent.lineTo(1, 1); dent.lineTo(0, 1); dent.lineTo(-.5,2); dent.lineTo(-2, 1); dent.close(); check_convexity(reporter, dent, SkPath::kConcave_Convexity); } static void check_convex_bounds(skiatest::Reporter* reporter, const SkPath& p, const SkRect& bounds) { REPORTER_ASSERT(reporter, p.isConvex()); REPORTER_ASSERT(reporter, p.getBounds() == bounds); SkPath p2(p); REPORTER_ASSERT(reporter, p2.isConvex()); REPORTER_ASSERT(reporter, p2.getBounds() == bounds); SkPath other; other.swap(p2); REPORTER_ASSERT(reporter, other.isConvex()); REPORTER_ASSERT(reporter, other.getBounds() == bounds); } static void setFromString(SkPath* path, const char str[]) { bool first = true; while (str) { SkScalar x, y; str = SkParse::FindScalar(str, &x); if (NULL == str) { break; } str = SkParse::FindScalar(str, &y); SkASSERT(str); if (first) { path->moveTo(x, y); first = false; } else { path->lineTo(x, y); } } } static void test_convexity(skiatest::Reporter* reporter) { static const SkPath::Convexity U = SkPath::kUnknown_Convexity; static const SkPath::Convexity C = SkPath::kConcave_Convexity; static const SkPath::Convexity V = SkPath::kConvex_Convexity; SkPath path; REPORTER_ASSERT(reporter, U == SkPath::ComputeConvexity(path)); path.addCircle(0, 0, 10); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); path.addCircle(0, 0, 10); // 2nd circle REPORTER_ASSERT(reporter, C == SkPath::ComputeConvexity(path)); path.reset(); path.addRect(0, 0, 10, 10, SkPath::kCCW_Direction); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); path.reset(); path.addRect(0, 0, 10, 10, SkPath::kCW_Direction); REPORTER_ASSERT(reporter, V == SkPath::ComputeConvexity(path)); static const struct { const char* fPathStr; SkPath::Convexity fExpectedConvexity; } gRec[] = { { "0 0", SkPath::kUnknown_Convexity }, { "0 0 10 10", SkPath::kUnknown_Convexity }, { "0 0 10 10 20 20 0 0 10 10", SkPath::kUnknown_Convexity }, { "0 0 10 10 10 20", SkPath::kConvex_Convexity }, { "0 0 10 10 10 0", SkPath::kConvex_Convexity }, { "0 0 10 10 10 0 0 10", SkPath::kConcave_Convexity }, { "0 0 10 0 0 10 -10 -10", SkPath::kConcave_Convexity }, }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) { SkPath path; setFromString(&path, gRec[i].fPathStr); SkPath::Convexity c = SkPath::ComputeConvexity(path); REPORTER_ASSERT(reporter, c == gRec[i].fExpectedConvexity); } } void TestPath(skiatest::Reporter* reporter); void TestPath(skiatest::Reporter* reporter) { { SkSize size; size.fWidth = 3.4f; size.width(); size = SkSize::Make(3,4); SkISize isize = SkISize::Make(3,4); } SkTSize<SkScalar>::Make(3,4); SkPath p, p2; SkRect bounds, bounds2; REPORTER_ASSERT(reporter, p.isEmpty()); REPORTER_ASSERT(reporter, !p.isConvex()); REPORTER_ASSERT(reporter, p.getFillType() == SkPath::kWinding_FillType); REPORTER_ASSERT(reporter, !p.isInverseFillType()); REPORTER_ASSERT(reporter, p == p2); REPORTER_ASSERT(reporter, !(p != p2)); REPORTER_ASSERT(reporter, p.getBounds().isEmpty()); bounds.set(0, 0, SK_Scalar1, SK_Scalar1); p.setIsConvex(false); p.addRoundRect(bounds, SK_Scalar1, SK_Scalar1); check_convex_bounds(reporter, p, bounds); p.reset(); p.setIsConvex(false); p.addOval(bounds); check_convex_bounds(reporter, p, bounds); p.reset(); p.setIsConvex(false); p.addRect(bounds); check_convex_bounds(reporter, p, bounds); REPORTER_ASSERT(reporter, p != p2); REPORTER_ASSERT(reporter, !(p == p2)); // does getPoints return the right result REPORTER_ASSERT(reporter, p.getPoints(NULL, 5) == 4); SkPoint pts[4]; int count = p.getPoints(pts, 4); REPORTER_ASSERT(reporter, count == 4); bounds2.set(pts, 4); REPORTER_ASSERT(reporter, bounds == bounds2); bounds.offset(SK_Scalar1*3, SK_Scalar1*4); p.offset(SK_Scalar1*3, SK_Scalar1*4); REPORTER_ASSERT(reporter, bounds == p.getBounds()); #if 0 // isRect needs to be implemented REPORTER_ASSERT(reporter, p.isRect(NULL)); bounds.setEmpty(); REPORTER_ASSERT(reporter, p.isRect(&bounds2)); REPORTER_ASSERT(reporter, bounds == bounds2); // now force p to not be a rect bounds.set(0, 0, SK_Scalar1/2, SK_Scalar1/2); p.addRect(bounds); REPORTER_ASSERT(reporter, !p.isRect(NULL)); #endif SkPoint pt; p.moveTo(SK_Scalar1, 0); p.getLastPt(&pt); REPORTER_ASSERT(reporter, pt.fX == SK_Scalar1); // check that reset and rewind clear the convex hint back to false p.setIsConvex(false); REPORTER_ASSERT(reporter, !p.isConvex()); p.setIsConvex(true); REPORTER_ASSERT(reporter, p.isConvex()); p.reset(); REPORTER_ASSERT(reporter, !p.isConvex()); p.setIsConvex(true); REPORTER_ASSERT(reporter, p.isConvex()); p.rewind(); REPORTER_ASSERT(reporter, !p.isConvex()); test_convexity(reporter); test_convexity2(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Path", PathTestClass, TestPath) <|endoftext|>
<commit_before>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-2-26 20:57:11 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i=2; i<MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD; } fact[0] = factinv[0] = 1; for (int i=1; i<MAX_SIZE; i++) { fact[i] = (i * fact[i-1])%MOD; factinv[i] = (inv[i] * factinv[i-1])%MOD; } } long long C(int n, int k) { if (n >=0 && k >= 0 && n-k >= 0) { return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n%2 == 1) { return (x * power(x, n-1)) % MOD; } else { long long half = power(x, n/2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a%b); } int N; vector<int> V[5010]; vector<int> children[5010]; int child_num[5010]; int parent[5010]; ll DP[5010][5010]; int calc_child_num(int n) { if (child_num[n] >= 0) return child_num[n]; child_num[n] = 1; for (auto x : children[n]) { child_num[n] += calc_child_num(x); } return child_num[n]; } int main() { init(); cin >> N; for (auto i = 0; i < N-1; i++) { int x, y; cin >> x >> y; x--; y--; V[x].push_back(y); V[y].push_back(x); } queue<int> Q; Q.push(0); fill(child_num, child_num + 5010, -1); fill(parent, parent + 5010, -1); parent[0] = -2; while (!Q.empty()) { int now = Q.front(); Q.pop(); for (auto x : V[now]) { if (parent[x] == -1) { parent[x] = now; children[now].push_back(x); Q.push(x); } } } calc_child_num(0); bool is_there_two_center = false; int center = 0; while (true) { bool found_center = true; #if DEBUG == 1 cerr << "center = " << center << endl; #endif for (auto x : children[center]) { if (N % 2 == 0 && child_num[x] == N / 2) { is_there_two_center = true; center = x; break; } else if (child_num[x] > N/2) { center = x; found_center = false; break; } } if (found_center) break; } if (is_there_two_center) { ll sq = fact[N / 2]; cout << (sq * sq) % MOD << endl; return 0; } vector<ll> T; T.push_back(0); ll nokori = N-1; for (auto x : children[center]) { ll n = child_num[x]; T.push_back(n); nokori -= n; } if (nokori > 0) T.push_back(nokori); int X = T.size(); X--; #if DEBUG == 1 cerr << "T : "; for (auto x : T) { cerr << x << " "; } cerr << endl; #endif fill(&DP[0][0], &DP[0][0] + 5010 * 5010, 0); DP[0][0] = 1; for (auto x = 1; x <= X; x++) { for (auto i = 0; i <= T[x]; i++) { for (auto k = 0; k <= N-i; k++) { ll c = C(T[x], i); ll plus = (DP[k][x - 1] * fact[i]) % MOD; plus = (plus * ((c * c) % MOD)) % MOD; DP[k + i][x] += plus; DP[k + i][x] %= MOD; } } } ll ans = 0; for (auto k = 0; k <= N; k++) { #if DEBUG == 1 cerr << "DP[" << X << "][" << k << "] = " << DP[X][k] << endl; #endif if (k%2 == 0) { ans += (fact[N - k] * DP[X][k]) % MOD; ans %= MOD; } else { ans += MOD - (fact[N - k] * DP[X][k]) % MOD; ans %= MOD; } } cout << ans << endl; }<commit_msg>tried F.cpp to 'F'<commit_after>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-2-26 20:57:11 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i=2; i<MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD; } fact[0] = factinv[0] = 1; for (int i=1; i<MAX_SIZE; i++) { fact[i] = (i * fact[i-1])%MOD; factinv[i] = (inv[i] * factinv[i-1])%MOD; } } long long C(int n, int k) { if (n >=0 && k >= 0 && n-k >= 0) { return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n%2 == 1) { return (x * power(x, n-1)) % MOD; } else { long long half = power(x, n/2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a%b); } int N; vector<int> V[5010]; vector<int> children[5010]; int child_num[5010]; int parent[5010]; ll DP[5010][5010]; int calc_child_num(int n) { if (child_num[n] >= 0) return child_num[n]; child_num[n] = 1; for (auto x : children[n]) { child_num[n] += calc_child_num(x); } return child_num[n]; } int main() { init(); cin >> N; for (auto i = 0; i < N-1; i++) { int x, y; cin >> x >> y; x--; y--; V[x].push_back(y); V[y].push_back(x); } queue<int> Q; Q.push(0); fill(child_num, child_num + 5010, -1); fill(parent, parent + 5010, -1); parent[0] = -2; while (!Q.empty()) { int now = Q.front(); Q.pop(); for (auto x : V[now]) { if (parent[x] == -1) { parent[x] = now; children[now].push_back(x); Q.push(x); } } } calc_child_num(0); bool is_there_two_center = false; int center = 0; while (true) { bool found_center = true; #if DEBUG == 1 cerr << "center = " << center << endl; #endif for (auto x : children[center]) { if (N % 2 == 0 && child_num[x] == N / 2) { is_there_two_center = true; center = x; break; } else if (child_num[x] > N/2) { center = x; found_center = false; break; } } if (found_center) break; } if (is_there_two_center) { ll sq = fact[N / 2]; cout << (sq * sq) % MOD << endl; return 0; } vector<ll> T; T.push_back(0); ll nokori = N-1; for (auto x : children[center]) { ll n = child_num[x]; T.push_back(n); nokori -= n; } if (nokori > 0) T.push_back(nokori); int X = T.size(); X--; #if DEBUG == 1 cerr << "T : "; for (auto x : T) { cerr << x << " "; } cerr << endl; #endif fill(&DP[0][0], &DP[0][0] + 5010 * 5010, 0); DP[0][0] = 1; for (auto x = 1; x <= X; x++) { for (auto i = 0; i <= T[x]; i++) { for (auto k = 0; k <= N-i; k++) { ll c = C(T[x], i); ll plus = (DP[k][x - 1] * fact[i]) % MOD; plus = (plus * ((c * c) % MOD)) % MOD; DP[k + i][x] += plus; DP[k + i][x] %= MOD; } } } ll ans = 0; #if DEBUG == 1 for (auto x = 1; x <= X; x++) { for (auto k = 0; k <= N; k++) { cerr << "DP[" << x << "][" << k << "] = " << DP[x][k] << endl; } } #endif for (auto k = 0; k <= N; k++) { if (k%2 == 0) { ans += (fact[N - k] * DP[X][k]) % MOD; ans %= MOD; } else { ans += MOD - (fact[N - k] * DP[X][k]) % MOD; ans %= MOD; } } cout << ans << endl; }<|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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Mark ExtensionApiTest.Tabs flaky on win and linux.<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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else // It's flaky on win and linux. // http://crbug.com/58269 #define MAYBE_Tabs FLAKY_Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <future> #include <algorithm> #include <chrono> #include <thread> #include <thread> #include "BTree.h" int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 10000); BTree tree4(4); // A B-Tree with minium degree 4 std::vector<int> keys(10000); // vector with 10000 ints. std::iota(keys.begin(), keys.end(), 0); // Fill with 0, 1, ..., 9999. std::random_shuffle(std::begin(keys), std::end(keys)); // the first shufle std::for_each(keys.begin(), keys.end(), [&tree4](int key) { // add tree4.insert(key); }); std::cout << "Main thread id: " << std::this_thread::get_id() << std::endl; std::vector<std::future<void>> futures; for (int i = 0; i < 20; ++i) { auto fut = std::async([&] { int key = distribution(generator); std::cout << "Searching for key " << key << "..." << std::endl; if (tree4.exist(key)) std::cout << "Key " << key << " is found!" << std::endl; }); futures.push_back(std::move(fut)); } std::for_each(futures.begin(), futures.end(), [](std::future<void> &fut) { fut.wait(); }); std::random_shuffle(std::begin(keys), std::end(keys)); // the second shufle std::for_each(keys.begin(), keys.end(), [&tree4](int key) { // remove tree4.remove(key); }); return 0; } <commit_msg>Posix IPC.<commit_after>#include <iostream> #include <vector> #include <future> #include <algorithm> #include <chrono> #include <thread> #include "BTree.h" int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 10000); BTree tree4(4); // A B-Tree with minium degree 4 std::vector<int> keys(10000); // vector with 10000 ints. std::iota(keys.begin(), keys.end(), 0); // Fill with 0, 1, ..., 9999. std::random_shuffle(std::begin(keys), std::end(keys)); // the first shufle std::for_each(keys.begin(), keys.end(), [&tree4](int key) { // add tree4.insert(key); }); std::cout << "Main thread id: " << std::this_thread::get_id() << std::endl; std::vector<std::future<void>> futures; for (int i = 0; i < 20; ++i) { auto fut = std::async([&] { int key = distribution(generator); std::cout << "Searching for key " << key << "..." << std::endl; if (tree4.exist(key)) std::cout << "Key " << key << " is found!" << std::endl; }); futures.push_back(std::move(fut)); } std::for_each(futures.begin(), futures.end(), [](std::future<void> &fut) { fut.wait(); }); std::random_shuffle(std::begin(keys), std::end(keys)); // the second shufle std::for_each(keys.begin(), keys.end(), [&tree4](int key) { // remove tree4.remove(key); }); return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2012, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/format.hpp" #include "OP/OP_Director.h" #include "PRM/PRM_Default.h" #include "PRM/PRM_Template.h" #include "IECore/CompoundObject.h" #include "IECore/TransformationMatrixData.h" #include "IECore/VectorTypedData.h" #include "Convert.h" #include "ToHoudiniAttribConverter.h" #include "SOP_InterpolatedCacheReader.h" using namespace IECore; using namespace IECoreHoudini; static PRM_Name parameterNames[] = { PRM_Name( "cacheSequence", "Cache Sequence" ), PRM_Name( "objectFixes", "Object Prefix/Suffix" ), PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ), PRM_Name( "transformAttribute", "Transform Attribute" ), PRM_Name( "frameMultiplier", "Frame Multiplier" ), }; static PRM_Default frameMultiplierDefault( 1 ); PRM_Template SOP_InterpolatedCacheReader::parameters[] = { PRM_Template( PRM_FILE, 1, &parameterNames[0] ), PRM_Template( PRM_STRING, 2, &parameterNames[1] ), PRM_Template( PRM_STRING, 2, &parameterNames[2] ), PRM_Template( PRM_STRING, 1, &parameterNames[3] ), PRM_Template( PRM_INT, 1, &parameterNames[4], &frameMultiplierDefault ), PRM_Template(), }; SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op ) : SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 ) { flags().setTimeDep( true ); } SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader() { } OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op ) { return new SOP_InterpolatedCacheReader( net, name, op ); } OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context ) { flags().setTimeDep( true ); if ( lockInputs( context ) >= UT_ERROR_ABORT ) { return error(); } gdp->stashAll(); float time = context.getTime(); float frame = context.getFloatFrame(); UT_String paramVal; evalString( paramVal, "cacheSequence", 0, time ); std::string cacheFileName = paramVal.toStdString(); evalString( paramVal, "objectFixes", 0, time ); std::string objectPrefix = paramVal.toStdString(); evalString( paramVal, "objectFixes", 1, time ); std::string objectSuffix = paramVal.toStdString(); evalString( paramVal, "attributeFixes", 0, time ); std::string attributePrefix = paramVal.toStdString(); evalString( paramVal, "attributeFixes", 1, time ); std::string attributeSuffix = paramVal.toStdString(); evalString( paramVal, "transformAttribute", 0, time ); std::string transformAttribute = paramVal.toStdString(); int frameMultiplier = evalInt( "frameMultiplier", 0, time ); // create the InterpolatedCache if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier ) { try { float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec(); OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier ); m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc ); } catch ( IECore::InvalidArgumentException e ) { addWarning( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } m_cacheFileName = cacheFileName; m_frameMultiplier = frameMultiplier; } if ( !m_cache ) { addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" ); unlockInputs(); return error(); } std::vector<InterpolatedCache::ObjectHandle> objects; std::vector<InterpolatedCache::AttributeHandle> attrs; try { m_cache->objects( frame, objects ); } catch ( IECore::Exception e ) { addWarning( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } duplicatePointSource( 0, context ); for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it ) { GA_PointGroup *group = (GA_PointGroup*)it.group(); if ( group->getInternal() || group->isEmpty() ) { continue; } // match GA_PointGroup name to InterpolatedCache::ObjectHandle std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix; std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName ); if ( oIt == objects.end() ) { continue; } CompoundObjectPtr attributes = 0; try { m_cache->attributes( frame, *oIt, attrs ); attributes = m_cache->read( frame, *oIt ); } catch ( IECore::Exception e ) { addError( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } const CompoundObject::ObjectMap &attributeMap = attributes->members(); GA_Range pointRange = gdp->getPointRange( group ); // transfer the InterpolatedCache::Attributes onto the GA_PointGroup /// \todo: this does not account for detail, prim, or vertex attribs... for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ ) { const Data *data = IECore::runTimeCast<const Data>( aIt->second ); if ( !data ) { continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data ); if ( !converter ) { continue; } // strip the prefix/suffix from the GA_Attribute name std::string attrName = aIt->first.value(); size_t prefixLength = attributePrefix.length(); if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) ) { attrName.erase( attrName.begin(), attrName.begin() + prefixLength ); } size_t suffixLength = attributeSuffix.length(); if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) ) { attrName.erase( attrName.end() - suffixLength, attrName.end() ); } if ( attrName == "P" ) { const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data ); if ( !positions ) { continue; } size_t index = 0; size_t entries = pointRange.getEntries(); const std::vector<Imath::V3f> &pos = positions->readable(); // Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves. // As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive // will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and // last two V3fs. In all other cases, we report a warning and don't apply the cache to these points. if ( pos.size() - 4 == entries ) { index = 2; } else if ( pos.size() != entries ) { addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() ); continue; } for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index ) { gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) ); } } else { converter->convert( attrName, gdp, pointRange ); } } // if transformAttribute is specified, use to to transform the points if ( transformAttribute != "" ) { const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute ); if ( transform ) { transformPoints<double>( transform->readable(), pointRange ); } else { const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute ); if ( transform ) { transformPoints<float>( transform->readable(), pointRange ); } } } } unlockInputs(); return error(); } template<typename T> void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range ) { UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() ); for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it ) { UT_Vector3 pos = gdp->getPos3( it.getOffset() ); pos *= matrix; gdp->setPos3( it.getOffset(), pos ); } } <commit_msg>simplified logic and added threading todos<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2012, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/format.hpp" #include "OP/OP_Director.h" #include "PRM/PRM_Default.h" #include "PRM/PRM_Template.h" #include "IECore/CompoundObject.h" #include "IECore/TransformationMatrixData.h" #include "IECore/VectorTypedData.h" #include "Convert.h" #include "ToHoudiniAttribConverter.h" #include "SOP_InterpolatedCacheReader.h" using namespace IECore; using namespace IECoreHoudini; static PRM_Name parameterNames[] = { PRM_Name( "cacheSequence", "Cache Sequence" ), PRM_Name( "objectFixes", "Object Prefix/Suffix" ), PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ), PRM_Name( "transformAttribute", "Transform Attribute" ), PRM_Name( "frameMultiplier", "Frame Multiplier" ), }; static PRM_Default frameMultiplierDefault( 1 ); PRM_Template SOP_InterpolatedCacheReader::parameters[] = { PRM_Template( PRM_FILE, 1, &parameterNames[0] ), PRM_Template( PRM_STRING, 2, &parameterNames[1] ), PRM_Template( PRM_STRING, 2, &parameterNames[2] ), PRM_Template( PRM_STRING, 1, &parameterNames[3] ), PRM_Template( PRM_INT, 1, &parameterNames[4], &frameMultiplierDefault ), PRM_Template(), }; SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op ) : SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 ) { flags().setTimeDep( true ); } SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader() { } OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op ) { return new SOP_InterpolatedCacheReader( net, name, op ); } OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context ) { flags().setTimeDep( true ); if ( lockInputs( context ) >= UT_ERROR_ABORT ) { return error(); } gdp->stashAll(); float time = context.getTime(); float frame = context.getFloatFrame(); UT_String paramVal; evalString( paramVal, "cacheSequence", 0, time ); std::string cacheFileName = paramVal.toStdString(); evalString( paramVal, "objectFixes", 0, time ); std::string objectPrefix = paramVal.toStdString(); evalString( paramVal, "objectFixes", 1, time ); std::string objectSuffix = paramVal.toStdString(); evalString( paramVal, "attributeFixes", 0, time ); std::string attributePrefix = paramVal.toStdString(); evalString( paramVal, "attributeFixes", 1, time ); std::string attributeSuffix = paramVal.toStdString(); evalString( paramVal, "transformAttribute", 0, time ); std::string transformAttribute = paramVal.toStdString(); int frameMultiplier = evalInt( "frameMultiplier", 0, time ); // create the InterpolatedCache if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier ) { try { float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec(); OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier ); m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc ); } catch ( IECore::InvalidArgumentException e ) { addWarning( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } m_cacheFileName = cacheFileName; m_frameMultiplier = frameMultiplier; } if ( !m_cache ) { addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" ); unlockInputs(); return error(); } std::vector<InterpolatedCache::ObjectHandle> objects; std::vector<InterpolatedCache::AttributeHandle> attrs; try { m_cache->objects( frame, objects ); } catch ( IECore::Exception e ) { addWarning( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } duplicatePointSource( 0, context ); for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it ) { GA_PointGroup *group = (GA_PointGroup*)it.group(); if ( group->getInternal() || group->isEmpty() ) { continue; } // match GA_PointGroup name to InterpolatedCache::ObjectHandle std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix; std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName ); if ( oIt == objects.end() ) { continue; } CompoundObjectPtr attributes = 0; try { m_cache->attributes( frame, *oIt, attrs ); attributes = m_cache->read( frame, *oIt ); } catch ( IECore::Exception e ) { addError( SOP_ATTRIBUTE_INVALID, e.what() ); unlockInputs(); return error(); } const CompoundObject::ObjectMap &attributeMap = attributes->members(); GA_Range pointRange = gdp->getPointRange( group ); // transfer the InterpolatedCache::Attributes onto the GA_PointGroup /// \todo: this does not account for detail, prim, or vertex attribs... for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ ) { const Data *data = IECore::runTimeCast<const Data>( aIt->second ); if ( !data ) { continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data ); if ( !converter ) { continue; } // strip the prefix/suffix from the GA_Attribute name std::string attrName = aIt->first.value(); size_t prefixLength = attributePrefix.length(); if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) ) { attrName.erase( attrName.begin(), attrName.begin() + prefixLength ); } size_t suffixLength = attributeSuffix.length(); if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) ) { attrName.erase( attrName.end() - suffixLength, attrName.end() ); } if ( attrName == "P" ) { const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data ); if ( !positions ) { continue; } size_t index = 0; size_t entries = pointRange.getEntries(); const std::vector<Imath::V3f> &pos = positions->readable(); // Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves. // As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive // will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and // last two V3fs. In all other cases, we report a warning and don't apply the cache to these points. if ( pos.size() - 4 == entries ) { index = 2; } else if ( pos.size() != entries ) { addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() ); continue; } /// \todo: try multi-threading this with a GA_SplittableRange for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index ) { gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) ); } } else { converter->convert( attrName, gdp, pointRange ); } } // if transformAttribute is specified, use to to transform the points if ( transformAttribute != "" ) { const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute ); if ( transform ) { transformPoints<double>( transform->readable(), pointRange ); } else { const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute ); if ( transform ) { transformPoints<float>( transform->readable(), pointRange ); } } } } unlockInputs(); return error(); } template<typename T> void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range ) { UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() ); /// \todo: try multi-threading this with a GA_SplittableRange for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it ) { gdp->setPos3( it.getOffset(), gdp->getPos3( it.getOffset() ) * matrix ); } } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2014 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Teapotnet. * * * * Teapotnet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Teapotnet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Teapotnet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/store.hpp" #include "tpn/config.hpp" #include "tpn/network.hpp" #include "tpn/cache.hpp" #include "tpn/block.hpp" #include "pla/directory.hpp" #include "pla/crypto.hpp" namespace tpn { Store *Store::Instance = NULL; BinaryString Store::Hash(const String &str) { return Sha256().compute(str); } Store::Store(void) : mRunning(false) { mDatabase = new Database("store.db"); mDatabase->execute("CREATE TABLE IF NOT EXISTS blocks\ (id INTEGER PRIMARY KEY AUTOINCREMENT,\ digest BLOB,\ file_id INTEGER,\ offset INTEGER(8),\ size INTEGER(8))"); mDatabase->execute("CREATE INDEX IF NOT EXISTS digest ON blocks (digest)"); mDatabase->execute("CREATE UNIQUE INDEX IF NOT EXISTS location ON blocks (file_id, offset)"); mDatabase->execute("CREATE TABLE IF NOT EXISTS files\ (id INTEGER PRIMARY KEY AUTOINCREMENT,\ name TEXT UNIQUE)"); mDatabase->execute("CREATE INDEX IF NOT EXISTS name ON files (name)"); mDatabase->execute("CREATE TABLE IF NOT EXISTS map\ (key BLOB,\ value BLOB,\ time INTEGER(8),\ type INTEGER(1))"); mDatabase->execute("CREATE UNIQUE INDEX IF NOT EXISTS pair ON map (key, value)"); } Store::~Store(void) { } bool Store::push(const BinaryString &digest, Fountain::Combination &input) { std::unique_lock<std::mutex> lock(mMutex); if(hasBlock(digest)) return true; Fountain::Sink &sink = mSinks[digest]; sink.solve(input); if(!sink.isDecoded()) return false; BinaryString sinkDigest; sink.hash(sinkDigest); LogDebug("Store::pu.hpp", "Block is complete, digest is " + sinkDigest.toString()); if(sinkDigest != digest) { LogWarn("Store::pu.hpp", "Block digest is invalid (expected " + digest.toString() + ")"); mSinks.erase(digest); return false; } String path = Cache::Instance->path(digest); File file(path, File::Write); int64_t size = sink.dump(file); file.close(); notifyBlock(digest, path, 0, size); mSinks.erase(digest); return true; } bool Store::pull(const BinaryString &digest, Fountain::Combination &output, unsigned *rank) { std::unique_lock<std::mutex> lock(mMutex); int64_t size; File *file = getBlock(digest, size); if(!file) return false; Fountain::FileSource source(file, file->tellRead(), size); source.generate(output); if(rank) *rank = source.rank(); return true; } unsigned Store::missing(const BinaryString &digest) { std::unique_lock<std::mutex> lock(mMutex); Map<BinaryString,Fountain::Sink>::iterator it = mSinks.find(digest); if(it != mSinks.end()) return it->second.missing(); else return uint16_t(-1); } bool Store::hasBlock(const BinaryString &digest) { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("SELECT 1 FROM blocks WHERE digest = ?1"); statement.bind(1, digest); if(statement.step()) { statement.finalize(); return true; } statement.finalize(); return false; } void Store::waitBlock(const BinaryString &digest, const BinaryString &hint) { const duration timeout = milliseconds(Config::Get("request_timeout").toDouble())*2; if(!waitBlock(digest, timeout, hint)) throw Timeout(); } bool Store::waitBlock(const BinaryString &digest, duration timeout, const BinaryString &hint) { if(!hasBlock(digest)) { Network::Caller caller(digest, hint); // Block is missing locally, call it LogDebug("Store::waitBlock", "Waiting for block: " + digest.toString()); { std::unique_lock<std::mutex> lock(mMutex); mCondition.wait_for(lock, timeout, [this, digest]() { return hasBlock(digest); }); if(!hasBlock(digest)) return false; } LogDebug("Store::waitBlock", "Block is now available: " + digest.toString()); } return true; } File *Store::getBlock(const BinaryString &digest, int64_t &size) { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("SELECT f.name, b.offset, b.size FROM blocks b LEFT JOIN files f ON f.id = b.file_id WHERE b.digest = ?1 LIMIT 1"); statement.bind(1, digest); if(statement.step()) { String filename; int64_t offset; statement.value(0, filename); statement.value(1, offset); statement.value(2, size); statement.finalize(); try { File *file = new File(filename); file->seekRead(offset); return file; } catch(...) { notifyFileErasure(filename); } return NULL; } statement.finalize(); return NULL; } void Store::notifyBlock(const BinaryString &digest, const String &filename, int64_t offset, int64_t size) { //LogDebug("Store::notifyBlock", "Block notified: " + digest.toString()); { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("INSERT OR IGNORE INTO files (name) VALUES (?1)"); statement.bind(1, filename); statement.execute(); statement = mDatabase->prepare("INSERT OR REPLACE INTO blocks (file_id, digest, offset, size) VALUES ((SELECT id FROM files WHERE name = ?1 LIMIT 1), ?2, ?3, ?4)"); statement.bind(1, filename); statement.bind(2, digest); statement.bind(3, offset); statement.bind(4, size); statement.execute(); } mCondition.notify_all(); // Publish into DHT Network::Instance->storeValue(digest, Network::Instance->overlay()->localNode()); } void Store::notifyFileErasure(const String &filename) { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("DELETE FROM blocks WHERE file_id = (SELECT id FROM files WHERE name = ?1)"); statement.bind(1, filename); statement.execute(); statement = mDatabase->prepare("DELETE FROM files WHERE name = ?1"); statement.bind(1, filename); statement.execute(); } void Store::storeValue(const BinaryString &key, const BinaryString &value, Store::ValueType type) { std::unique_lock<std::mutex> lock(mMutex); if(type == Permanent) { Database::Statement statement = mDatabase->prepare("DELETE FROM map WHERE key = ?1 AND type = ?2"); statement.bind(1, key); statement.bind(2, static_cast<int>(Permanent)); statement.execute(); } auto secs = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); Database::Statement statement = mDatabase->prepare("INSERT OR REPLACE INTO map (key, value, time, type) VALUES (?1, ?2, ?3, ?4)"); statement.bind(1, key); statement.bind(2, value); statement.bind(3, secs); statement.bind(4, static_cast<int>(type)); statement.execute(); } bool Store::retrieveValue(const BinaryString &key, Set<BinaryString> &values) { Identifier localNode = Network::Instance->overlay()->localNode(); std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("SELECT value FROM map WHERE key = ?1"); statement.bind(1, key); while(statement.step()) { BinaryString v; statement.value(0, v); values.insert(v); } statement.finalize(); // Also look for digest in blocks in case map is not up-to-date statement = mDatabase->prepare("SELECT 1 FROM blocks WHERE digest = ?1 LIMIT 1"); statement.bind(1, key); if(statement.step()) values.insert(localNode); statement.finalize(); return !values.empty(); } bool Store::hasValue(const BinaryString &key, const BinaryString &value) const { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("SELECT 1 FROM map WHERE key = ?1 AND value = ?2 LIMIT 1"); statement.bind(1, key); statement.bind(2, value); bool found = statement.step(); statement.finalize(); return found; } Time Store::getValueTime(const BinaryString &key, const BinaryString &value) const { std::unique_lock<std::mutex> lock(mMutex); Database::Statement statement = mDatabase->prepare("SELECT time FROM map WHERE key = ?1 AND value = ?2 LIMIT 1"); statement.bind(1, key); statement.bind(2, value); Time time(0); if(statement.step()) statement.value(0, time); statement.finalize(); return time; } void Store::start(void) { std::unique_lock<std::mutex> lock(mMutex); if(mRunning) return; mRunning = true; std::thread thread([this]() { run(); }); thread.detach(); } void Store::run(void) { { std::unique_lock<std::mutex> lock(mMutex); if(mRunning) return; mRunning = true; } const duration maxAge = seconds(Config::Get("store_max_age").toDouble()); const duration delay = seconds(1.); // TODO const int batch = 10; // TODO LogDebug("Store::run", "Started"); try { BinaryString node = Network::Instance->overlay()->localNode(); auto secs = std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() - maxAge).time_since_epoch()).count(); // Delete old non-permanent values Database::Statement statement = mDatabase->prepare("DELETE FROM map WHERE type != ?1 AND time < ?2"); statement.bind(1, static_cast<int>(Permanent)); statement.bind(2, secs); statement.execute(); // Publish everything into DHT periodically int offset = 0; while(true) { if(Network::Instance->overlay()->connectionsCount() == 0) { LogDebug("Store::run", "Interrupted"); return; } // Select DHT values Database::Statement statement = mDatabase->prepare("SELECT digest FROM blocks WHERE digest IS NOT NULL ORDER BY id DESC LIMIT ?1 OFFSET ?2"); statement.bind(1, batch); statement.bind(2, offset); List<BinaryString> result; statement.fetchColumn(0, result); statement.finalize(); if(result.empty()) break; else { for(List<BinaryString>::iterator it = result.begin(); it != result.end(); ++it) Network::Instance->storeValue(*it, node); std::this_thread::sleep_for(delay); } offset+= result.size(); } LogDebug("Store::run", "Finished, " + String::number(offset) + " values published"); } catch(const std::exception &e) { LogWarn("Store::run", e.what()); } { std::unique_lock<std::mutex> lock(mMutex); mRunning = false; // Store is scheduled by Overlay on first connection // TODO //Scheduler::Global->schedule(this, maxAge/2); } } } <commit_msg>Fixed Store synchronization<commit_after>/************************************************************************* * Copyright (C) 2011-2014 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Teapotnet. * * * * Teapotnet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Teapotnet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Teapotnet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/store.hpp" #include "tpn/config.hpp" #include "tpn/network.hpp" #include "tpn/cache.hpp" #include "tpn/block.hpp" #include "pla/directory.hpp" #include "pla/crypto.hpp" namespace tpn { Store *Store::Instance = NULL; BinaryString Store::Hash(const String &str) { return Sha256().compute(str); } Store::Store(void) : mRunning(false) { mDatabase = new Database("store.db"); mDatabase->execute("CREATE TABLE IF NOT EXISTS blocks\ (id INTEGER PRIMARY KEY AUTOINCREMENT,\ digest BLOB,\ file_id INTEGER,\ offset INTEGER(8),\ size INTEGER(8))"); mDatabase->execute("CREATE INDEX IF NOT EXISTS digest ON blocks (digest)"); mDatabase->execute("CREATE UNIQUE INDEX IF NOT EXISTS location ON blocks (file_id, offset)"); mDatabase->execute("CREATE TABLE IF NOT EXISTS files\ (id INTEGER PRIMARY KEY AUTOINCREMENT,\ name TEXT UNIQUE)"); mDatabase->execute("CREATE INDEX IF NOT EXISTS name ON files (name)"); mDatabase->execute("CREATE TABLE IF NOT EXISTS map\ (key BLOB,\ value BLOB,\ time INTEGER(8),\ type INTEGER(1))"); mDatabase->execute("CREATE UNIQUE INDEX IF NOT EXISTS pair ON map (key, value)"); } Store::~Store(void) { } bool Store::push(const BinaryString &digest, Fountain::Combination &input) { // TODO: sinks should be independant std::unique_lock<std::mutex> lock(mMutex); if(hasBlock(digest)) return true; Fountain::Sink &sink = mSinks[digest]; sink.solve(input); if(!sink.isDecoded()) return false; BinaryString sinkDigest; sink.hash(sinkDigest); LogDebug("Store::pu.hpp", "Block is complete, digest is " + sinkDigest.toString()); if(sinkDigest != digest) { LogWarn("Store::pu.hpp", "Block digest is invalid (expected " + digest.toString() + ")"); mSinks.erase(digest); return false; } String path = Cache::Instance->path(digest); File file(path, File::Write); int64_t size = sink.dump(file); file.close(); mSinks.erase(digest); notifyBlock(digest, path, 0, size); return true; } bool Store::pull(const BinaryString &digest, Fountain::Combination &output, unsigned *rank) { std::unique_lock<std::mutex> lock(mMutex); int64_t size; File *file = getBlock(digest, size); if(!file) return false; Fountain::FileSource source(file, file->tellRead(), size); source.generate(output); if(rank) *rank = source.rank(); return true; } unsigned Store::missing(const BinaryString &digest) { std::unique_lock<std::mutex> lock(mMutex); Map<BinaryString,Fountain::Sink>::iterator it = mSinks.find(digest); if(it != mSinks.end()) return it->second.missing(); else return uint16_t(-1); } bool Store::hasBlock(const BinaryString &digest) { Database::Statement statement = mDatabase->prepare("SELECT 1 FROM blocks WHERE digest = ?1"); statement.bind(1, digest); if(statement.step()) { statement.finalize(); return true; } statement.finalize(); return false; } void Store::waitBlock(const BinaryString &digest, const BinaryString &hint) { const duration timeout = milliseconds(Config::Get("request_timeout").toDouble())*2; if(!waitBlock(digest, timeout, hint)) throw Timeout(); } bool Store::waitBlock(const BinaryString &digest, duration timeout, const BinaryString &hint) { if(!hasBlock(digest)) { Network::Caller caller(digest, hint); // Block is missing locally, call it LogDebug("Store::waitBlock", "Waiting for block: " + digest.toString()); { std::unique_lock<std::mutex> lock(mMutex); mCondition.wait_for(lock, timeout, [this, digest]() { return hasBlock(digest); }); if(!hasBlock(digest)) return false; } LogDebug("Store::waitBlock", "Block is now available: " + digest.toString()); } return true; } File *Store::getBlock(const BinaryString &digest, int64_t &size) { Database::Statement statement = mDatabase->prepare("SELECT f.name, b.offset, b.size FROM blocks b LEFT JOIN files f ON f.id = b.file_id WHERE b.digest = ?1 LIMIT 1"); statement.bind(1, digest); if(statement.step()) { String filename; int64_t offset; statement.value(0, filename); statement.value(1, offset); statement.value(2, size); statement.finalize(); try { File *file = new File(filename); file->seekRead(offset); return file; } catch(...) { notifyFileErasure(filename); } return NULL; } statement.finalize(); return NULL; } void Store::notifyBlock(const BinaryString &digest, const String &filename, int64_t offset, int64_t size) { //LogDebug("Store::notifyBlock", "Block notified: " + digest.toString()); Database::Statement statement = mDatabase->prepare("INSERT OR IGNORE INTO files (name) VALUES (?1)"); statement.bind(1, filename); statement.execute(); statement = mDatabase->prepare("INSERT OR REPLACE INTO blocks (file_id, digest, offset, size) VALUES ((SELECT id FROM files WHERE name = ?1 LIMIT 1), ?2, ?3, ?4)"); statement.bind(1, filename); statement.bind(2, digest); statement.bind(3, offset); statement.bind(4, size); statement.execute(); mCondition.notify_all(); // Publish into DHT Network::Instance->storeValue(digest, Network::Instance->overlay()->localNode()); } void Store::notifyFileErasure(const String &filename) { Database::Statement statement = mDatabase->prepare("DELETE FROM blocks WHERE file_id = (SELECT id FROM files WHERE name = ?1)"); statement.bind(1, filename); statement.execute(); statement = mDatabase->prepare("DELETE FROM files WHERE name = ?1"); statement.bind(1, filename); statement.execute(); } void Store::storeValue(const BinaryString &key, const BinaryString &value, Store::ValueType type) { if(type == Permanent) { Database::Statement statement = mDatabase->prepare("DELETE FROM map WHERE key = ?1 AND type = ?2"); statement.bind(1, key); statement.bind(2, static_cast<int>(Permanent)); statement.execute(); } auto secs = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); Database::Statement statement = mDatabase->prepare("INSERT OR REPLACE INTO map (key, value, time, type) VALUES (?1, ?2, ?3, ?4)"); statement.bind(1, key); statement.bind(2, value); statement.bind(3, secs); statement.bind(4, static_cast<int>(type)); statement.execute(); } bool Store::retrieveValue(const BinaryString &key, Set<BinaryString> &values) { Identifier localNode = Network::Instance->overlay()->localNode(); Database::Statement statement = mDatabase->prepare("SELECT value FROM map WHERE key = ?1"); statement.bind(1, key); while(statement.step()) { BinaryString v; statement.value(0, v); values.insert(v); } statement.finalize(); // Also look for digest in blocks in case map is not up-to-date statement = mDatabase->prepare("SELECT 1 FROM blocks WHERE digest = ?1 LIMIT 1"); statement.bind(1, key); if(statement.step()) values.insert(localNode); statement.finalize(); return !values.empty(); } bool Store::hasValue(const BinaryString &key, const BinaryString &value) const { Database::Statement statement = mDatabase->prepare("SELECT 1 FROM map WHERE key = ?1 AND value = ?2 LIMIT 1"); statement.bind(1, key); statement.bind(2, value); bool found = statement.step(); statement.finalize(); return found; } Time Store::getValueTime(const BinaryString &key, const BinaryString &value) const { Database::Statement statement = mDatabase->prepare("SELECT time FROM map WHERE key = ?1 AND value = ?2 LIMIT 1"); statement.bind(1, key); statement.bind(2, value); Time time(0); if(statement.step()) statement.value(0, time); statement.finalize(); return time; } void Store::start(void) { std::unique_lock<std::mutex> lock(mMutex); if(mRunning) return; mRunning = true; std::thread thread([this]() { run(); }); thread.detach(); } void Store::run(void) { const duration maxAge = seconds(Config::Get("store_max_age").toDouble()); const duration delay = seconds(1.); // TODO const int batch = 10; // TODO LogDebug("Store::run", "Started"); try { BinaryString node = Network::Instance->overlay()->localNode(); auto secs = std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() - maxAge).time_since_epoch()).count(); // Delete old non-permanent values Database::Statement statement = mDatabase->prepare("DELETE FROM map WHERE type != ?1 AND time < ?2"); statement.bind(1, static_cast<int>(Permanent)); statement.bind(2, secs); statement.execute(); // Publish everything into DHT periodically int offset = 0; while(true) { if(Network::Instance->overlay()->connectionsCount() == 0) { LogDebug("Store::run", "Interrupted"); return; } // Select DHT values Database::Statement statement = mDatabase->prepare("SELECT digest FROM blocks WHERE digest IS NOT NULL ORDER BY id DESC LIMIT ?1 OFFSET ?2"); statement.bind(1, batch); statement.bind(2, offset); List<BinaryString> result; statement.fetchColumn(0, result); statement.finalize(); if(result.empty()) break; else { for(List<BinaryString>::iterator it = result.begin(); it != result.end(); ++it) Network::Instance->storeValue(*it, node); std::this_thread::sleep_for(delay); } offset+= result.size(); } LogDebug("Store::run", "Finished, " + String::number(offset) + " values published"); } catch(const std::exception &e) { LogWarn("Store::run", e.what()); } { std::unique_lock<std::mutex> lock(mMutex); mRunning = false; // Store is scheduled by Overlay on first connection // TODO //Scheduler::Global->schedule(this, maxAge/2); } } } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 // rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // <h1>Reduced Basis Example 1 - Certified Reduced Basis Method</h1> // \author David Knezevic // \date 2010 // // In this example problem we use the Certified Reduced Basis method // to solve a steady convection-diffusion problem on the unit square. // The reduced basis method relies on an expansion of the PDE in the // form \sum_q=1^Q_a theta_a^q(\mu) * a^q(u,v) = \sum_q=1^Q_f // theta_f^q(\mu) f^q(v) where theta_a, theta_f are parameter // dependent functions and a^q, f^q are parameter independent // operators (\mu denotes a parameter). // // We first attach the parameter dependent functions and parameter // independent operators to the RBSystem. Then in Offline mode, a // reduced basis space is generated and written out to the directory // "offline_data". In Online mode, the reduced basis data in // "offline_data" is read in and used to solve the reduced problem for // the parameters specified in reduced_basis_ex1.in. // // We also attach four outputs to the system which are averages over // certain subregions of the domain. In Online mode, we print out the // values of these outputs as well as rigorous error bounds with // respect to the output associated with the "truth" finite element // discretization. // C++ include files that we need #include <iostream> #include <algorithm> #include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC #include <cmath> #include <set> // Basic include file needed for the mesh functionality. #include "libmesh/libmesh.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/exodusII_io.h" #include "libmesh/equation_systems.h" #include "libmesh/dof_map.h" #include "libmesh/getpot.h" #include "libmesh/elem.h" #include "libmesh/rb_data_serialization.h" #include "libmesh/rb_data_deserialization.h" #include "libmesh/enum_solver_package.h" // local includes #include "rb_classes.h" #include "assembly.h" // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char ** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); // This example requires a linear solver package. libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE, "--enable-petsc, --enable-trilinos, or --enable-eigen"); #if !defined(LIBMESH_HAVE_XDR) // We need XDR support to write out reduced bases libmesh_example_requires(false, "--enable-xdr"); #elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION) // XDR binary support requires double precision libmesh_example_requires(false, "--disable-singleprecision"); #endif // FIXME: This example currently segfaults with Trilinos? It works // with PETSc and Eigen sparse linear solvers though. libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc"); // Skip this 2D example if libMesh was compiled as 1D-only. libmesh_example_requires(2 <= LIBMESH_DIM, "2D support"); #ifndef LIBMESH_ENABLE_DIRICHLET libmesh_example_requires(false, "--enable-dirichlet"); #else // Parse the input file (reduced_basis_ex1.in) using GetPot std::string parameters_filename = "reduced_basis_ex1.in"; GetPot infile(parameters_filename); unsigned int n_elem = infile("n_elem", 1); // Determines the number of elements in the "truth" mesh const unsigned int dim = 2; // The number of spatial dimensions bool store_basis_functions = infile("store_basis_functions", true); // Do we write the RB basis functions to disk? // Read the "online_mode" flag from the command line GetPot command_line (argc, argv); int online_mode = 0; if (command_line.search(1, "-online_mode")) online_mode = command_line.next(online_mode); int use_POD_training = 0; if (command_line.search(1, "-use_POD_training")) use_POD_training = command_line.next(use_POD_training); // Build a mesh on the default MPI communicator. Mesh mesh (init.comm(), dim); MeshTools::Generation::build_square (mesh, n_elem, n_elem, 0., 1., 0., 1., QUAD4); // Create an equation systems object. EquationSystems equation_systems (mesh); // We override RBConstruction with SimpleRBConstruction in order to // specialize a few functions for this particular problem. SimpleRBConstruction & rb_con = equation_systems.add_system<SimpleRBConstruction> ("RBConvectionDiffusion"); // Initialize the data structures for the equation system. equation_systems.init (); // Print out some information about the "truth" discretization equation_systems.print_info(); mesh.print_info(); // Build a new RBEvaluation object which will be used to perform // Reduced Basis calculations. This is required in both the // "Offline" and "Online" stages. SimpleRBEvaluation rb_eval(mesh.comm()); // We need to give the RBConstruction object a pointer to // our RBEvaluation object rb_con.set_rb_evaluation(rb_eval); if (!online_mode) // Perform the Offline stage of the RB method { // Read in the data that defines this problem from the specified text file rb_con.process_parameters_file(parameters_filename); // Print out info that describes the current setup of rb_con rb_con.print_info(); // Prepare rb_con for the Construction stage of the RB method. // This sets up the necessary data structures and performs // initial assembly of the "truth" affine expansion of the PDE. rb_con.initialize_rb_construction(); // Compute the reduced basis space by computing "snapshots", i.e. // "truth" solves, at well-chosen parameter values and employing // these snapshots as basis functions. rb_con.train_reduced_basis(); // Write out the data that will subsequently be required for the Evaluation stage #if defined(LIBMESH_HAVE_CAPNPROTO) RBDataSerialization::RBEvaluationSerialization rb_eval_writer(rb_con.get_rb_evaluation()); rb_eval_writer.write_to_file("rb_eval.bin"); #else rb_con.get_rb_evaluation().legacy_write_offline_data_to_files(); #endif // If requested, write out the RB basis functions for visualization purposes if (store_basis_functions) { // Write out the basis functions rb_con.get_rb_evaluation().write_out_basis_functions(rb_con); } // Basis functions should be orthonormal, so // print out the inner products to check this rb_con.print_basis_function_orthogonality(); } else // Perform the Online stage of the RB method { // Read in the reduced basis data #if defined(LIBMESH_HAVE_CAPNPROTO) RBDataDeserialization::RBEvaluationDeserialization rb_eval_reader(rb_eval); rb_eval_reader.read_from_file("rb_eval.bin", /*read_error_bound_data*/ true); #else rb_eval.legacy_read_offline_data_from_files(); #endif // Read in online_N and initialize online parameters unsigned int online_N = infile("online_N", 1); Real online_x_vel = infile("online_x_vel", 0.); Real online_y_vel = infile("online_y_vel", 0.); RBParameters online_mu; online_mu.set_value("x_vel", online_x_vel); online_mu.set_value("y_vel", online_y_vel); rb_eval.set_parameters(online_mu); rb_eval.print_parameters(); // Now do the Online solve using the precomputed reduced basis rb_eval.rb_solve(online_N); // Print out outputs as well as the corresponding output error bounds. libMesh::out << "output 1, value = " << rb_eval.RB_outputs[0] << ", bound = " << rb_eval.RB_output_error_bounds[0] << std::endl; libMesh::out << "output 2, value = " << rb_eval.RB_outputs[1] << ", bound = " << rb_eval.RB_output_error_bounds[1] << std::endl; libMesh::out << "output 3, value = " << rb_eval.RB_outputs[2] << ", bound = " << rb_eval.RB_output_error_bounds[2] << std::endl; libMesh::out << "output 4, value = " << rb_eval.RB_outputs[3] << ", bound = " << rb_eval.RB_output_error_bounds[3] << std::endl << std::endl; if (store_basis_functions) { // Read in the basis functions rb_eval.read_in_basis_functions(rb_con); // Plot the solution rb_con.load_rb_solution(); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("RB_sol.e", equation_systems); #endif // Plot the first basis function that was generated from the train_reduced_basis // call in the Offline stage rb_con.load_basis_function(0); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("bf0.e", equation_systems); #endif } } #endif // LIBMESH_ENABLE_DIRICHLET return 0; } <commit_msg>Removed unused code from reduced_basis_ex1<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 // rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // <h1>Reduced Basis Example 1 - Certified Reduced Basis Method</h1> // \author David Knezevic // \date 2010 // // In this example problem we use the Certified Reduced Basis method // to solve a steady convection-diffusion problem on the unit square. // The reduced basis method relies on an expansion of the PDE in the // form \sum_q=1^Q_a theta_a^q(\mu) * a^q(u,v) = \sum_q=1^Q_f // theta_f^q(\mu) f^q(v) where theta_a, theta_f are parameter // dependent functions and a^q, f^q are parameter independent // operators (\mu denotes a parameter). // // We first attach the parameter dependent functions and parameter // independent operators to the RBSystem. Then in Offline mode, a // reduced basis space is generated and written out to the directory // "offline_data". In Online mode, the reduced basis data in // "offline_data" is read in and used to solve the reduced problem for // the parameters specified in reduced_basis_ex1.in. // // We also attach four outputs to the system which are averages over // certain subregions of the domain. In Online mode, we print out the // values of these outputs as well as rigorous error bounds with // respect to the output associated with the "truth" finite element // discretization. // C++ include files that we need #include <iostream> #include <algorithm> #include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC #include <cmath> #include <set> // Basic include file needed for the mesh functionality. #include "libmesh/libmesh.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/exodusII_io.h" #include "libmesh/equation_systems.h" #include "libmesh/dof_map.h" #include "libmesh/getpot.h" #include "libmesh/elem.h" #include "libmesh/rb_data_serialization.h" #include "libmesh/rb_data_deserialization.h" #include "libmesh/enum_solver_package.h" // local includes #include "rb_classes.h" #include "assembly.h" // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char ** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); // This example requires a linear solver package. libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE, "--enable-petsc, --enable-trilinos, or --enable-eigen"); #if !defined(LIBMESH_HAVE_XDR) // We need XDR support to write out reduced bases libmesh_example_requires(false, "--enable-xdr"); #elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION) // XDR binary support requires double precision libmesh_example_requires(false, "--disable-singleprecision"); #endif // FIXME: This example currently segfaults with Trilinos? It works // with PETSc and Eigen sparse linear solvers though. libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc"); // Skip this 2D example if libMesh was compiled as 1D-only. libmesh_example_requires(2 <= LIBMESH_DIM, "2D support"); #ifndef LIBMESH_ENABLE_DIRICHLET libmesh_example_requires(false, "--enable-dirichlet"); #else // Parse the input file (reduced_basis_ex1.in) using GetPot std::string parameters_filename = "reduced_basis_ex1.in"; GetPot infile(parameters_filename); unsigned int n_elem = infile("n_elem", 1); // Determines the number of elements in the "truth" mesh const unsigned int dim = 2; // The number of spatial dimensions bool store_basis_functions = infile("store_basis_functions", true); // Do we write the RB basis functions to disk? // Read the "online_mode" flag from the command line GetPot command_line (argc, argv); int online_mode = 0; if (command_line.search(1, "-online_mode")) online_mode = command_line.next(online_mode); // Build a mesh on the default MPI communicator. Mesh mesh (init.comm(), dim); MeshTools::Generation::build_square (mesh, n_elem, n_elem, 0., 1., 0., 1., QUAD4); // Create an equation systems object. EquationSystems equation_systems (mesh); // We override RBConstruction with SimpleRBConstruction in order to // specialize a few functions for this particular problem. SimpleRBConstruction & rb_con = equation_systems.add_system<SimpleRBConstruction> ("RBConvectionDiffusion"); // Initialize the data structures for the equation system. equation_systems.init (); // Print out some information about the "truth" discretization equation_systems.print_info(); mesh.print_info(); // Build a new RBEvaluation object which will be used to perform // Reduced Basis calculations. This is required in both the // "Offline" and "Online" stages. SimpleRBEvaluation rb_eval(mesh.comm()); // We need to give the RBConstruction object a pointer to // our RBEvaluation object rb_con.set_rb_evaluation(rb_eval); if (!online_mode) // Perform the Offline stage of the RB method { // Read in the data that defines this problem from the specified text file rb_con.process_parameters_file(parameters_filename); // Print out info that describes the current setup of rb_con rb_con.print_info(); // Prepare rb_con for the Construction stage of the RB method. // This sets up the necessary data structures and performs // initial assembly of the "truth" affine expansion of the PDE. rb_con.initialize_rb_construction(); // Compute the reduced basis space by computing "snapshots", i.e. // "truth" solves, at well-chosen parameter values and employing // these snapshots as basis functions. rb_con.train_reduced_basis(); // Write out the data that will subsequently be required for the Evaluation stage #if defined(LIBMESH_HAVE_CAPNPROTO) RBDataSerialization::RBEvaluationSerialization rb_eval_writer(rb_con.get_rb_evaluation()); rb_eval_writer.write_to_file("rb_eval.bin"); #else rb_con.get_rb_evaluation().legacy_write_offline_data_to_files(); #endif // If requested, write out the RB basis functions for visualization purposes if (store_basis_functions) { // Write out the basis functions rb_con.get_rb_evaluation().write_out_basis_functions(rb_con); } // Basis functions should be orthonormal, so // print out the inner products to check this rb_con.print_basis_function_orthogonality(); } else // Perform the Online stage of the RB method { // Read in the reduced basis data #if defined(LIBMESH_HAVE_CAPNPROTO) RBDataDeserialization::RBEvaluationDeserialization rb_eval_reader(rb_eval); rb_eval_reader.read_from_file("rb_eval.bin", /*read_error_bound_data*/ true); #else rb_eval.legacy_read_offline_data_from_files(); #endif // Read in online_N and initialize online parameters unsigned int online_N = infile("online_N", 1); Real online_x_vel = infile("online_x_vel", 0.); Real online_y_vel = infile("online_y_vel", 0.); RBParameters online_mu; online_mu.set_value("x_vel", online_x_vel); online_mu.set_value("y_vel", online_y_vel); rb_eval.set_parameters(online_mu); rb_eval.print_parameters(); // Now do the Online solve using the precomputed reduced basis rb_eval.rb_solve(online_N); // Print out outputs as well as the corresponding output error bounds. libMesh::out << "output 1, value = " << rb_eval.RB_outputs[0] << ", bound = " << rb_eval.RB_output_error_bounds[0] << std::endl; libMesh::out << "output 2, value = " << rb_eval.RB_outputs[1] << ", bound = " << rb_eval.RB_output_error_bounds[1] << std::endl; libMesh::out << "output 3, value = " << rb_eval.RB_outputs[2] << ", bound = " << rb_eval.RB_output_error_bounds[2] << std::endl; libMesh::out << "output 4, value = " << rb_eval.RB_outputs[3] << ", bound = " << rb_eval.RB_output_error_bounds[3] << std::endl << std::endl; if (store_basis_functions) { // Read in the basis functions rb_eval.read_in_basis_functions(rb_con); // Plot the solution rb_con.load_rb_solution(); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("RB_sol.e", equation_systems); #endif // Plot the first basis function that was generated from the train_reduced_basis // call in the Offline stage rb_con.load_basis_function(0); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("bf0.e", equation_systems); #endif } } #endif // LIBMESH_ENABLE_DIRICHLET return 0; } <|endoftext|>
<commit_before>#include <limits> #include <fstream> #include <vector> #include <Eigen/Core> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/voxel_grid.h> #include <pcl/features/normal_3d.h> #include <pcl/features/fpfh.h> #include <pcl/registration/ia_ransac.h> class FeatureCloud { public: // A bit of shorthand typedef pcl::PointCloud<pcl::PointXYZ> PointCloud; typedef pcl::PointCloud<pcl::Normal> SurfaceNormals; typedef pcl::PointCloud<pcl::FPFHSignature33> LocalFeatures; typedef pcl::search::KdTree<pcl::PointXYZ> SearchMethod; FeatureCloud () : search_method_xyz_ (new SearchMethod), normal_radius_ (0.02f), feature_radius_ (0.02f) {} ~FeatureCloud () {} // Process the given cloud void setInputCloud (PointCloud::Ptr xyz) { xyz_ = xyz; processInput (); } // Load and process the cloud in the given PCD file void loadInputCloud (const std::string &pcd_file) { xyz_ = PointCloud::Ptr (new PointCloud); pcl::io::loadPCDFile (pcd_file, *xyz_); processInput (); } // Get a pointer to the cloud 3D points PointCloud::Ptr getPointCloud () const { return (xyz_); } // Get a pointer to the cloud of 3D surface normals SurfaceNormals::Ptr getSurfaceNormals () const { return (normals_); } // Get a pointer to the cloud of feature descriptors LocalFeatures::Ptr getLocalFeatures () const { return (features_); } protected: // Compute the surface normals and local features void processInput () { computeSurfaceNormals (); computeLocalFeatures (); } // Compute the surface normals void computeSurfaceNormals () { normals_ = SurfaceNormals::Ptr (new SurfaceNormals); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> norm_est; norm_est.setInputCloud (xyz_); norm_est.setSearchMethod (search_method_xyz_); norm_est.setRadiusSearch (normal_radius_); norm_est.compute (*normals_); } // Compute the local feature descriptors void computeLocalFeatures () { features_ = LocalFeatures::Ptr (new LocalFeatures); pcl::FPFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fpfh_est; fpfh_est.setInputCloud (xyz_); fpfh_est.setInputNormals (normals_); fpfh_est.setSearchMethod (search_method_xyz_); fpfh_est.setRadiusSearch (feature_radius_); fpfh_est.compute (*features_); } private: // Point cloud data PointCloud::Ptr xyz_; SurfaceNormals::Ptr normals_; LocalFeatures::Ptr features_; SearchMethod::Ptr search_method_xyz_; // Parameters float normal_radius_; float feature_radius_; }; class TemplateAlignment { public: // A struct for storing alignment results struct Result { float fitness_score; Eigen::Matrix4f final_transformation; EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; TemplateAlignment () : min_sample_distance_ (0.05f), max_correspondence_distance_ (0.01f*0.01f), nr_iterations_ (500) { // Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm sac_ia_.setMinSampleDistance (min_sample_distance_); sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_); sac_ia_.setMaximumIterations (nr_iterations_); } ~TemplateAlignment () {} // Set the given cloud as the target to which the templates will be aligned void setTargetCloud (FeatureCloud &target_cloud) { target_ = target_cloud; sac_ia_.setInputTarget (target_cloud.getPointCloud ()); sac_ia_.setTargetFeatures (target_cloud.getLocalFeatures ()); } // Add the given cloud to the list of template clouds void addTemplateCloud (FeatureCloud &template_cloud) { templates_.push_back (template_cloud); } // Align the given template cloud to the target specified by setTargetCloud () void align (FeatureCloud &template_cloud, TemplateAlignment::Result &result) { sac_ia_.setInputCloud (template_cloud.getPointCloud ()); sac_ia_.setSourceFeatures (template_cloud.getLocalFeatures ()); pcl::PointCloud<pcl::PointXYZ> registration_output; sac_ia_.align (registration_output); result.fitness_score = (float) sac_ia_.getFitnessScore (max_correspondence_distance_); result.final_transformation = sac_ia_.getFinalTransformation (); } // Align all of template clouds set by addTemplateCloud to the target specified by setTargetCloud () void alignAll (std::vector<TemplateAlignment::Result, Eigen::aligned_allocator<Result> > &results) { results.resize (templates_.size ()); for (size_t i = 0; i < templates_.size (); ++i) { align (templates_[i], results[i]); } } // Align all of template clouds to the target cloud to find the one with best alignment score int findBestAlignment (TemplateAlignment::Result &result) { // Align all of the templates to the target cloud std::vector<Result, Eigen::aligned_allocator<Result> > results; alignAll (results); // Find the template with the best (lowest) fitness score float lowest_score = std::numeric_limits<float>::infinity (); int best_template = 0; for (size_t i = 0; i < results.size (); ++i) { const Result &r = results[i]; if (r.fitness_score < lowest_score) { lowest_score = r.fitness_score; best_template = (int) i; } } // Output the best alignment result = results[best_template]; return (best_template); } private: // A list of template clouds and the target to which they will be aligned std::vector<FeatureCloud> templates_; FeatureCloud target_; // The Sample Consensus Initial Alignment (SAC-IA) registration routine and its parameters pcl::SampleConsensusInitialAlignment<pcl::PointXYZ, pcl::PointXYZ, pcl::FPFHSignature33> sac_ia_; float min_sample_distance_; float max_correspondence_distance_; int nr_iterations_; }; // Align a collection of object templates to a sample point cloud int main (int argc, char **argv) { if (argc < 3) { printf ("No target PCD file given!\n"); return (-1); } // Load the object templates specified in the object_templates.txt file std::vector<FeatureCloud> object_templates; std::ifstream input_stream (argv[1]); object_templates.resize (0); std::string pcd_filename; while (input_stream.good ()) { std::getline (input_stream, pcd_filename); if (pcd_filename.empty () || pcd_filename.at (0) == '#') // Skip blank lines or comments continue; FeatureCloud template_cloud; template_cloud.loadInputCloud (pcd_filename); object_templates.push_back (template_cloud); } input_stream.close (); // Load the target cloud PCD file pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[2], *cloud); // Preprocess the cloud by... // ...removing distant points const float depth_limit = 1.0; pcl::PassThrough<pcl::PointXYZ> pass; pass.setInputCloud (cloud); pass.setFilterFieldName ("z"); pass.setFilterLimits (0, depth_limit); pass.filter (*cloud); // ... and downsampling the point cloud const float voxel_grid_size = 0.005f; pcl::VoxelGrid<pcl::PointXYZ> vox_grid; vox_grid.setInputCloud (cloud); vox_grid.setLeafSize (voxel_grid_size, voxel_grid_size, voxel_grid_size); vox_grid.filter (*cloud); // Assign to the target FeatureCloud FeatureCloud target_cloud; target_cloud.setInputCloud (cloud); // Set the TemplateAlignment inputs TemplateAlignment template_align; for (size_t i = 0; i < object_templates.size (); ++i) { template_align.addTemplateCloud (object_templates[i]); } template_align.setTargetCloud (target_cloud); // Find the best template alignment TemplateAlignment::Result best_alignment; int best_index = template_align.findBestAlignment (best_alignment); const FeatureCloud &best_template = object_templates[best_index]; // Print the alignment fitness score (values less than 0.00002 are good) printf ("Best fitness score: %f\n", best_alignment.fitness_score); // Print the rotation matrix and translation vector Eigen::Matrix3f rotation = best_alignment.final_transformation.block<3,3>(0, 0); Eigen::Vector3f translation = best_alignment.final_transformation.block<3,1>(0, 3); printf ("\n"); printf (" | %6.3f %6.3f %6.3f | \n", rotation (0,0), rotation (0,1), rotation (0,2)); printf ("R = | %6.3f %6.3f %6.3f | \n", rotation (1,0), rotation (1,1), rotation (1,2)); printf (" | %6.3f %6.3f %6.3f | \n", rotation (2,0), rotation (2,1), rotation (2,2)); printf ("\n"); printf ("t = < %0.3f, %0.3f, %0.3f >\n", translation (0), translation (1), translation (2)); // Save the aligned template for visualization pcl::PointCloud<pcl::PointXYZ> transformed_cloud; pcl::transformPointCloud (*best_template.getPointCloud (), transformed_cloud, best_alignment.final_transformation); pcl::io::savePCDFileBinary ("output.pcd", transformed_cloud); return (0); } <commit_msg>fix for template_alignment (thanks Adnan)<commit_after>#include <limits> #include <fstream> #include <vector> #include <Eigen/Core> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/voxel_grid.h> #include <pcl/features/normal_3d.h> #include <pcl/features/fpfh.h> #include <pcl/registration/ia_ransac.h> class FeatureCloud { public: // A bit of shorthand typedef pcl::PointCloud<pcl::PointXYZ> PointCloud; typedef pcl::PointCloud<pcl::Normal> SurfaceNormals; typedef pcl::PointCloud<pcl::FPFHSignature33> LocalFeatures; typedef pcl::search::KdTree<pcl::PointXYZ> SearchMethod; FeatureCloud () : search_method_xyz_ (new SearchMethod), normal_radius_ (0.02f), feature_radius_ (0.02f) {} ~FeatureCloud () {} // Process the given cloud void setInputCloud (PointCloud::Ptr xyz) { xyz_ = xyz; processInput (); } // Load and process the cloud in the given PCD file void loadInputCloud (const std::string &pcd_file) { xyz_ = PointCloud::Ptr (new PointCloud); pcl::io::loadPCDFile (pcd_file, *xyz_); processInput (); } // Get a pointer to the cloud 3D points PointCloud::Ptr getPointCloud () const { return (xyz_); } // Get a pointer to the cloud of 3D surface normals SurfaceNormals::Ptr getSurfaceNormals () const { return (normals_); } // Get a pointer to the cloud of feature descriptors LocalFeatures::Ptr getLocalFeatures () const { return (features_); } protected: // Compute the surface normals and local features void processInput () { computeSurfaceNormals (); computeLocalFeatures (); } // Compute the surface normals void computeSurfaceNormals () { normals_ = SurfaceNormals::Ptr (new SurfaceNormals); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> norm_est; norm_est.setInputCloud (xyz_); norm_est.setSearchMethod (search_method_xyz_); norm_est.setRadiusSearch (normal_radius_); norm_est.compute (*normals_); } // Compute the local feature descriptors void computeLocalFeatures () { features_ = LocalFeatures::Ptr (new LocalFeatures); pcl::FPFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fpfh_est; fpfh_est.setInputCloud (xyz_); fpfh_est.setInputNormals (normals_); fpfh_est.setSearchMethod (search_method_xyz_); fpfh_est.setRadiusSearch (feature_radius_); fpfh_est.compute (*features_); } private: // Point cloud data PointCloud::Ptr xyz_; SurfaceNormals::Ptr normals_; LocalFeatures::Ptr features_; SearchMethod::Ptr search_method_xyz_; // Parameters float normal_radius_; float feature_radius_; }; class TemplateAlignment { public: // A struct for storing alignment results struct Result { float fitness_score; Eigen::Matrix4f final_transformation; EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; TemplateAlignment () : min_sample_distance_ (0.05f), max_correspondence_distance_ (0.01f*0.01f), nr_iterations_ (500) { // Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm sac_ia_.setMinSampleDistance (min_sample_distance_); sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_); sac_ia_.setMaximumIterations (nr_iterations_); } ~TemplateAlignment () {} // Set the given cloud as the target to which the templates will be aligned void setTargetCloud (FeatureCloud &target_cloud) { target_ = target_cloud; sac_ia_.setInputTarget (target_cloud.getPointCloud ()); sac_ia_.setTargetFeatures (target_cloud.getLocalFeatures ()); } // Add the given cloud to the list of template clouds void addTemplateCloud (FeatureCloud &template_cloud) { templates_.push_back (template_cloud); } // Align the given template cloud to the target specified by setTargetCloud () void align (FeatureCloud &template_cloud, TemplateAlignment::Result &result) { sac_ia_.setInputCloud (template_cloud.getPointCloud ()); sac_ia_.setSourceFeatures (template_cloud.getLocalFeatures ()); pcl::PointCloud<pcl::PointXYZ> registration_output; sac_ia_.align (registration_output); result.fitness_score = (float) sac_ia_.getFitnessScore (max_correspondence_distance_); result.final_transformation = sac_ia_.getFinalTransformation (); } // Align all of template clouds set by addTemplateCloud to the target specified by setTargetCloud () void alignAll (std::vector<TemplateAlignment::Result, Eigen::aligned_allocator<Result> > &results) { results.resize (templates_.size ()); for (size_t i = 0; i < templates_.size (); ++i) { align (templates_[i], results[i]); } } // Align all of template clouds to the target cloud to find the one with best alignment score int findBestAlignment (TemplateAlignment::Result &result) { // Align all of the templates to the target cloud std::vector<Result, Eigen::aligned_allocator<Result> > results; alignAll (results); // Find the template with the best (lowest) fitness score float lowest_score = std::numeric_limits<float>::infinity (); int best_template = 0; for (size_t i = 0; i < results.size (); ++i) { const Result &r = results[i]; if (r.fitness_score < lowest_score) { lowest_score = r.fitness_score; best_template = (int) i; } } // Output the best alignment result = results[best_template]; return (best_template); } private: // A list of template clouds and the target to which they will be aligned std::vector<FeatureCloud> templates_; FeatureCloud target_; // The Sample Consensus Initial Alignment (SAC-IA) registration routine and its parameters pcl::SampleConsensusInitialAlignment<pcl::PointXYZ, pcl::PointXYZ, pcl::FPFHSignature33> sac_ia_; float min_sample_distance_; float max_correspondence_distance_; int nr_iterations_; }; // Align a collection of object templates to a sample point cloud int main (int argc, char **argv) { if (argc < 3) { printf ("No target PCD file given!\n"); return (-1); } // Load the object templates specified in the object_templates.txt file std::vector<FeatureCloud> object_templates; std::ifstream input_stream (argv[1]); object_templates.resize (0); std::string pcd_filename; while (input_stream.good ()) { std::getline (input_stream, pcd_filename); if (pcd_filename.empty () || pcd_filename.at (0) == '#') // Skip blank lines or comments continue; FeatureCloud template_cloud; template_cloud.loadInputCloud (pcd_filename); object_templates.push_back (template_cloud); } input_stream.close (); // Load the target cloud PCD file pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[2], *cloud); // Preprocess the cloud by... // ...removing distant points const float depth_limit = 1.0; pcl::PassThrough<pcl::PointXYZ> pass; pass.setInputCloud (cloud); pass.setFilterFieldName ("z"); pass.setFilterLimits (0, depth_limit); pass.filter (*cloud); // ... and downsampling the point cloud const float voxel_grid_size = 0.005f; pcl::VoxelGrid<pcl::PointXYZ> vox_grid; vox_grid.setInputCloud (cloud); vox_grid.setLeafSize (voxel_grid_size, voxel_grid_size, voxel_grid_size); //vox_grid.filter (*cloud); // Please see this http://www.pcl-developers.org/Possible-problem-in-new-VoxelGrid-implementation-from-PCL-1-5-0-td5490361.html pcl::PointCloud<pcl::PointXYZ>::Ptr tempCloud (new pcl::PointCloud<pcl::PointXYZ>); vox_grid.filter (*tempCloud); cloud = tempCloud; // Assign to the target FeatureCloud FeatureCloud target_cloud; target_cloud.setInputCloud (cloud); // Set the TemplateAlignment inputs TemplateAlignment template_align; for (size_t i = 0; i < object_templates.size (); ++i) { template_align.addTemplateCloud (object_templates[i]); } template_align.setTargetCloud (target_cloud); // Find the best template alignment TemplateAlignment::Result best_alignment; int best_index = template_align.findBestAlignment (best_alignment); const FeatureCloud &best_template = object_templates[best_index]; // Print the alignment fitness score (values less than 0.00002 are good) printf ("Best fitness score: %f\n", best_alignment.fitness_score); // Print the rotation matrix and translation vector Eigen::Matrix3f rotation = best_alignment.final_transformation.block<3,3>(0, 0); Eigen::Vector3f translation = best_alignment.final_transformation.block<3,1>(0, 3); printf ("\n"); printf (" | %6.3f %6.3f %6.3f | \n", rotation (0,0), rotation (0,1), rotation (0,2)); printf ("R = | %6.3f %6.3f %6.3f | \n", rotation (1,0), rotation (1,1), rotation (1,2)); printf (" | %6.3f %6.3f %6.3f | \n", rotation (2,0), rotation (2,1), rotation (2,2)); printf ("\n"); printf ("t = < %0.3f, %0.3f, %0.3f >\n", translation (0), translation (1), translation (2)); // Save the aligned template for visualization pcl::PointCloud<pcl::PointXYZ> transformed_cloud; pcl::transformPointCloud (*best_template.getPointCloud (), transformed_cloud, best_alignment.final_transformation); pcl::io::savePCDFileBinary ("output.pcd", transformed_cloud); return (0); } <|endoftext|>
<commit_before>/* =========================================================================== Daemon GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Daemon Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ // sv_bot.c #include "server.h" /* ================== SV_BotAllocateClient ================== */ int SV_BotAllocateClient( void ) { int i; // Never use the first slot otherwise: if a bot connect before the first client game supposedly won't start int firstSlot = std::max( 1, sv_privateClients->integer ); client_t *cl; // find a free client slot which was occupied by a bot (doesn't matter which) for ( i = firstSlot, cl = svs.clients + firstSlot; i < sv_maxclients->integer; i++, cl++ ) { if ( cl->state == CS_FREE && cl->netchan.remoteAddress.type == NA_BOT ) { break; } } // find any free client slot if ( i == sv_maxclients->integer ) { for ( i = firstSlot, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) { if ( cl->state == CS_FREE ) { break; } } } if ( i >= sv_maxclients->integer ) { return -1; } cl->gentity = SV_GentityNum( i ); cl->gentity->s.number = i; cl->state = CS_ACTIVE; cl->lastPacketTime = svs.time; cl->netchan.remoteAddress.type = NA_BOT; cl->rate = 16384; return i; } /* ================== SV_BotFreeClient ================== */ void SV_BotFreeClient( int clientNum ) { client_t *cl; if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { Com_Error( ERR_DROP, "SV_BotFreeClient: bad clientNum: %i", clientNum ); } cl = &svs.clients[ clientNum ]; cl->state = CS_FREE; cl->name[ 0 ] = 0; } /* ================== SV_IsBot ================== */ bool SV_IsBot( const client_t* client ) { return client->netchan.remoteAddress.type == NA_BOT && client->state == CS_ACTIVE; } // // * * * BOT AI CODE IS BELOW THIS POINT * * * // /* ================== SV_BotGetConsoleMessage ================== */ int SV_BotGetConsoleMessage( int client, char *buf, int size ) { client_t *cl; int index; cl = &svs.clients[ client ]; cl->lastPacketTime = svs.time; if ( cl->reliableAcknowledge == cl->reliableSequence ) { return qfalse; } cl->reliableAcknowledge++; index = cl->reliableAcknowledge & ( MAX_RELIABLE_COMMANDS - 1 ); if ( !cl->reliableCommands[ index ][ 0 ] ) { return qfalse; } //Q_strncpyz( buf, cl->reliableCommands[index], size ); return qtrue; } <commit_msg>Simplify the bot client allocation logic<commit_after>/* =========================================================================== Daemon GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Daemon Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ // sv_bot.c #include "server.h" /* ================== SV_BotAllocateClient ================== */ int SV_BotAllocateClient( void ) { int i; for (i = std::max(1, sv_privateClients->integer); i < sv_maxclients->integer; i++) { if (svs.clients[i].state == CS_FREE) { break; } } if (i >= sv_maxclients->integer) { return -1; } client_t* cl = svs.clients + i; cl->gentity = SV_GentityNum(i); cl->gentity->s.number = i; cl->state = CS_ACTIVE; cl->lastPacketTime = svs.time; cl->netchan.remoteAddress.type = NA_BOT; cl->rate = 16384; return i; } /* ================== SV_BotFreeClient ================== */ void SV_BotFreeClient( int clientNum ) { client_t *cl; if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { Com_Error( ERR_DROP, "SV_BotFreeClient: bad clientNum: %i", clientNum ); } cl = &svs.clients[ clientNum ]; cl->state = CS_FREE; cl->name[ 0 ] = 0; } /* ================== SV_IsBot ================== */ bool SV_IsBot( const client_t* client ) { return client->netchan.remoteAddress.type == NA_BOT && client->state == CS_ACTIVE; } // // * * * BOT AI CODE IS BELOW THIS POINT * * * // /* ================== SV_BotGetConsoleMessage ================== */ int SV_BotGetConsoleMessage( int client, char *buf, int size ) { client_t *cl; int index; cl = &svs.clients[ client ]; cl->lastPacketTime = svs.time; if ( cl->reliableAcknowledge == cl->reliableSequence ) { return qfalse; } cl->reliableAcknowledge++; index = cl->reliableAcknowledge & ( MAX_RELIABLE_COMMANDS - 1 ); if ( !cl->reliableCommands[ index ][ 0 ] ) { return qfalse; } //Q_strncpyz( buf, cl->reliableCommands[index], size ); return qtrue; } <|endoftext|>
<commit_before>#include <rcc/rcc.h> #include <gpio/gpio.h> #include <interrupt/interrupt.h> #include <timer/timer.h> #include <os/time.h> #include <usb/usb.h> #include <usb/descriptor.h> #include "report_desc.h" #include "usb_strings.h" #include "configloader.h" #include "config.h" static uint32_t& reset_reason = *(uint32_t*)0x10000000; static bool do_reset_bootloader; static bool do_reset; void reset() { SCB.AIRCR = (0x5fa << 16) | (1 << 2); // SYSRESETREQ } void reset_bootloader() { reset_reason = 0xb007; reset(); } Configloader configloader(0x801f800); config_t config; auto dev_desc = device_desc(0x200, 0, 0, 0, 64, 0x1d50, 0x6080, 0x110, 1, 2, 3, 1); auto conf_desc = configuration_desc(1, 1, 0, 0xc0, 0, // HID interface. interface_desc(0, 0, 1, 0x03, 0x00, 0x00, 0, hid_desc(0x111, 0, 1, 0x22, sizeof(report_desc)), endpoint_desc(0x81, 0x03, 16, 1) ) ); desc_t dev_desc_p = {sizeof(dev_desc), (void*)&dev_desc}; desc_t conf_desc_p = {sizeof(conf_desc), (void*)&conf_desc}; desc_t report_desc_p = {sizeof(report_desc), (void*)&report_desc}; static Pin usb_dm = GPIOA[11]; static Pin usb_dp = GPIOA[12]; static Pin usb_pu = GPIOA[15]; static PinArray button_inputs = GPIOB.array(0, 10); static PinArray button_leds = GPIOC.array(0, 10); static Pin qe1a = GPIOA[0]; static Pin qe1b = GPIOA[1]; static Pin qe2a = GPIOA[6]; static Pin qe2b = GPIOA[7]; static Pin led1 = GPIOA[8]; static Pin led2 = GPIOA[9]; USB_f1 usb(USB, dev_desc_p, conf_desc_p); uint32_t last_led_time; class HID_arcin : public USB_HID { private: bool set_feature_bootloader(bootloader_report_t* report) { switch(report->func) { case 0: return true; case 0x10: // Reset to bootloader do_reset_bootloader = true; return true; case 0x20: // Reset to runtime do_reset = true; return true; default: return false; } } bool set_feature_config(config_report_t* report) { if(report->segment != 0) { return false; } configloader.write(report->size, report->data); return true; } bool get_feature_config() { config_report_t report = {0xc0, 0, sizeof(config)}; memcpy(report.data, &config, sizeof(config)); usb.write(0, (uint32_t*)&report, sizeof(report)); return true; } public: HID_arcin(USB_generic& usbd, desc_t rdesc) : USB_HID(usbd, rdesc, 0, 1, 64) {} protected: virtual bool set_output_report(uint32_t* buf, uint32_t len) { if(len != sizeof(output_report_t)) { return false; } output_report_t* report = (output_report_t*)buf; last_led_time = Time::time(); button_leds.set(report->leds); return true; } virtual bool set_feature_report(uint32_t* buf, uint32_t len) { switch(*buf & 0xff) { case 0xb0: if(len != sizeof(bootloader_report_t)) { return false; } return set_feature_bootloader((bootloader_report_t*)buf); case 0xc0: if(len != sizeof(config_report_t)) { return false; } return set_feature_config((config_report_t*)buf); default: return false; } } virtual bool get_feature_report(uint8_t report_id) { switch(report_id) { case 0xc0: return get_feature_config(); default: return false; } } }; HID_arcin usb_hid(usb, report_desc_p); USB_strings usb_strings(usb, config.label); int main() { rcc_init(); // Initialize system timer. STK.LOAD = 72000000 / 8 / 1000; // 1000 Hz. STK.CTRL = 0x03; // Load config. configloader.read(sizeof(config), &config); RCC.enable(RCC.GPIOA); RCC.enable(RCC.GPIOB); RCC.enable(RCC.GPIOC); usb_dm.set_mode(Pin::AF); usb_dm.set_af(14); usb_dp.set_mode(Pin::AF); usb_dp.set_af(14); RCC.enable(RCC.USB); usb.init(); usb_pu.set_mode(Pin::Output); usb_pu.on(); button_inputs.set_mode(Pin::Input); button_inputs.set_pull(Pin::PullUp); button_leds.set_mode(Pin::Output); led1.set_mode(Pin::Output); led1.on(); led2.set_mode(Pin::Output); led2.on(); RCC.enable(RCC.TIM2); RCC.enable(RCC.TIM3); if(!(config.flags & (1 << 1))) { TIM2.CCER = 1 << 1; } TIM2.CCMR1 = (1 << 8) | (1 << 0); TIM2.SMCR = 3; TIM2.CR1 = 1; if(config.qe1_sens < 0) { TIM2.ARR = 256 * -config.qe1_sens - 1; } else { TIM2.ARR = 256 - 1; } if(!(config.flags & (1 << 2))) { TIM3.CCER = 1 << 1; } TIM3.CCMR1 = (1 << 8) | (1 << 0); TIM3.SMCR = 3; TIM3.CR1 = 1; if(config.qe2_sens < 0) { TIM3.ARR = 256 * -config.qe2_sens - 1; } else { TIM3.ARR = 256 - 1; } qe1a.set_af(1); qe1b.set_af(1); qe1a.set_mode(Pin::AF); qe1b.set_mode(Pin::AF); qe2a.set_af(2); qe2b.set_af(2); qe2a.set_mode(Pin::AF); qe2b.set_mode(Pin::AF); uint8_t last_x = 0; uint8_t last_y = 0; int8_t state_x = 0; int8_t state_y = 0; while(1) { usb.process(); uint16_t buttons = button_inputs.get() ^ 0x7ff; if(do_reset_bootloader) { Time::sleep(10); reset_bootloader(); } if(do_reset) { Time::sleep(10); reset(); } if(Time::time() - last_led_time > 1000) { button_leds.set(buttons); } if(usb.ep_ready(1)) { uint32_t qe1_count = TIM2.CNT; uint32_t qe2_count = TIM3.CNT; int8_t rx = qe1_count - last_x; int8_t ry = qe2_count - last_y; if(rx > 1) { state_x = 100; last_x = qe1_count; } else if(rx < -1) { state_x = -100; last_x = qe1_count; } else if(state_x > 0) { state_x--; last_x = qe1_count; } else if(state_x < 0) { state_x++; last_x = qe1_count; } if(ry > 1) { state_y = 100; last_y = qe2_count; } else if(ry < -1) { state_y = -100; last_y = qe2_count; } else if(state_y > 0) { state_y--; last_y = qe2_count; } else if(state_y < 0) { state_y++; last_y = qe2_count; } if(state_x > 0) { buttons |= 1 << 11; } else if(state_x < 0) { buttons |= 1 << 12; } if(state_y > 0) { buttons |= 1 << 13; } else if(state_y < 0) { buttons |= 1 << 14; } if(config.qe1_sens < 0) { qe1_count /= -config.qe1_sens; } else if(config.qe1_sens > 0) { qe1_count *= config.qe1_sens; } if(config.qe2_sens < 0) { qe2_count /= -config.qe2_sens; } else if(config.qe2_sens > 0) { qe2_count *= config.qe2_sens; } input_report_t report = {1, buttons, uint8_t(qe1_count), uint8_t(qe2_count)}; usb.write(1, (uint32_t*)&report, sizeof(report)); } } } <commit_msg>Added common axis interface to allow switching between QE/analog.<commit_after>#include <rcc/rcc.h> #include <gpio/gpio.h> #include <interrupt/interrupt.h> #include <timer/timer.h> #include <os/time.h> #include <usb/usb.h> #include <usb/descriptor.h> #include "report_desc.h" #include "usb_strings.h" #include "configloader.h" #include "config.h" static uint32_t& reset_reason = *(uint32_t*)0x10000000; static bool do_reset_bootloader; static bool do_reset; void reset() { SCB.AIRCR = (0x5fa << 16) | (1 << 2); // SYSRESETREQ } void reset_bootloader() { reset_reason = 0xb007; reset(); } Configloader configloader(0x801f800); config_t config; auto dev_desc = device_desc(0x200, 0, 0, 0, 64, 0x1d50, 0x6080, 0x110, 1, 2, 3, 1); auto conf_desc = configuration_desc(1, 1, 0, 0xc0, 0, // HID interface. interface_desc(0, 0, 1, 0x03, 0x00, 0x00, 0, hid_desc(0x111, 0, 1, 0x22, sizeof(report_desc)), endpoint_desc(0x81, 0x03, 16, 1) ) ); desc_t dev_desc_p = {sizeof(dev_desc), (void*)&dev_desc}; desc_t conf_desc_p = {sizeof(conf_desc), (void*)&conf_desc}; desc_t report_desc_p = {sizeof(report_desc), (void*)&report_desc}; static Pin usb_dm = GPIOA[11]; static Pin usb_dp = GPIOA[12]; static Pin usb_pu = GPIOA[15]; static PinArray button_inputs = GPIOB.array(0, 10); static PinArray button_leds = GPIOC.array(0, 10); static Pin qe1a = GPIOA[0]; static Pin qe1b = GPIOA[1]; static Pin qe2a = GPIOA[6]; static Pin qe2b = GPIOA[7]; static Pin led1 = GPIOA[8]; static Pin led2 = GPIOA[9]; USB_f1 usb(USB, dev_desc_p, conf_desc_p); uint32_t last_led_time; class HID_arcin : public USB_HID { private: bool set_feature_bootloader(bootloader_report_t* report) { switch(report->func) { case 0: return true; case 0x10: // Reset to bootloader do_reset_bootloader = true; return true; case 0x20: // Reset to runtime do_reset = true; return true; default: return false; } } bool set_feature_config(config_report_t* report) { if(report->segment != 0) { return false; } configloader.write(report->size, report->data); return true; } bool get_feature_config() { config_report_t report = {0xc0, 0, sizeof(config)}; memcpy(report.data, &config, sizeof(config)); usb.write(0, (uint32_t*)&report, sizeof(report)); return true; } public: HID_arcin(USB_generic& usbd, desc_t rdesc) : USB_HID(usbd, rdesc, 0, 1, 64) {} protected: virtual bool set_output_report(uint32_t* buf, uint32_t len) { if(len != sizeof(output_report_t)) { return false; } output_report_t* report = (output_report_t*)buf; last_led_time = Time::time(); button_leds.set(report->leds); return true; } virtual bool set_feature_report(uint32_t* buf, uint32_t len) { switch(*buf & 0xff) { case 0xb0: if(len != sizeof(bootloader_report_t)) { return false; } return set_feature_bootloader((bootloader_report_t*)buf); case 0xc0: if(len != sizeof(config_report_t)) { return false; } return set_feature_config((config_report_t*)buf); default: return false; } } virtual bool get_feature_report(uint8_t report_id) { switch(report_id) { case 0xc0: return get_feature_config(); default: return false; } } }; HID_arcin usb_hid(usb, report_desc_p); USB_strings usb_strings(usb, config.label); class Axis { public: virtual uint32_t get() = 0; }; class QEAxis : public Axis { private: TIM_t& tim; public: QEAxis(TIM_t& t) : tim(t) {} void enable(bool invert, int8_t sens) { if(!invert) { tim.CCER = 1 << 1; } tim.CCMR1 = (1 << 8) | (1 << 0); tim.SMCR = 3; tim.CR1 = 1; if(sens < 0) { tim.ARR = 256 * -sens - 1; } else { tim.ARR = 256 - 1; } } virtual uint32_t get() final { return tim.CNT; } }; QEAxis axis_qe1(TIM2); QEAxis axis_qe2(TIM3); int main() { rcc_init(); // Initialize system timer. STK.LOAD = 72000000 / 8 / 1000; // 1000 Hz. STK.CTRL = 0x03; // Load config. configloader.read(sizeof(config), &config); RCC.enable(RCC.GPIOA); RCC.enable(RCC.GPIOB); RCC.enable(RCC.GPIOC); usb_dm.set_mode(Pin::AF); usb_dm.set_af(14); usb_dp.set_mode(Pin::AF); usb_dp.set_af(14); RCC.enable(RCC.USB); usb.init(); usb_pu.set_mode(Pin::Output); usb_pu.on(); button_inputs.set_mode(Pin::Input); button_inputs.set_pull(Pin::PullUp); button_leds.set_mode(Pin::Output); led1.set_mode(Pin::Output); led1.on(); led2.set_mode(Pin::Output); led2.on(); Axis* axis_1; if(0) { // TODO: Analog mode. //axis_1 = &ana_1; } else { RCC.enable(RCC.TIM2); axis_qe1.enable(config.flags & (1 << 1), config.qe1_sens); qe1a.set_af(1); qe1b.set_af(1); qe1a.set_mode(Pin::AF); qe1b.set_mode(Pin::AF); axis_1 = &axis_qe1; } Axis* axis_2; if(0) { // TODO: Analog mode. //axis_2 = &ana_2; } else { RCC.enable(RCC.TIM3); axis_qe2.enable(config.flags & (1 << 2), config.qe2_sens); qe2a.set_af(1); qe2b.set_af(1); qe2a.set_mode(Pin::AF); qe2b.set_mode(Pin::AF); axis_2 = &axis_qe2; } uint8_t last_x = 0; uint8_t last_y = 0; int8_t state_x = 0; int8_t state_y = 0; while(1) { usb.process(); uint16_t buttons = button_inputs.get() ^ 0x7ff; if(do_reset_bootloader) { Time::sleep(10); reset_bootloader(); } if(do_reset) { Time::sleep(10); reset(); } if(Time::time() - last_led_time > 1000) { button_leds.set(buttons); } if(usb.ep_ready(1)) { uint32_t qe1_count = axis_1->get(); uint32_t qe2_count = axis_2->get(); int8_t rx = qe1_count - last_x; int8_t ry = qe2_count - last_y; if(rx > 1) { state_x = 100; last_x = qe1_count; } else if(rx < -1) { state_x = -100; last_x = qe1_count; } else if(state_x > 0) { state_x--; last_x = qe1_count; } else if(state_x < 0) { state_x++; last_x = qe1_count; } if(ry > 1) { state_y = 100; last_y = qe2_count; } else if(ry < -1) { state_y = -100; last_y = qe2_count; } else if(state_y > 0) { state_y--; last_y = qe2_count; } else if(state_y < 0) { state_y++; last_y = qe2_count; } if(state_x > 0) { buttons |= 1 << 11; } else if(state_x < 0) { buttons |= 1 << 12; } if(state_y > 0) { buttons |= 1 << 13; } else if(state_y < 0) { buttons |= 1 << 14; } if(config.qe1_sens < 0) { qe1_count /= -config.qe1_sens; } else if(config.qe1_sens > 0) { qe1_count *= config.qe1_sens; } if(config.qe2_sens < 0) { qe2_count /= -config.qe2_sens; } else if(config.qe2_sens > 0) { qe2_count *= config.qe2_sens; } input_report_t report = {1, buttons, uint8_t(qe1_count), uint8_t(qe2_count)}; usb.write(1, (uint32_t*)&report, sizeof(report)); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: componentdef.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-08-03 14:37:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ #include "ldapuserprofilebe.hxx" #endif //CONFIGMGR_BACKEND_LDAPUSERPROFILE_HXX_ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_ #include <cppuhelper/implementationentry.hxx> #endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_ #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif // _RTL_USTRBUF_HXX_ using namespace extensions::config::ldap ; //============================================================================== static uno::Reference<uno::XInterface> SAL_CALL createLdapUserProfileBe( const uno::Reference<uno::XComponentContext>& aContext) { return * new LdapUserProfileBe(aContext) ; } //------------------------------------------------------------------------------ static const cppu::ImplementationEntry kImplementations_entries[] = { { createLdapUserProfileBe, LdapUserProfileBe::getLdapUserProfileBeName, LdapUserProfileBe::getLdapUserProfileBeServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { NULL } } ; //------------------------------------------------------------------------------ extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **aEnvTypeName, uno_Environment **aEnvironment) { *aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } //------------------------------------------------------------------------------ extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager, void *aRegistryKey) { using namespace ::com::sun::star::registry; if (aRegistryKey) { /** Service factory */ uno::Reference<lang::XMultiServiceFactory> xFactory (reinterpret_cast<lang::XMultiServiceFactory*> (aServiceManager), uno::UNO_QUERY); rtl::OUStringBuffer aImplKeyName; aImplKeyName.appendAscii("/"); aImplKeyName.append(LdapUserProfileBe::getLdapUserProfileBeName()); rtl::OUString aMainKeyName(RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); uno::Reference<XRegistryKey> xNewImplKey( reinterpret_cast<XRegistryKey*> (aRegistryKey)->createKey(aImplKeyName.makeStringAndClear())); uno::Reference<XRegistryKey> xNewKey( xNewImplKey->createKey(aMainKeyName)); //Now register associated service names uno::Sequence<rtl::OUString> sServiceNames = LdapUserProfileBe::getLdapUserProfileBeServiceNames(); for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i) { xNewKey->createKey(sServiceNames[i]); } //Now register associated org.openoffice.UserProfile component //that this backend supports under xNewImplKey uno::Reference<XRegistryKey> xComponentKey( xNewImplKey->createKey(rtl::OUString::createFromAscii ("/DATA/SupportedComponents"))); uno::Sequence<rtl::OUString> aComponentList(1); aComponentList[0]= rtl::OUString::createFromAscii ("org.openoffice.UserProfile"); xComponentKey->setAsciiListValue(aComponentList); return sal_True; } return sal_False; } //------------------------------------------------------------------------------ extern "C" void *component_getFactory(const sal_Char *aImplementationName, void *aServiceManager, void *aRegistryKey) { return cppu::component_getFactoryHelper(aImplementationName, aServiceManager, aRegistryKey, kImplementations_entries) ; } //------------------------------------------------------------------------------ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.222); FILE MERGED 2005/09/05 12:58:51 rt 1.2.222.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: componentdef.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:22:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ #include "ldapuserprofilebe.hxx" #endif //CONFIGMGR_BACKEND_LDAPUSERPROFILE_HXX_ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_ #include <cppuhelper/implementationentry.hxx> #endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_ #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif // _RTL_USTRBUF_HXX_ using namespace extensions::config::ldap ; //============================================================================== static uno::Reference<uno::XInterface> SAL_CALL createLdapUserProfileBe( const uno::Reference<uno::XComponentContext>& aContext) { return * new LdapUserProfileBe(aContext) ; } //------------------------------------------------------------------------------ static const cppu::ImplementationEntry kImplementations_entries[] = { { createLdapUserProfileBe, LdapUserProfileBe::getLdapUserProfileBeName, LdapUserProfileBe::getLdapUserProfileBeServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { NULL } } ; //------------------------------------------------------------------------------ extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **aEnvTypeName, uno_Environment **aEnvironment) { *aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } //------------------------------------------------------------------------------ extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager, void *aRegistryKey) { using namespace ::com::sun::star::registry; if (aRegistryKey) { /** Service factory */ uno::Reference<lang::XMultiServiceFactory> xFactory (reinterpret_cast<lang::XMultiServiceFactory*> (aServiceManager), uno::UNO_QUERY); rtl::OUStringBuffer aImplKeyName; aImplKeyName.appendAscii("/"); aImplKeyName.append(LdapUserProfileBe::getLdapUserProfileBeName()); rtl::OUString aMainKeyName(RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); uno::Reference<XRegistryKey> xNewImplKey( reinterpret_cast<XRegistryKey*> (aRegistryKey)->createKey(aImplKeyName.makeStringAndClear())); uno::Reference<XRegistryKey> xNewKey( xNewImplKey->createKey(aMainKeyName)); //Now register associated service names uno::Sequence<rtl::OUString> sServiceNames = LdapUserProfileBe::getLdapUserProfileBeServiceNames(); for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i) { xNewKey->createKey(sServiceNames[i]); } //Now register associated org.openoffice.UserProfile component //that this backend supports under xNewImplKey uno::Reference<XRegistryKey> xComponentKey( xNewImplKey->createKey(rtl::OUString::createFromAscii ("/DATA/SupportedComponents"))); uno::Sequence<rtl::OUString> aComponentList(1); aComponentList[0]= rtl::OUString::createFromAscii ("org.openoffice.UserProfile"); xComponentKey->setAsciiListValue(aComponentList); return sal_True; } return sal_False; } //------------------------------------------------------------------------------ extern "C" void *component_getFactory(const sal_Char *aImplementationName, void *aServiceManager, void *aRegistryKey) { return cppu::component_getFactoryHelper(aImplementationName, aServiceManager, aRegistryKey, kImplementations_entries) ; } //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>#include <iomanip> #include <stdexcept> #include "performance.h" using namespace std; using namespace cv; void TestSystem::setWorkingDir(const string& val) { working_dir_ = val; } void TestSystem::setTestFilter(const string& val) { test_filter_ = val; } void TestSystem::run() { // Run test initializers vector<Runnable*>::iterator it = inits_.begin(); for (; it != inits_.end(); ++it) { if ((*it)->name().find(test_filter_, 0) != string::npos) (*it)->run(); } printHeading(); // Run tests it = tests_.begin(); for (; it != tests_.end(); ++it) { try { if ((*it)->name().find(test_filter_, 0) != string::npos) { cout << endl << (*it)->name() << ":\n"; (*it)->run(); finishCurrentSubtest(); } } catch (const Exception&) { // Message is printed via callback resetCurrentSubtest(); } catch (const runtime_error& e) { printError(e.what()); resetCurrentSubtest(); } } printSummary(); } void TestSystem::finishCurrentSubtest() { if (cur_subtest_is_empty_) // There is no need to print subtest statistics return; int cpu_time = static_cast<int>(cpu_elapsed_ / getTickFrequency() * 1000.0); int gpu_time = static_cast<int>(gpu_elapsed_ / getTickFrequency() * 1000.0); double speedup = static_cast<double>(cpu_elapsed_) / std::max((int64)1, gpu_elapsed_); speedup_total_ += speedup; printMetrics(cpu_time, gpu_time, speedup); num_subtests_called_++; resetCurrentSubtest(); } void TestSystem::printHeading() { cout << setiosflags(ios_base::left); cout << TAB << setw(10) << "CPU, ms" << setw(10) << "GPU, ms" << setw(14) << "SPEEDUP" << "DESCRIPTION\n"; cout << resetiosflags(ios_base::left); } void TestSystem::printSummary() { cout << setiosflags(ios_base::fixed); cout << "\naverage GPU speedup: x" << setprecision(3) << speedup_total_ / std::max(1, num_subtests_called_) << endl; cout << resetiosflags(ios_base::fixed); } void TestSystem::printMetrics(double cpu_time, double gpu_time, double speedup) { cout << TAB << setiosflags(ios_base::left); stringstream stream; stream << cpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << gpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << "x" << setprecision(3) << speedup; cout << setw(14) << stream.str(); cout << cur_subtest_description_.str(); cout << resetiosflags(ios_base::left) << endl; } void TestSystem::printError(const std::string& msg) { cout << TAB << "[error: " << msg << "] " << cur_subtest_description_.str() << endl; } void gen(Mat& mat, int rows, int cols, int type, Scalar low, Scalar high) { mat.create(rows, cols, type); RNG rng(0); rng.fill(mat, RNG::UNIFORM, low, high); } string abspath(const string& relpath) { return TestSystem::instance().workingDir() + relpath; } int CV_CDECL cvErrorCallback(int /*status*/, const char* /*func_name*/, const char* err_msg, const char* /*file_name*/, int /*line*/, void* /*userdata*/) { TestSystem::instance().printError(err_msg); return 0; } int main(int argc, char** argv) { if (argc < 3) cout << "Usage: performance_gpu <test_filter> <working_dir_with_slash>\n\n"; if (argc >= 2) TestSystem::instance().setTestFilter(argv[1]); if (argc >= 3) TestSystem::instance().setWorkingDir(argv[2]); redirectError(cvErrorCallback); TestSystem::instance().run(); return 0; } <commit_msg>added command line args parsing into gpu performance sample<commit_after>#include <iomanip> #include <stdexcept> #include <string> #include "performance.h" using namespace std; using namespace cv; void TestSystem::setWorkingDir(const string& val) { working_dir_ = val; } void TestSystem::setTestFilter(const string& val) { test_filter_ = val; } void TestSystem::run() { // Run test initializers vector<Runnable*>::iterator it = inits_.begin(); for (; it != inits_.end(); ++it) { if ((*it)->name().find(test_filter_, 0) != string::npos) (*it)->run(); } printHeading(); // Run tests it = tests_.begin(); for (; it != tests_.end(); ++it) { try { if ((*it)->name().find(test_filter_, 0) != string::npos) { cout << endl << (*it)->name() << ":\n"; (*it)->run(); finishCurrentSubtest(); } } catch (const Exception&) { // Message is printed via callback resetCurrentSubtest(); } catch (const runtime_error& e) { printError(e.what()); resetCurrentSubtest(); } } printSummary(); } void TestSystem::finishCurrentSubtest() { if (cur_subtest_is_empty_) // There is no need to print subtest statistics return; int cpu_time = static_cast<int>(cpu_elapsed_ / getTickFrequency() * 1000.0); int gpu_time = static_cast<int>(gpu_elapsed_ / getTickFrequency() * 1000.0); double speedup = static_cast<double>(cpu_elapsed_) / std::max((int64)1, gpu_elapsed_); speedup_total_ += speedup; printMetrics(cpu_time, gpu_time, speedup); num_subtests_called_++; resetCurrentSubtest(); } void TestSystem::printHeading() { cout << setiosflags(ios_base::left); cout << TAB << setw(10) << "CPU, ms" << setw(10) << "GPU, ms" << setw(14) << "SPEEDUP" << "DESCRIPTION\n"; cout << resetiosflags(ios_base::left); } void TestSystem::printSummary() { cout << setiosflags(ios_base::fixed); cout << "\naverage GPU speedup: x" << setprecision(3) << speedup_total_ / std::max(1, num_subtests_called_) << endl; cout << resetiosflags(ios_base::fixed); } void TestSystem::printMetrics(double cpu_time, double gpu_time, double speedup) { cout << TAB << setiosflags(ios_base::left); stringstream stream; stream << cpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << gpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << "x" << setprecision(3) << speedup; cout << setw(14) << stream.str(); cout << cur_subtest_description_.str(); cout << resetiosflags(ios_base::left) << endl; } void TestSystem::printError(const std::string& msg) { cout << TAB << "[error: " << msg << "] " << cur_subtest_description_.str() << endl; } void gen(Mat& mat, int rows, int cols, int type, Scalar low, Scalar high) { mat.create(rows, cols, type); RNG rng(0); rng.fill(mat, RNG::UNIFORM, low, high); } string abspath(const string& relpath) { return TestSystem::instance().workingDir() + relpath; } int CV_CDECL cvErrorCallback(int /*status*/, const char* /*func_name*/, const char* err_msg, const char* /*file_name*/, int /*line*/, void* /*userdata*/) { TestSystem::instance().printError(err_msg); return 0; } int main(int argc, char** argv) { // Parse command line arguments for (int i = 1; i < argc; ++i) { string key = argv[i]; if (key == "--help") { cout << "Usage: performance_gpu [--filter <test_filter>] [--working-dir <working_dir_with_slash>]\n"; return 0; } if (key == "--filter" && i + 1 < argc) TestSystem::instance().setTestFilter(argv[++i]); else if (key == "--working-dir" && i + 1 < argc) TestSystem::instance().setWorkingDir(argv[++i]); else { cout << "Unknown parameter: '" << key << "'" << endl; return -1; } } redirectError(cvErrorCallback); TestSystem::instance().run(); return 0; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "resultconfig.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.resultconfig"); namespace search::docsummary { void ResultConfig::Clean() { _classLookup.clear(); _nameLookup.clear(); } void ResultConfig::Init() { } ResultConfig::ResultConfig() : _defaultSummaryId(-1), _classLookup(), _nameLookup() { Init(); } ResultConfig::~ResultConfig() { Clean(); } const char * ResultConfig::GetResTypeName(ResType type) { switch (type) { case RES_INT: return "integer"; case RES_SHORT: return "short"; case RES_BYTE: return "byte"; case RES_BOOL: return "bool"; case RES_FLOAT: return "float"; case RES_DOUBLE: return "double"; case RES_INT64: return "int64"; case RES_STRING: return "string"; case RES_DATA: return "data"; case RES_LONG_STRING: return "longstring"; case RES_LONG_DATA: return "longdata"; case RES_XMLSTRING: return "xmlstring"; case RES_JSONSTRING: return "jsonstring"; case RES_TENSOR: return "tensor"; case RES_FEATUREDATA: return "featuredata"; } return "unknown-type"; } void ResultConfig::Reset() { if (! _classLookup.empty() || _fieldEnum.GetNumEntries() > 0) { Clean(); Init(); } } ResultClass * ResultConfig::AddResultClass(const char *name, uint32_t id) { ResultClass *ret = nullptr; if (id != NoClassID() && (_classLookup.find(id) == _classLookup.end())) { ResultClass::UP rc(new ResultClass(name, id, _fieldEnum)); ret = rc.get(); _classLookup[id] = std::move(rc); if (_nameLookup.find(name) != _nameLookup.end()) { LOG(warning, "Duplicate result class name: %s (now maps to class id %u)", name, id); } _nameLookup[name] = id; } return ret; } const ResultClass* ResultConfig::LookupResultClass(uint32_t id) const { IdMap::const_iterator it(_classLookup.find(id)); return (it != _classLookup.end()) ? it->second.get() : nullptr; } uint32_t ResultConfig::LookupResultClassId(const vespalib::string &name, uint32_t def) const { NameMap::const_iterator found(_nameLookup.find(name)); return (found != _nameLookup.end()) ? found->second : def; } uint32_t ResultConfig::LookupResultClassId(const vespalib::string &name) const { return LookupResultClassId(name, (name.empty() || (name == "default")) ? _defaultSummaryId : NoClassID()); } void ResultConfig::CreateEnumMaps() { for (auto & entry : _classLookup) { entry.second->CreateEnumMap(); } } bool ResultConfig::ReadConfig(const vespa::config::search::SummaryConfig &cfg, const char *configId) { bool rc = true; Reset(); int maxclassID = 0x7fffffff; // avoid negative classids _defaultSummaryId = cfg.defaultsummaryid; for (uint32_t i = 0; rc && i < cfg.classes.size(); i++) { if (cfg.classes[i].name.empty()) { LOG(warning, "%s classes[%d]: empty name", configId, i); } int classID = cfg.classes[i].id; if (classID < 0 || classID > maxclassID) { LOG(error, "%s classes[%d]: bad id %d", configId, i, classID); rc = false; break; } ResultClass *resClass = AddResultClass(cfg.classes[i].name.c_str(), classID); if (resClass == nullptr) { LOG(error,"%s: unable to add classes[%d] name %s", configId, i, cfg.classes[i].name.c_str()); rc = false; break; } for (unsigned int j = 0; rc && (j < cfg.classes[i].fields.size()); j++) { const char *fieldtype = cfg.classes[i].fields[j].type.c_str(); const char *fieldname = cfg.classes[i].fields[j].name.c_str(); LOG(debug, "Reconfiguring class '%s' field '%s' of type '%s'", cfg.classes[i].name.c_str(), fieldname, fieldtype); if (strcmp(fieldtype, "integer") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_INT); } else if (strcmp(fieldtype, "short") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_SHORT); } else if (strcmp(fieldtype, "bool") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_BOOL); } else if (strcmp(fieldtype, "byte") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_BYTE); } else if (strcmp(fieldtype, "float") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_FLOAT); } else if (strcmp(fieldtype, "double") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_DOUBLE); } else if (strcmp(fieldtype, "int64") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_INT64); } else if (strcmp(fieldtype, "string") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_STRING); } else if (strcmp(fieldtype, "data") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_DATA); } else if (strcmp(fieldtype, "longstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_LONG_STRING); } else if (strcmp(fieldtype, "longdata") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_LONG_DATA); } else if (strcmp(fieldtype, "xmlstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_XMLSTRING); } else if (strcmp(fieldtype, "jsonstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_JSONSTRING); } else if (strcmp(fieldtype, "tensor") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_TENSOR); } else if (strcmp(fieldtype, "featuredata") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_FEATUREDATA); } else { LOG(error, "%s %s.fields[%d]: unknown type '%s'", configId, cfg.classes[i].name.c_str(), j, fieldtype); rc = false; break; } if (!rc) { LOG(error, "%s %s.fields[%d]: duplicate name '%s'", configId, cfg.classes[i].name.c_str(), j, fieldname); break; } } } if (rc) { CreateEnumMaps(); // create mappings needed by TVM } else { Reset(); // FAIL, discard all config } return rc; } uint32_t ResultConfig::GetClassID(const char *buf, uint32_t buflen) { uint32_t ret = NoClassID(); uint32_t tmp32; if (buflen >= sizeof(tmp32)) { memcpy(&tmp32, buf, sizeof(tmp32)); ret = tmp32; } return ret; } } <commit_msg>Handle raw type<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "resultconfig.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.resultconfig"); namespace search::docsummary { void ResultConfig::Clean() { _classLookup.clear(); _nameLookup.clear(); } void ResultConfig::Init() { } ResultConfig::ResultConfig() : _defaultSummaryId(-1), _classLookup(), _nameLookup() { Init(); } ResultConfig::~ResultConfig() { Clean(); } const char * ResultConfig::GetResTypeName(ResType type) { switch (type) { case RES_INT: return "integer"; case RES_SHORT: return "short"; case RES_BYTE: return "byte"; case RES_BOOL: return "bool"; case RES_FLOAT: return "float"; case RES_DOUBLE: return "double"; case RES_INT64: return "int64"; case RES_STRING: return "string"; case RES_DATA: return "data"; case RES_LONG_STRING: return "longstring"; case RES_LONG_DATA: return "longdata"; case RES_XMLSTRING: return "xmlstring"; case RES_JSONSTRING: return "jsonstring"; case RES_TENSOR: return "tensor"; case RES_FEATUREDATA: return "featuredata"; } return "unknown-type"; } void ResultConfig::Reset() { if (! _classLookup.empty() || _fieldEnum.GetNumEntries() > 0) { Clean(); Init(); } } ResultClass * ResultConfig::AddResultClass(const char *name, uint32_t id) { ResultClass *ret = nullptr; if (id != NoClassID() && (_classLookup.find(id) == _classLookup.end())) { ResultClass::UP rc(new ResultClass(name, id, _fieldEnum)); ret = rc.get(); _classLookup[id] = std::move(rc); if (_nameLookup.find(name) != _nameLookup.end()) { LOG(warning, "Duplicate result class name: %s (now maps to class id %u)", name, id); } _nameLookup[name] = id; } return ret; } const ResultClass* ResultConfig::LookupResultClass(uint32_t id) const { IdMap::const_iterator it(_classLookup.find(id)); return (it != _classLookup.end()) ? it->second.get() : nullptr; } uint32_t ResultConfig::LookupResultClassId(const vespalib::string &name, uint32_t def) const { NameMap::const_iterator found(_nameLookup.find(name)); return (found != _nameLookup.end()) ? found->second : def; } uint32_t ResultConfig::LookupResultClassId(const vespalib::string &name) const { return LookupResultClassId(name, (name.empty() || (name == "default")) ? _defaultSummaryId : NoClassID()); } void ResultConfig::CreateEnumMaps() { for (auto & entry : _classLookup) { entry.second->CreateEnumMap(); } } bool ResultConfig::ReadConfig(const vespa::config::search::SummaryConfig &cfg, const char *configId) { bool rc = true; Reset(); int maxclassID = 0x7fffffff; // avoid negative classids _defaultSummaryId = cfg.defaultsummaryid; for (uint32_t i = 0; rc && i < cfg.classes.size(); i++) { if (cfg.classes[i].name.empty()) { LOG(warning, "%s classes[%d]: empty name", configId, i); } int classID = cfg.classes[i].id; if (classID < 0 || classID > maxclassID) { LOG(error, "%s classes[%d]: bad id %d", configId, i, classID); rc = false; break; } ResultClass *resClass = AddResultClass(cfg.classes[i].name.c_str(), classID); if (resClass == nullptr) { LOG(error,"%s: unable to add classes[%d] name %s", configId, i, cfg.classes[i].name.c_str()); rc = false; break; } for (unsigned int j = 0; rc && (j < cfg.classes[i].fields.size()); j++) { const char *fieldtype = cfg.classes[i].fields[j].type.c_str(); const char *fieldname = cfg.classes[i].fields[j].name.c_str(); LOG(debug, "Reconfiguring class '%s' field '%s' of type '%s'", cfg.classes[i].name.c_str(), fieldname, fieldtype); if (strcmp(fieldtype, "integer") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_INT); } else if (strcmp(fieldtype, "short") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_SHORT); } else if (strcmp(fieldtype, "bool") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_BOOL); } else if (strcmp(fieldtype, "byte") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_BYTE); } else if (strcmp(fieldtype, "float") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_FLOAT); } else if (strcmp(fieldtype, "double") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_DOUBLE); } else if (strcmp(fieldtype, "int64") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_INT64); } else if (strcmp(fieldtype, "string") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_STRING); } else if (strcmp(fieldtype, "data") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_DATA); } else if (strcmp(fieldtype, "raw") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_DATA); } else if (strcmp(fieldtype, "longstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_LONG_STRING); } else if (strcmp(fieldtype, "longdata") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_LONG_DATA); } else if (strcmp(fieldtype, "xmlstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_XMLSTRING); } else if (strcmp(fieldtype, "jsonstring") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_JSONSTRING); } else if (strcmp(fieldtype, "tensor") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_TENSOR); } else if (strcmp(fieldtype, "featuredata") == 0) { rc = resClass->AddConfigEntry(fieldname, RES_FEATUREDATA); } else { LOG(error, "%s %s.fields[%d]: unknown type '%s'", configId, cfg.classes[i].name.c_str(), j, fieldtype); rc = false; break; } if (!rc) { LOG(error, "%s %s.fields[%d]: duplicate name '%s'", configId, cfg.classes[i].name.c_str(), j, fieldname); break; } } } if (rc) { CreateEnumMaps(); // create mappings needed by TVM } else { Reset(); // FAIL, discard all config } return rc; } uint32_t ResultConfig::GetClassID(const char *buf, uint32_t buflen) { uint32_t ret = NoClassID(); uint32_t tmp32; if (buflen >= sizeof(tmp32)) { memcpy(&tmp32, buf, sizeof(tmp32)); ret = tmp32; } return ret; } } <|endoftext|>
<commit_before>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-4-15 23:25:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M, Q; int a[50]; int l[50]; int r[50]; bool used[50]; ll solve() { ll ans = 0; for (auto i = 0; i < Q; i++) { int maxi = -1; int ind = 0; for (auto j = 0; j < N; j++) { if (!used[j] && l[i] <= a[j] && a[j] <= r[i] && a[j] > maxi) { maxi = a[j]; ind = j; } } if (maxi >= 0) { ans += maxi; used[ind] = true; } } cerr << "ans = " << ans << endl; return ans; } void solveA() { ll ans = 0; for (auto i = 0; i < (1 << N); i++) { int cnt = 0; for (auto j = 0; j < N; j++) { if ((i >> j) & 1) { cnt++; } } if (cnt == M) { for (auto j = 0; j < N; j++) { used[j] = (i >> j) & 1; } ans = min(ans, solve()); } } cout << ans << endl; } void solveB() { fill(used, used + N, false); for (auto i = 0; i < M; i++) { used[i] = false; } cout << solve() << endl; } int main() { cin >> N >> M >> Q; for (auto i = 0; i < N; i++) { cin >> a[i]; } for (auto i = 0; i < Q; i++) { cin >> l[i] >> r[i]; } if (N <= 15) { solveA(); } else { solveB(); } }<commit_msg>tried F.cpp to 'F'<commit_after>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-4-15 23:25:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M, Q; int a[50]; int l[50]; int r[50]; bool used[50]; ll solve() { ll ans = 0; for (auto i = 0; i < Q; i++) { int maxi = -1; int ind = 0; for (auto j = 0; j < N; j++) { if (!used[j] && l[i] <= a[j] && a[j] <= r[i] && a[j] > maxi) { maxi = a[j]; ind = j; } } if (maxi >= 0) { ans += maxi; } } // cerr << "ans = " << ans << endl; return ans; } void solveA() { ll ans = 0; for (auto i = 0; i < (1 << N); i++) { int cnt = 0; for (auto j = 0; j < N; j++) { if ((i >> j) & 1) { cnt++; } } if (cnt == M) { for (auto j = 0; j < N; j++) { used[j] = (i >> j) & 1; } ans = min(ans, solve()); } } cout << ans << endl; } void solveB() { fill(used, used + N, false); for (auto i = 0; i < M; i++) { used[i] = false; } cout << solve() << endl; } int main() { cin >> N >> M >> Q; for (auto i = 0; i < N; i++) { cin >> a[i]; } for (auto i = 0; i < Q; i++) { cin >> l[i] >> r[i]; } if (N <= 15) { solveA(); } else { solveB(); } }<|endoftext|>
<commit_before>// Copyright (c) 2009 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 <gtk/gtk.h> #include "app/l10n_util.h" #include "base/message_loop.h" #include "base/gfx/gtk_util.h" #include "chrome/browser/gtk/options/url_picker_dialog_gtk.h" #include "chrome/browser/net/url_fixer_upper.h" #include "chrome/browser/possible_url_model.h" #include "chrome/browser/profile.h" #include "chrome/common/gtk_util.h" #include "chrome/common/pref_names.h" #include "googleurl/src/gurl.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" namespace { // Initial size for dialog. const int kDialogDefaultWidth = 450; const int kDialogDefaultHeight = 450; // Initial width of the first column. const int kTitleColumnInitialSize = 200; // Style for recent history label. const char kHistoryLabelMarkup[] = "<span weight='bold'>%s</span>"; // Column ids for |history_list_store_|. enum { COL_FAVICON, COL_TITLE, COL_DISPLAY_URL, COL_COUNT, }; // Get the row number corresponding to |path|. gint GetRowNumForPath(GtkTreePath* path) { gint* indices = gtk_tree_path_get_indices(path); if (!indices) { NOTREACHED(); return -1; } return indices[0]; } // Get the row number corresponding to |iter|. gint GetRowNumForIter(GtkTreeModel* model, GtkTreeIter* iter) { GtkTreePath* path = gtk_tree_model_get_path(model, iter); int row = GetRowNumForPath(path); gtk_tree_path_free(path); return row; } // Get the row number in the child tree model corresponding to |sort_path| in // the parent tree model. gint GetTreeSortChildRowNumForPath(GtkTreeModel* sort_model, GtkTreePath* sort_path) { GtkTreePath *child_path = gtk_tree_model_sort_convert_path_to_child_path( GTK_TREE_MODEL_SORT(sort_model), sort_path); int row = GetRowNumForPath(child_path); gtk_tree_path_free(child_path); return row; } } // anonymous namespace UrlPickerDialogGtk::UrlPickerDialogGtk(UrlPickerCallback* callback, Profile* profile, GtkWindow* parent) : profile_(profile), callback_(callback) { dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_ASI_ADD_TITLE).c_str(), parent, static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); add_button_ = gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_ADD, GTK_RESPONSE_OK); gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK); gtk_window_set_default_size(GTK_WINDOW(dialog_), kDialogDefaultWidth, kDialogDefaultHeight); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); // URL entry. GtkWidget* url_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing); GtkWidget* url_label = gtk_label_new( l10n_util::GetStringUTF8(IDS_ASI_URL).c_str()); gtk_box_pack_start(GTK_BOX(url_hbox), url_label, FALSE, FALSE, 0); url_entry_ = gtk_entry_new(); gtk_entry_set_activates_default(GTK_ENTRY(url_entry_), TRUE); g_signal_connect(G_OBJECT(url_entry_), "changed", G_CALLBACK(OnUrlEntryChanged), this); gtk_box_pack_start(GTK_BOX(url_hbox), url_entry_, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), url_hbox, FALSE, FALSE, 0); // Recent history description label. GtkWidget* history_vbox = gtk_vbox_new(FALSE, gtk_util::kLabelSpacing); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), history_vbox); GtkWidget* history_label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped(kHistoryLabelMarkup, l10n_util::GetStringUTF8(IDS_ASI_DESCRIPTION).c_str()); gtk_label_set_markup(GTK_LABEL(history_label), markup); g_free(markup); GtkWidget* history_label_alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); gtk_container_add(GTK_CONTAINER(history_label_alignment), history_label); gtk_box_pack_start(GTK_BOX(history_vbox), history_label_alignment, FALSE, FALSE, 0); // Recent history list. GtkWidget* scroll_window = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_window), GTK_SHADOW_ETCHED_IN); gtk_container_add(GTK_CONTAINER(history_vbox), scroll_window); history_list_store_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING); history_list_sort_ = gtk_tree_model_sort_new_with_model( GTK_TREE_MODEL(history_list_store_)); gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_), COL_TITLE, CompareTitle, this, NULL); gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_), COL_DISPLAY_URL, CompareURL, this, NULL); history_tree_ = gtk_tree_view_new_with_model(history_list_sort_); gtk_container_add(GTK_CONTAINER(scroll_window), history_tree_); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(history_tree_), TRUE); g_signal_connect(G_OBJECT(history_tree_), "row-activated", G_CALLBACK(OnHistoryRowActivated), this); history_selection_ = gtk_tree_view_get_selection( GTK_TREE_VIEW(history_tree_)); gtk_tree_selection_set_mode(history_selection_, GTK_SELECTION_SINGLE); g_signal_connect(G_OBJECT(history_selection_), "changed", G_CALLBACK(OnHistorySelectionChanged), this); // History list columns. GtkTreeViewColumn* column = gtk_tree_view_column_new(); GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new(); gtk_tree_view_column_pack_start(column, renderer, FALSE); gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(column, renderer, TRUE); gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE); gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_), column); gtk_tree_view_column_set_title( column, l10n_util::GetStringUTF8(IDS_ASI_PAGE_COLUMN).c_str()); gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED); gtk_tree_view_column_set_resizable(column, TRUE); gtk_tree_view_column_set_fixed_width(column, kTitleColumnInitialSize); gtk_tree_view_column_set_sort_column_id(column, COL_TITLE); GtkTreeViewColumn* url_column = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8(IDS_ASI_URL_COLUMN).c_str(), gtk_cell_renderer_text_new(), "text", COL_DISPLAY_URL, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_), url_column); gtk_tree_view_column_set_sort_column_id(url_column, COL_DISPLAY_URL); // Loading data, showing dialog. url_table_model_.reset(new PossibleURLModel()); url_table_model_->SetObserver(this); url_table_model_->Reload(profile_); EnableControls(); gtk_widget_show_all(dialog_); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); } UrlPickerDialogGtk::~UrlPickerDialogGtk() { delete callback_; } void UrlPickerDialogGtk::AddURL() { GURL url(URLFixerUpper::FixupURL( gtk_entry_get_text(GTK_ENTRY(url_entry_)), "")); callback_->Run(url); } void UrlPickerDialogGtk::EnableControls() { const gchar* text = gtk_entry_get_text(GTK_ENTRY(url_entry_)); gtk_widget_set_sensitive(add_button_, text && *text); } std::string UrlPickerDialogGtk::GetURLForPath(GtkTreePath* path) const { gint row = GetTreeSortChildRowNumForPath(history_list_sort_, path); if (row < 0) { NOTREACHED(); return std::string(); } std::wstring languages = profile_->GetPrefs()->GetString(prefs::kAcceptLanguages); // Because the url_field_ is user-editable, we set the URL with // username:password and escaped path and query. std::wstring formatted = net::FormatUrl( url_table_model_->GetURL(row), languages, false, UnescapeRule::NONE, NULL, NULL); return WideToUTF8(formatted); } void UrlPickerDialogGtk::SetColumnValues(int row, GtkTreeIter* iter) { SkBitmap bitmap = url_table_model_->GetIcon(row); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap); std::wstring title = url_table_model_->GetText(row, IDS_ASI_PAGE_COLUMN); std::wstring url = url_table_model_->GetText(row, IDS_ASI_URL_COLUMN); gtk_list_store_set(history_list_store_, iter, COL_FAVICON, pixbuf, COL_TITLE, WideToUTF8(title).c_str(), COL_DISPLAY_URL, WideToUTF8(url).c_str(), -1); g_object_unref(pixbuf); } void UrlPickerDialogGtk::AddNodeToList(int row) { GtkTreeIter iter; if (row == 0) { gtk_list_store_prepend(history_list_store_, &iter); } else { GtkTreeIter sibling; gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(history_list_store_), &sibling, NULL, row - 1); gtk_list_store_insert_after(history_list_store_, &iter, &sibling); } SetColumnValues(row, &iter); } void UrlPickerDialogGtk::OnModelChanged() { gtk_list_store_clear(history_list_store_); for (int i = 0; i < url_table_model_->RowCount(); ++i) AddNodeToList(i); } void UrlPickerDialogGtk::OnItemsChanged(int start, int length) { GtkTreeIter iter; bool rv = gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(history_list_store_), &iter, NULL, start); for (int i = 0; i < length; ++i) { if (!rv) { NOTREACHED(); return; } SetColumnValues(start + i, &iter); rv = gtk_tree_model_iter_next(GTK_TREE_MODEL(history_list_store_), &iter); } } void UrlPickerDialogGtk::OnItemsAdded(int start, int length) { NOTREACHED(); } void UrlPickerDialogGtk::OnItemsRemoved(int start, int length) { NOTREACHED(); } // static gint UrlPickerDialogGtk::CompareTitle(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window) { int row1 = GetRowNumForIter(model, a); int row2 = GetRowNumForIter(model, b); return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_-> CompareValues(row1, row2, IDS_ASI_PAGE_COLUMN); } // static gint UrlPickerDialogGtk::CompareURL(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window) { int row1 = GetRowNumForIter(model, a); int row2 = GetRowNumForIter(model, b); return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_-> CompareValues(row1, row2, IDS_ASI_URL_COLUMN); } // static void UrlPickerDialogGtk::OnUrlEntryChanged(GtkEditable* editable, UrlPickerDialogGtk* window) { window->EnableControls(); } // static void UrlPickerDialogGtk::OnHistorySelectionChanged( GtkTreeSelection *selection, UrlPickerDialogGtk* window) { GtkTreeIter iter; if (!gtk_tree_selection_get_selected(selection, NULL, &iter)) { NOTREACHED(); return; } GtkTreePath* path = gtk_tree_model_get_path( GTK_TREE_MODEL(window->history_list_sort_), &iter); gtk_entry_set_text(GTK_ENTRY(window->url_entry_), window->GetURLForPath(path).c_str()); gtk_tree_path_free(path); } void UrlPickerDialogGtk::OnHistoryRowActivated(GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* column, UrlPickerDialogGtk* window) { GURL url(URLFixerUpper::FixupURL(window->GetURLForPath(path), "")); window->callback_->Run(url); gtk_widget_destroy(window->dialog_); } // static void UrlPickerDialogGtk::OnResponse(GtkDialog* dialog, int response_id, UrlPickerDialogGtk* window) { if (response_id == GTK_RESPONSE_OK) { window->AddURL(); } gtk_widget_destroy(window->dialog_); } // static void UrlPickerDialogGtk::OnWindowDestroy(GtkWidget* widget, UrlPickerDialogGtk* window) { MessageLoop::current()->DeleteSoon(FROM_HERE, window); } <commit_msg>Linux: it's not actually a bug to have the selection become empty in the URL picker. BUG=none TEST=in a debug build, go to wrench->options->basics, select "open the following pages", click "add", select something from the list, and then deselect it by holding ctrl and clicking it again; chromium should not crash<commit_after>// Copyright (c) 2009 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 <gtk/gtk.h> #include "app/l10n_util.h" #include "base/message_loop.h" #include "base/gfx/gtk_util.h" #include "chrome/browser/gtk/options/url_picker_dialog_gtk.h" #include "chrome/browser/net/url_fixer_upper.h" #include "chrome/browser/possible_url_model.h" #include "chrome/browser/profile.h" #include "chrome/common/gtk_util.h" #include "chrome/common/pref_names.h" #include "googleurl/src/gurl.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" namespace { // Initial size for dialog. const int kDialogDefaultWidth = 450; const int kDialogDefaultHeight = 450; // Initial width of the first column. const int kTitleColumnInitialSize = 200; // Style for recent history label. const char kHistoryLabelMarkup[] = "<span weight='bold'>%s</span>"; // Column ids for |history_list_store_|. enum { COL_FAVICON, COL_TITLE, COL_DISPLAY_URL, COL_COUNT, }; // Get the row number corresponding to |path|. gint GetRowNumForPath(GtkTreePath* path) { gint* indices = gtk_tree_path_get_indices(path); if (!indices) { NOTREACHED(); return -1; } return indices[0]; } // Get the row number corresponding to |iter|. gint GetRowNumForIter(GtkTreeModel* model, GtkTreeIter* iter) { GtkTreePath* path = gtk_tree_model_get_path(model, iter); int row = GetRowNumForPath(path); gtk_tree_path_free(path); return row; } // Get the row number in the child tree model corresponding to |sort_path| in // the parent tree model. gint GetTreeSortChildRowNumForPath(GtkTreeModel* sort_model, GtkTreePath* sort_path) { GtkTreePath *child_path = gtk_tree_model_sort_convert_path_to_child_path( GTK_TREE_MODEL_SORT(sort_model), sort_path); int row = GetRowNumForPath(child_path); gtk_tree_path_free(child_path); return row; } } // anonymous namespace UrlPickerDialogGtk::UrlPickerDialogGtk(UrlPickerCallback* callback, Profile* profile, GtkWindow* parent) : profile_(profile), callback_(callback) { dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_ASI_ADD_TITLE).c_str(), parent, static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); add_button_ = gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_ADD, GTK_RESPONSE_OK); gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK); gtk_window_set_default_size(GTK_WINDOW(dialog_), kDialogDefaultWidth, kDialogDefaultHeight); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); // URL entry. GtkWidget* url_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing); GtkWidget* url_label = gtk_label_new( l10n_util::GetStringUTF8(IDS_ASI_URL).c_str()); gtk_box_pack_start(GTK_BOX(url_hbox), url_label, FALSE, FALSE, 0); url_entry_ = gtk_entry_new(); gtk_entry_set_activates_default(GTK_ENTRY(url_entry_), TRUE); g_signal_connect(G_OBJECT(url_entry_), "changed", G_CALLBACK(OnUrlEntryChanged), this); gtk_box_pack_start(GTK_BOX(url_hbox), url_entry_, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), url_hbox, FALSE, FALSE, 0); // Recent history description label. GtkWidget* history_vbox = gtk_vbox_new(FALSE, gtk_util::kLabelSpacing); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), history_vbox); GtkWidget* history_label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped(kHistoryLabelMarkup, l10n_util::GetStringUTF8(IDS_ASI_DESCRIPTION).c_str()); gtk_label_set_markup(GTK_LABEL(history_label), markup); g_free(markup); GtkWidget* history_label_alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); gtk_container_add(GTK_CONTAINER(history_label_alignment), history_label); gtk_box_pack_start(GTK_BOX(history_vbox), history_label_alignment, FALSE, FALSE, 0); // Recent history list. GtkWidget* scroll_window = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_window), GTK_SHADOW_ETCHED_IN); gtk_container_add(GTK_CONTAINER(history_vbox), scroll_window); history_list_store_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING); history_list_sort_ = gtk_tree_model_sort_new_with_model( GTK_TREE_MODEL(history_list_store_)); gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_), COL_TITLE, CompareTitle, this, NULL); gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_), COL_DISPLAY_URL, CompareURL, this, NULL); history_tree_ = gtk_tree_view_new_with_model(history_list_sort_); gtk_container_add(GTK_CONTAINER(scroll_window), history_tree_); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(history_tree_), TRUE); g_signal_connect(G_OBJECT(history_tree_), "row-activated", G_CALLBACK(OnHistoryRowActivated), this); history_selection_ = gtk_tree_view_get_selection( GTK_TREE_VIEW(history_tree_)); gtk_tree_selection_set_mode(history_selection_, GTK_SELECTION_SINGLE); g_signal_connect(G_OBJECT(history_selection_), "changed", G_CALLBACK(OnHistorySelectionChanged), this); // History list columns. GtkTreeViewColumn* column = gtk_tree_view_column_new(); GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new(); gtk_tree_view_column_pack_start(column, renderer, FALSE); gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(column, renderer, TRUE); gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE); gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_), column); gtk_tree_view_column_set_title( column, l10n_util::GetStringUTF8(IDS_ASI_PAGE_COLUMN).c_str()); gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED); gtk_tree_view_column_set_resizable(column, TRUE); gtk_tree_view_column_set_fixed_width(column, kTitleColumnInitialSize); gtk_tree_view_column_set_sort_column_id(column, COL_TITLE); GtkTreeViewColumn* url_column = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8(IDS_ASI_URL_COLUMN).c_str(), gtk_cell_renderer_text_new(), "text", COL_DISPLAY_URL, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_), url_column); gtk_tree_view_column_set_sort_column_id(url_column, COL_DISPLAY_URL); // Loading data, showing dialog. url_table_model_.reset(new PossibleURLModel()); url_table_model_->SetObserver(this); url_table_model_->Reload(profile_); EnableControls(); gtk_widget_show_all(dialog_); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); } UrlPickerDialogGtk::~UrlPickerDialogGtk() { delete callback_; } void UrlPickerDialogGtk::AddURL() { GURL url(URLFixerUpper::FixupURL( gtk_entry_get_text(GTK_ENTRY(url_entry_)), "")); callback_->Run(url); } void UrlPickerDialogGtk::EnableControls() { const gchar* text = gtk_entry_get_text(GTK_ENTRY(url_entry_)); gtk_widget_set_sensitive(add_button_, text && *text); } std::string UrlPickerDialogGtk::GetURLForPath(GtkTreePath* path) const { gint row = GetTreeSortChildRowNumForPath(history_list_sort_, path); if (row < 0) { NOTREACHED(); return std::string(); } std::wstring languages = profile_->GetPrefs()->GetString(prefs::kAcceptLanguages); // Because the url_field_ is user-editable, we set the URL with // username:password and escaped path and query. std::wstring formatted = net::FormatUrl( url_table_model_->GetURL(row), languages, false, UnescapeRule::NONE, NULL, NULL); return WideToUTF8(formatted); } void UrlPickerDialogGtk::SetColumnValues(int row, GtkTreeIter* iter) { SkBitmap bitmap = url_table_model_->GetIcon(row); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap); std::wstring title = url_table_model_->GetText(row, IDS_ASI_PAGE_COLUMN); std::wstring url = url_table_model_->GetText(row, IDS_ASI_URL_COLUMN); gtk_list_store_set(history_list_store_, iter, COL_FAVICON, pixbuf, COL_TITLE, WideToUTF8(title).c_str(), COL_DISPLAY_URL, WideToUTF8(url).c_str(), -1); g_object_unref(pixbuf); } void UrlPickerDialogGtk::AddNodeToList(int row) { GtkTreeIter iter; if (row == 0) { gtk_list_store_prepend(history_list_store_, &iter); } else { GtkTreeIter sibling; gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(history_list_store_), &sibling, NULL, row - 1); gtk_list_store_insert_after(history_list_store_, &iter, &sibling); } SetColumnValues(row, &iter); } void UrlPickerDialogGtk::OnModelChanged() { gtk_list_store_clear(history_list_store_); for (int i = 0; i < url_table_model_->RowCount(); ++i) AddNodeToList(i); } void UrlPickerDialogGtk::OnItemsChanged(int start, int length) { GtkTreeIter iter; bool rv = gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(history_list_store_), &iter, NULL, start); for (int i = 0; i < length; ++i) { if (!rv) { NOTREACHED(); return; } SetColumnValues(start + i, &iter); rv = gtk_tree_model_iter_next(GTK_TREE_MODEL(history_list_store_), &iter); } } void UrlPickerDialogGtk::OnItemsAdded(int start, int length) { NOTREACHED(); } void UrlPickerDialogGtk::OnItemsRemoved(int start, int length) { NOTREACHED(); } // static gint UrlPickerDialogGtk::CompareTitle(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window) { int row1 = GetRowNumForIter(model, a); int row2 = GetRowNumForIter(model, b); return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_-> CompareValues(row1, row2, IDS_ASI_PAGE_COLUMN); } // static gint UrlPickerDialogGtk::CompareURL(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer window) { int row1 = GetRowNumForIter(model, a); int row2 = GetRowNumForIter(model, b); return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_-> CompareValues(row1, row2, IDS_ASI_URL_COLUMN); } // static void UrlPickerDialogGtk::OnUrlEntryChanged(GtkEditable* editable, UrlPickerDialogGtk* window) { window->EnableControls(); } // static void UrlPickerDialogGtk::OnHistorySelectionChanged( GtkTreeSelection *selection, UrlPickerDialogGtk* window) { GtkTreeIter iter; if (!gtk_tree_selection_get_selected(selection, NULL, &iter)) { // The user has unselected the history element, nothing to do. return; } GtkTreePath* path = gtk_tree_model_get_path( GTK_TREE_MODEL(window->history_list_sort_), &iter); gtk_entry_set_text(GTK_ENTRY(window->url_entry_), window->GetURLForPath(path).c_str()); gtk_tree_path_free(path); } void UrlPickerDialogGtk::OnHistoryRowActivated(GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* column, UrlPickerDialogGtk* window) { GURL url(URLFixerUpper::FixupURL(window->GetURLForPath(path), "")); window->callback_->Run(url); gtk_widget_destroy(window->dialog_); } // static void UrlPickerDialogGtk::OnResponse(GtkDialog* dialog, int response_id, UrlPickerDialogGtk* window) { if (response_id == GTK_RESPONSE_OK) { window->AddURL(); } gtk_widget_destroy(window->dialog_); } // static void UrlPickerDialogGtk::OnWindowDestroy(GtkWidget* widget, UrlPickerDialogGtk* window) { MessageLoop::current()->DeleteSoon(FROM_HERE, window); } <|endoftext|>
<commit_before>// btlso_defaulteventmanager_devpoll.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <btlso_defaulteventmanager_devpoll.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(btlso_defaulteventmanager_devpoll_cpp,"$Id$ $CSID$") #include <btlso_timemetrics.h> #include <btlso_flag.h> #include <bsls_timeinterval.h> #include <bdlb_bitmaskutil.h> #include <bdlb_bitutil.h> #include <bdlt_currenttime.h> #include <bsls_assert.h> #if defined(BSLS_PLATFORM_OS_SOLARIS) || defined(BSLS_PLATFORM_OS_HPUX) #include <sys/devpoll.h> #include <unistd.h> #include <fcntl.h> #include <sys/file.h> #include <bsl_algorithm.h> #include <bsl_c_errno.h> #include <bsl_cstring.h> #include <bsl_limits.h> #include <bsl_utility.h> namespace BloombergLP { namespace btlso { namespace { // unnamed namespace for private resources enum { MIN_IOCTL_TIMEOUT_MS = 333 // force spinning of devpoll every 333ms, // otherwise a bug on Solaris may cause // missing events if passing a longer timeout // to ioctl(fd, DP_POLL, ...) }; const int k_POLLFD_SIZE = static_cast<int>(sizeof(struct ::pollfd)); // This object is used to initialize and grow the working arrays passed to // ioctl. This is not strictly necessary but prevents frequent warnings about // uninitialized memory reads in Purify and similar tools without meaningful // cost. static struct ::pollfd DEFAULT_POLLFD; // initialized to 0 as a static struct PollRemoveVisitor { // Visit a set of sockets and populate an array of pollfd to deregister // those sockets. struct ::pollfd *d_pollfdArray; int d_index; PollRemoveVisitor(struct ::pollfd *pollfdArray) { d_pollfdArray = pollfdArray; d_index = -1; } void operator()(int fd) { int i = ++d_index; d_pollfdArray[i].fd = fd; d_pollfdArray[i].events = POLLREMOVE; d_pollfdArray[i].revents = 0; } }; static short convertMask(uint32_t eventMask) // Return a mask with POLLIN set if READ or ACCEPT is set in 'eventMask', // and with POLLOUT set if WRITE or CONNECT is set in 'eventMask'. // Assert that if multiple events are registered, they are READ and WRITE. { int pollinEvents = bdlb::BitUtil::numBitsSet(eventMask & EventType::k_INBOUND_EVENTS); int polloutEvents = bdlb::BitUtil::numBitsSet(eventMask & EventType::k_OUTBOUND_EVENTS); BSLS_ASSERT(2 > pollinEvents); BSLS_ASSERT(2 > polloutEvents); BSLS_ASSERT(!(pollinEvents && polloutEvents) || (eventMask & bdlb::BitMaskUtil::eq(EventType::e_READ) && eventMask & bdlb::BitMaskUtil::eq(EventType::e_WRITE))); return (POLLIN * (short)pollinEvents) | (POLLOUT * (short)polloutEvents); } static inline int dispatchCallbacks(bsl::vector<struct ::pollfd>& signaled, int rfds, EventCallbackRegistry *callbacks) { int numCallbacks = 0; for (int i = 0; i < rfds && i < signaled.size(); ++i) { const struct ::pollfd& currData = signaled[i]; BSLS_ASSERT(currData.revents); int eventMask = callbacks->getRegisteredEventMask(currData.fd); // Read/Accept. if (currData.revents & POLLIN) { if (eventMask & bdlb::BitMaskUtil::eq(EventType::e_READ)) { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_READ)); } else { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_ACCEPT)); } } // Write/Connect. if (currData.revents & POLLOUT) { if (eventMask & bdlb::BitMaskUtil::eq(EventType::e_WRITE)) { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_WRITE)); } else { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_CONNECT)); } } } return numCallbacks; } } // close unnamed namespace // -------------------------------------------- // class DefaultEventManager<Platform::DEVPOLL> // -------------------------------------------- // CREATORS DefaultEventManager<Platform::DEVPOLL>::DefaultEventManager( TimeMetrics *timeMetric, bslma::Allocator *basicAllocator) : d_callbacks(basicAllocator) , d_timeMetric_p(timeMetric) , d_signaled(basicAllocator) , d_dpFd(open("/dev/poll", O_RDWR)) { } DefaultEventManager<Platform::DEVPOLL>::~DefaultEventManager() { int rc = close(d_dpFd); BSLS_ASSERT(0 == rc); } // MANIPULATORS int DefaultEventManager<Platform::DEVPOLL>::dispatch( const bsls::TimeInterval& timeout, int flags) { bsls::TimeInterval now(bdlt::CurrentTime::now()); if (!numEvents()) { if (timeout <= now) { return 0; // RETURN } while (timeout > now) { bsls::TimeInterval currTimeout(timeout - now); struct timespec ts; ts.tv_sec = static_cast<time_t>( bsl::min(static_cast<bsls::Types::Int64>( bsl::numeric_limits<time_t>::max()), currTimeout.seconds())); ts.tv_nsec = currTimeout.nanoseconds(); // Sleep till it's time. int savedErrno; int rc; if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rc = nanosleep(&ts, 0); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rc = nanosleep(&ts, 0); savedErrno = errno; } errno = 0; if (0 > rc) { if (EINTR == savedErrno) { if (flags & btlso::Flag::k_ASYNC_INTERRUPT) { return -1; // RETURN } } else { return -2; // RETURN } } now = bdlt::CurrentTime::now(); } return 0; // RETURN } int ncbs = 0; // number of callbacks dispatched do { int rfds; // number of returned sockets int savedErrno = 0; // saved errno value set by poll do { d_signaled.resize(d_callbacks.numSockets(), DEFAULT_POLLFD); struct dvpoll dopoll; dopoll.dp_nfds = d_signaled.size(); dopoll.dp_fds = &d_signaled.front(); if (timeout < now) { // The ioctl() call should return immediately. dopoll.dp_timeout = 0; } else { // Calculate the time remaining for the ioctl() call. bsls::TimeInterval curr_timeout(timeout - now); // Convert this timeout to a 32 bit value in milliseconds. dopoll.dp_timeout = static_cast<int>( bsl::min(static_cast<bsls::Types::Int64>( bsl::numeric_limits<int>::max()), curr_timeout.seconds() * 1000 + curr_timeout.nanoseconds() / 1000000 + 1)); } dopoll.dp_timeout = bsl::min( dopoll.dp_timeout, static_cast<int>(MIN_IOCTL_TIMEOUT_MS)); if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; } errno = 0; now = bdlt::CurrentTime::now(); } while ((0 > rfds && EINTR == savedErrno) && !(btlso::Flag::k_ASYNC_INTERRUPT & flags) && now < timeout); if (0 >= rfds) { return rfds ? -1 == rfds && EINTR == savedErrno ? -1 : -2 : 0; // RETURN } ncbs += dispatchCallbacks(d_signaled, rfds, &d_callbacks); now = bdlt::CurrentTime::now(); } while (0 == ncbs && now < timeout); return ncbs; } int DefaultEventManager<Platform::DEVPOLL>::dispatch(int flags) { if (!numEvents()) { return 0; // RETURN } int ncbs = 0; // number of callbacks dispatched while (0 == ncbs) { int rfds; // number of returned fds int savedErrno = 0; // saved errno value set by 'poll' d_signaled.resize(d_callbacks.numSockets(), DEFAULT_POLLFD); struct dvpoll dopoll; dopoll.dp_nfds = d_signaled.size(); dopoll.dp_fds = &d_signaled.front(); dopoll.dp_timeout = MIN_IOCTL_TIMEOUT_MS; do { if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; } errno = 0; } while ((0 > rfds && EINTR == savedErrno) && !(btlso::Flag::k_ASYNC_INTERRUPT & flags)); if (0 >= rfds) { return rfds ? -1 == rfds && EINTR == savedErrno ? -1 : -2 : 0; // RETURN } ncbs += dispatchCallbacks(d_signaled, rfds, &d_callbacks); } return ncbs; } int DefaultEventManager<Platform::DEVPOLL>::registerSocketEvent( const SocketHandle::Handle& handle, const EventType::Type event, const EventManager::Callback& callback) { Event handleEvent(handle, event); uint32_t newMask = d_callbacks.registerCallback(handleEvent, callback); if (0 == newMask) { // We replaced an existing callback function. return 0; // RETURN } // Prepare a ::pollfd object to write to /dev/poll struct ::pollfd pfd; pfd.fd = handle; pfd.revents = 0; // just to satisfy purify // Calculate the new event mask pfd.events = convertMask(newMask); // Write the new event mask for this fd to /dev/poll. ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); if (k_POLLFD_SIZE != rc) { // Unregister the event we added earlier. d_callbacks.remove(handleEvent); return errno; // RETURN } return 0; } void DefaultEventManager<Platform::DEVPOLL>::deregisterSocketEvent( const SocketHandle::Handle& handle, EventType::Type event) { Event handleEvent(handle, event); bool removed = d_callbacks.remove(handleEvent); BSLS_ASSERT(removed); // Retrieve the new event mask int eventmask = convertMask(d_callbacks.getRegisteredEventMask(handle)); // Prepare a ::pollfd object to write to /dev/poll // First, we need to remove this socket handle from the set. // The write it out with a new mask, if applicable. struct ::pollfd pfd; pfd.fd = handle; pfd.events = POLLREMOVE; pfd.revents = 0; // just to satisfy purify ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); if (eventmask) { // Write the new event mask for this fd to /dev/poll. pfd.events = static_cast<short>(eventmask); ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); } } int DefaultEventManager<Platform::DEVPOLL>::deregisterSocket( const SocketHandle::Handle& handle) { int eventmask = d_callbacks.getRegisteredEventMask(handle); if (0 == eventmask) { // No registered events, nothing to do. return 0; // RETURN } struct ::pollfd req; req.fd = handle; req.events = POLLREMOVE; req.revents = 0; ssize_t rc = ::write(d_dpFd, &req, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); return d_callbacks.removeSocket(handle); } void DefaultEventManager<Platform::DEVPOLL>::deregisterAll() { bsl::vector<struct ::pollfd> removed(d_callbacks.numSockets(), DEFAULT_POLLFD); if (!removed.empty()) { PollRemoveVisitor visitor(&removed.front()); d_callbacks.visitSockets(&visitor); int pollfdSize = removed.size() * k_POLLFD_SIZE; ssize_t rc = write(d_dpFd, &removed.front(), pollfdSize); BSLS_ASSERT(pollfdSize == rc); } d_callbacks.removeAll(); } // ACCESSORS int DefaultEventManager<Platform::DEVPOLL>::numSocketEvents( const SocketHandle::Handle& handle) const { return bdlb::BitUtil::numBitsSet( d_callbacks.getRegisteredEventMask(handle)); } int DefaultEventManager<Platform::DEVPOLL>::numEvents() const { return d_callbacks.numCallbacks(); } int DefaultEventManager<Platform::DEVPOLL>::isRegistered( const SocketHandle::Handle& handle, const EventType::Type event) const { return d_callbacks.contains(Event(handle, event)); } } // close package namespace } // close namespace BloombergLP #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>fix nightly build for sun gcc 4.9.2<commit_after>// btlso_defaulteventmanager_devpoll.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <btlso_defaulteventmanager_devpoll.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(btlso_defaulteventmanager_devpoll_cpp,"$Id$ $CSID$") #include <btlso_timemetrics.h> #include <btlso_flag.h> #include <bsls_timeinterval.h> #include <bdlb_bitmaskutil.h> #include <bdlb_bitutil.h> #include <bdlt_currenttime.h> #include <bsls_assert.h> #if defined(BSLS_PLATFORM_OS_SOLARIS) || defined(BSLS_PLATFORM_OS_HPUX) #include <sys/devpoll.h> #include <unistd.h> #include <fcntl.h> #include <sys/file.h> #include <bsl_algorithm.h> #include <bsl_c_errno.h> #include <bsl_cstring.h> #include <bsl_limits.h> #include <bsl_utility.h> namespace BloombergLP { namespace btlso { namespace { // unnamed namespace for private resources enum { MIN_IOCTL_TIMEOUT_MS = 333 // force spinning of devpoll every 333ms, // otherwise a bug on Solaris may cause // missing events if passing a longer timeout // to ioctl(fd, DP_POLL, ...) }; const int k_POLLFD_SIZE = static_cast<int>(sizeof(struct ::pollfd)); // This object is used to initialize and grow the working arrays passed to // ioctl. This is not strictly necessary but prevents frequent warnings about // uninitialized memory reads in Purify and similar tools without meaningful // cost. static struct ::pollfd DEFAULT_POLLFD; // initialized to 0 as a static struct PollRemoveVisitor { // Visit a set of sockets and populate an array of pollfd to deregister // those sockets. struct ::pollfd *d_pollfdArray; int d_index; PollRemoveVisitor(struct ::pollfd *pollfdArray) { d_pollfdArray = pollfdArray; d_index = -1; } void operator()(int fd) { int i = ++d_index; d_pollfdArray[i].fd = fd; d_pollfdArray[i].events = POLLREMOVE; d_pollfdArray[i].revents = 0; } }; static short convertMask(uint32_t eventMask) // Return a mask with POLLIN set if READ or ACCEPT is set in 'eventMask', // and with POLLOUT set if WRITE or CONNECT is set in 'eventMask'. // Assert that if multiple events are registered, they are READ and WRITE. { int pollinEvents = bdlb::BitUtil::numBitsSet(eventMask & EventType::k_INBOUND_EVENTS); int polloutEvents = bdlb::BitUtil::numBitsSet(eventMask & EventType::k_OUTBOUND_EVENTS); BSLS_ASSERT(2 > pollinEvents); BSLS_ASSERT(2 > polloutEvents); BSLS_ASSERT(!(pollinEvents && polloutEvents) || (eventMask & bdlb::BitMaskUtil::eq(EventType::e_READ) && eventMask & bdlb::BitMaskUtil::eq(EventType::e_WRITE))); return static_cast<short>( (POLLIN * static_cast<short>(pollinEvents)) | (POLLOUT * static_cast<short>(polloutEvents))); } static inline int dispatchCallbacks(bsl::vector<struct ::pollfd>& signaled, int rfds, EventCallbackRegistry *callbacks) { int numCallbacks = 0; for (int i = 0; i < rfds && i < static_cast<int>(signaled.size()); ++i) { const struct ::pollfd& currData = signaled[i]; BSLS_ASSERT(currData.revents); int eventMask = callbacks->getRegisteredEventMask(currData.fd); // Read/Accept. if (currData.revents & POLLIN) { if (eventMask & bdlb::BitMaskUtil::eq(EventType::e_READ)) { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_READ)); } else { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_ACCEPT)); } } // Write/Connect. if (currData.revents & POLLOUT) { if (eventMask & bdlb::BitMaskUtil::eq(EventType::e_WRITE)) { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_WRITE)); } else { numCallbacks += !callbacks->invoke(Event(currData.fd, EventType::e_CONNECT)); } } } return numCallbacks; } } // close unnamed namespace // -------------------------------------------- // class DefaultEventManager<Platform::DEVPOLL> // -------------------------------------------- // CREATORS DefaultEventManager<Platform::DEVPOLL>::DefaultEventManager( TimeMetrics *timeMetric, bslma::Allocator *basicAllocator) : d_callbacks(basicAllocator) , d_timeMetric_p(timeMetric) , d_signaled(basicAllocator) , d_dpFd(open("/dev/poll", O_RDWR)) { } DefaultEventManager<Platform::DEVPOLL>::~DefaultEventManager() { int rc = close(d_dpFd); BSLS_ASSERT(0 == rc); } // MANIPULATORS int DefaultEventManager<Platform::DEVPOLL>::dispatch( const bsls::TimeInterval& timeout, int flags) { bsls::TimeInterval now(bdlt::CurrentTime::now()); if (!numEvents()) { if (timeout <= now) { return 0; // RETURN } while (timeout > now) { bsls::TimeInterval currTimeout(timeout - now); struct timespec ts; ts.tv_sec = static_cast<time_t>( bsl::min(static_cast<bsls::Types::Int64>( bsl::numeric_limits<time_t>::max()), currTimeout.seconds())); ts.tv_nsec = currTimeout.nanoseconds(); // Sleep till it's time. int savedErrno; int rc; if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rc = nanosleep(&ts, 0); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rc = nanosleep(&ts, 0); savedErrno = errno; } errno = 0; if (0 > rc) { if (EINTR == savedErrno) { if (flags & btlso::Flag::k_ASYNC_INTERRUPT) { return -1; // RETURN } } else { return -2; // RETURN } } now = bdlt::CurrentTime::now(); } return 0; // RETURN } int ncbs = 0; // number of callbacks dispatched do { int rfds; // number of returned sockets int savedErrno = 0; // saved errno value set by poll do { d_signaled.resize(d_callbacks.numSockets(), DEFAULT_POLLFD); struct dvpoll dopoll; dopoll.dp_nfds = d_signaled.size(); dopoll.dp_fds = &d_signaled.front(); if (timeout < now) { // The ioctl() call should return immediately. dopoll.dp_timeout = 0; } else { // Calculate the time remaining for the ioctl() call. bsls::TimeInterval curr_timeout(timeout - now); // Convert this timeout to a 32 bit value in milliseconds. dopoll.dp_timeout = static_cast<int>( bsl::min(static_cast<bsls::Types::Int64>( bsl::numeric_limits<int>::max()), curr_timeout.seconds() * 1000 + curr_timeout.nanoseconds() / 1000000 + 1)); } dopoll.dp_timeout = bsl::min( dopoll.dp_timeout, static_cast<int>(MIN_IOCTL_TIMEOUT_MS)); if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; } errno = 0; now = bdlt::CurrentTime::now(); } while ((0 > rfds && EINTR == savedErrno) && !(btlso::Flag::k_ASYNC_INTERRUPT & flags) && now < timeout); if (0 >= rfds) { return rfds ? -1 == rfds && EINTR == savedErrno ? -1 : -2 : 0; // RETURN } ncbs += dispatchCallbacks(d_signaled, rfds, &d_callbacks); now = bdlt::CurrentTime::now(); } while (0 == ncbs && now < timeout); return ncbs; } int DefaultEventManager<Platform::DEVPOLL>::dispatch(int flags) { if (!numEvents()) { return 0; // RETURN } int ncbs = 0; // number of callbacks dispatched while (0 == ncbs) { int rfds; // number of returned fds int savedErrno = 0; // saved errno value set by 'poll' d_signaled.resize(d_callbacks.numSockets(), DEFAULT_POLLFD); struct dvpoll dopoll; dopoll.dp_nfds = d_signaled.size(); dopoll.dp_fds = &d_signaled.front(); dopoll.dp_timeout = MIN_IOCTL_TIMEOUT_MS; do { if (d_timeMetric_p) { d_timeMetric_p->switchTo(TimeMetrics::e_IO_BOUND); rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; d_timeMetric_p->switchTo(TimeMetrics::e_CPU_BOUND); } else { rfds = ioctl(d_dpFd, DP_POLL, &dopoll); savedErrno = errno; } errno = 0; } while ((0 > rfds && EINTR == savedErrno) && !(btlso::Flag::k_ASYNC_INTERRUPT & flags)); if (0 >= rfds) { return rfds ? -1 == rfds && EINTR == savedErrno ? -1 : -2 : 0; // RETURN } ncbs += dispatchCallbacks(d_signaled, rfds, &d_callbacks); } return ncbs; } int DefaultEventManager<Platform::DEVPOLL>::registerSocketEvent( const SocketHandle::Handle& handle, const EventType::Type event, const EventManager::Callback& callback) { Event handleEvent(handle, event); uint32_t newMask = d_callbacks.registerCallback(handleEvent, callback); if (0 == newMask) { // We replaced an existing callback function. return 0; // RETURN } // Prepare a ::pollfd object to write to /dev/poll struct ::pollfd pfd; pfd.fd = handle; pfd.revents = 0; // just to satisfy purify // Calculate the new event mask pfd.events = convertMask(newMask); // Write the new event mask for this fd to /dev/poll. ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); if (k_POLLFD_SIZE != rc) { // Unregister the event we added earlier. d_callbacks.remove(handleEvent); return errno; // RETURN } return 0; } void DefaultEventManager<Platform::DEVPOLL>::deregisterSocketEvent( const SocketHandle::Handle& handle, EventType::Type event) { Event handleEvent(handle, event); bool removed = d_callbacks.remove(handleEvent); BSLS_ASSERT(removed); // Retrieve the new event mask int eventmask = convertMask(d_callbacks.getRegisteredEventMask(handle)); // Prepare a ::pollfd object to write to /dev/poll // First, we need to remove this socket handle from the set. // The write it out with a new mask, if applicable. struct ::pollfd pfd; pfd.fd = handle; pfd.events = POLLREMOVE; pfd.revents = 0; // just to satisfy purify ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); if (eventmask) { // Write the new event mask for this fd to /dev/poll. pfd.events = static_cast<short>(eventmask); ssize_t rc = write(d_dpFd, &pfd, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); } } int DefaultEventManager<Platform::DEVPOLL>::deregisterSocket( const SocketHandle::Handle& handle) { int eventmask = d_callbacks.getRegisteredEventMask(handle); if (0 == eventmask) { // No registered events, nothing to do. return 0; // RETURN } struct ::pollfd req; req.fd = handle; req.events = POLLREMOVE; req.revents = 0; ssize_t rc = ::write(d_dpFd, &req, k_POLLFD_SIZE); BSLS_ASSERT(k_POLLFD_SIZE == rc); return d_callbacks.removeSocket(handle); } void DefaultEventManager<Platform::DEVPOLL>::deregisterAll() { bsl::vector<struct ::pollfd> removed(d_callbacks.numSockets(), DEFAULT_POLLFD); if (!removed.empty()) { PollRemoveVisitor visitor(&removed.front()); d_callbacks.visitSockets(&visitor); int pollfdSize = removed.size() * k_POLLFD_SIZE; ssize_t rc = write(d_dpFd, &removed.front(), pollfdSize); BSLS_ASSERT(pollfdSize == rc); } d_callbacks.removeAll(); } // ACCESSORS int DefaultEventManager<Platform::DEVPOLL>::numSocketEvents( const SocketHandle::Handle& handle) const { return bdlb::BitUtil::numBitsSet( d_callbacks.getRegisteredEventMask(handle)); } int DefaultEventManager<Platform::DEVPOLL>::numEvents() const { return d_callbacks.numCallbacks(); } int DefaultEventManager<Platform::DEVPOLL>::isRegistered( const SocketHandle::Handle& handle, const EventType::Type event) const { return d_callbacks.contains(Event(handle, event)); } } // close package namespace } // close namespace BloombergLP #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <stddef.h> #include <libpstack/dwarf.h> #include <libpstack/proc.h> #include <python2.7/Python.h> #include <python2.7/frameobject.h> static bool pthreadTidOffset(const Process &proc, size_t *offsetp) { static size_t offset; static enum { notDone, notFound, found } status; if (status == notDone) { try { auto addr = proc.findNamedSymbol(0, "_thread_db_pthread_tid"); uint32_t desc[3]; proc.io->readObj(addr, &desc[0], 3); offset = desc[2]; status = found; if (verbose) *debug << "found thread offset " << offset << "\n"; } catch (const std::exception &ex) { if (verbose) *debug << "failed to find offset of tid in pthread: " << ex.what(); status = notFound; } } if (status == found) { *offsetp = offset; return true; } return false; } /* * process one python thread in an interpreter, at remote addr "ptr". * returns the address of the next thread on the list. */ Elf_Addr doPyThread(Process &proc, std::ostream &os, Elf_Addr ptr) { PyThreadState thread; proc.io->readObj(ptr, &thread); PyFrameObject frame; size_t toff; if (thread.thread_id && pthreadTidOffset(proc, &toff)) { Elf_Addr tidptr = thread.thread_id + toff; pid_t tid; proc.io->readObj(tidptr, &tid); os << "pthread: 0x" << std::hex << thread.thread_id << std::dec << ", lwp " << tid; } else { os << "anonymous thread"; } os << "\n"; for (auto framePtr = Elf_Addr(thread.frame); framePtr != 0; framePtr = Elf_Addr(frame.f_back)) { proc.io->readObj(framePtr, &frame); PyCodeObject code; proc.io->readObj(Elf_Addr(frame.f_code), &code); auto func = proc.io->readString(Elf_Addr(code.co_name) + offsetof(PyStringObject, ob_sval)); auto file = proc.io->readString(Elf_Addr(code.co_filename) + offsetof(PyStringObject, ob_sval)); os << "\t" << func << " in " << file << ":" << frame.f_lineno << "\n"; } return Elf_Addr(thread.next); } /* * Process one python interpreter in the process at remote address ptr * Returns the address of the next interpreter on on the process's list. */ Elf32_Addr doPyInterp(Process &proc, std::ostream &os, Elf_Addr ptr) { PyInterpreterState state; proc.io->readObj(ptr, &state); os << "---- interpreter @" << std::hex << ptr << std::dec << " -----" << std::endl ; for (Elf_Addr tsp = reinterpret_cast<Elf_Addr>(state.tstate_head); tsp; ) { tsp = doPyThread(proc, os, tsp); os << std::endl; } return reinterpret_cast<Elf_Addr>(state.next); } /* * Print all python stack traces from this process. */ std::ostream & pythonStack(Process &proc, std::ostream &os, const PstackOptions &) { // Find the python library. for (auto &o : proc.objects) { std::string module = stringify(*o.object->io); if (module.find("python") == std::string::npos) continue; auto dwarf = proc.imageCache.getDwarf(ElfObject::getDebug(o.object)); if (!dwarf) continue; for (auto u : dwarf->getUnits()) { // For each unit for (const DwarfEntry *compile : u->entries) { if (compile->type->tag != DW_TAG_compile_unit) continue; // Do we have a global variable called interp_head? for (const DwarfEntry *var : compile->children) { if (var->type->tag != DW_TAG_variable) continue; if (var->name() != "interp_head") continue; // Yes - let's run through the interpreters, and dump their stacks. DwarfExpressionStack evalStack; auto addr = evalStack.eval(proc, var->attrForName(DW_AT_location), 0, o.reloc); Elf_Addr ptr; for (proc.io->readObj(addr, &ptr); ptr; ) ptr = doPyInterp(proc, os, ptr); } } } } return os; } <commit_msg>Fix line numbers for python traces.<commit_after>#include <iostream> #include <stdlib.h> #include <stddef.h> #include <libpstack/dwarf.h> #include <libpstack/proc.h> #include <python2.7/Python.h> #include <python2.7/frameobject.h> static bool pthreadTidOffset(const Process &proc, size_t *offsetp) { static size_t offset; static enum { notDone, notFound, found } status; if (status == notDone) { try { auto addr = proc.findNamedSymbol(0, "_thread_db_pthread_tid"); uint32_t desc[3]; proc.io->readObj(addr, &desc[0], 3); offset = desc[2]; status = found; if (verbose) *debug << "found thread offset " << offset << "\n"; } catch (const std::exception &ex) { if (verbose) *debug << "failed to find offset of tid in pthread: " << ex.what(); status = notFound; } } if (status == found) { *offsetp = offset; return true; } return false; } // This reimplements PyCode_Addr2Line int getLine(Process *proc, const PyCodeObject *code, const PyFrameObject *frame) { PyVarObject lnotab; proc->io->readObj(Elf_Addr(code->co_lnotab), &lnotab); unsigned char linedata[lnotab.ob_size]; proc->io->readObj(Elf_Addr(code->co_lnotab) + offsetof(PyStringObject, ob_sval), &linedata[0], lnotab.ob_size); int line = code->co_firstlineno; int addr = 0; unsigned char *p = linedata; unsigned char *e = linedata + lnotab.ob_size; while (p < e) { addr += *p++; if (addr > frame->f_lasti) { break; } line += *p++; } return line; } /* * process one python thread in an interpreter, at remote addr "ptr". * returns the address of the next thread on the list. */ Elf_Addr doPyThread(Process &proc, std::ostream &os, Elf_Addr ptr) { PyThreadState thread; proc.io->readObj(ptr, &thread); PyFrameObject frame; size_t toff; if (thread.thread_id && pthreadTidOffset(proc, &toff)) { Elf_Addr tidptr = thread.thread_id + toff; pid_t tid; proc.io->readObj(tidptr, &tid); os << "pthread: 0x" << std::hex << thread.thread_id << std::dec << ", lwp " << tid; } else { os << "anonymous thread"; } os << "\n"; for (auto framePtr = Elf_Addr(thread.frame); framePtr != 0; framePtr = Elf_Addr(frame.f_back)) { proc.io->readObj(framePtr, &frame); PyCodeObject code; proc.io->readObj(Elf_Addr(frame.f_code), &code); auto lineNo = getLine(&proc, &code, &frame); auto func = proc.io->readString(Elf_Addr(code.co_name) + offsetof(PyStringObject, ob_sval)); auto file = proc.io->readString(Elf_Addr(code.co_filename) + offsetof(PyStringObject, ob_sval)); os << "\t" << func << " in " << file << ":" << lineNo << "\n"; } return Elf_Addr(thread.next); } /* * Process one python interpreter in the process at remote address ptr * Returns the address of the next interpreter on on the process's list. */ Elf32_Addr doPyInterp(Process &proc, std::ostream &os, Elf_Addr ptr) { PyInterpreterState state; proc.io->readObj(ptr, &state); os << "---- interpreter @" << std::hex << ptr << std::dec << " -----" << std::endl ; for (Elf_Addr tsp = reinterpret_cast<Elf_Addr>(state.tstate_head); tsp; ) { tsp = doPyThread(proc, os, tsp); os << std::endl; } return reinterpret_cast<Elf_Addr>(state.next); } /* * Print all python stack traces from this process. */ std::ostream & pythonStack(Process &proc, std::ostream &os, const PstackOptions &) { // Find the python library. for (auto &o : proc.objects) { std::string module = stringify(*o.object->io); if (module.find("python") == std::string::npos) continue; auto dwarf = proc.imageCache.getDwarf(ElfObject::getDebug(o.object)); if (!dwarf) continue; for (auto u : dwarf->getUnits()) { // For each unit for (const DwarfEntry *compile : u->entries) { if (compile->type->tag != DW_TAG_compile_unit) continue; // Do we have a global variable called interp_head? for (const DwarfEntry *var : compile->children) { if (var->type->tag != DW_TAG_variable) continue; if (var->name() != "interp_head") continue; // Yes - let's run through the interpreters, and dump their stacks. DwarfExpressionStack evalStack; auto addr = evalStack.eval(proc, var->attrForName(DW_AT_location), 0, o.reloc); Elf_Addr ptr; for (proc.io->readObj(addr, &ptr); ptr; ) ptr = doPyInterp(proc, os, ptr); } } } } return os; } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "SoftXMT.hpp" #include "Addressing.hpp" #include "Cache.hpp" #include "ForkJoin.hpp" #include "GlobalAllocator.hpp" BOOST_AUTO_TEST_SUITE( ForkJoin_tests ); #define MEM_SIZE 1<<24; struct func_initialize : public ForkJoinIteration { GlobalAddress<int64_t> base_addr; int64_t value; void operator()(int64_t index) { VLOG(2) << "called func_initialize with index = " << index; Incoherent<int64_t>::RW c(base_addr+index, 1); c[0] = value+index; } }; struct func_hello : public ForkJoinIteration { void operator()(int64_t index) { LOG(INFO) << "Hello from " << index << "!"; } }; static void user_main(Thread * me, void * args) { LOG(INFO) << "beginning user main... (" << SoftXMT_mynode() << ")"; { size_t N = 128; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } { size_t N = 101; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } { func_hello f; fork_join_custom(&f); } { size_t N = fLI64::FLAGS_max_forkjoin_threads_per_node * SoftXMT_nodes() * 3 + 13; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } SoftXMT_signal_done(); } BOOST_AUTO_TEST_CASE( test1 ) { SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv), 1<<14); SoftXMT_activate(); SoftXMT_run_user_main(&user_main, NULL); LOG(INFO) << "finishing..."; SoftXMT_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Fixed ForkJoin_test for user_main as task<commit_after>#include <boost/test/unit_test.hpp> #include "SoftXMT.hpp" #include "Addressing.hpp" #include "Cache.hpp" #include "ForkJoin.hpp" #include "GlobalAllocator.hpp" BOOST_AUTO_TEST_SUITE( ForkJoin_tests ); #define MEM_SIZE 1<<24; struct func_initialize : public ForkJoinIteration { GlobalAddress<int64_t> base_addr; int64_t value; void operator()(int64_t index) { VLOG(2) << "called func_initialize with index = " << index; Incoherent<int64_t>::RW c(base_addr+index, 1); c[0] = value+index; } }; struct func_hello : public ForkJoinIteration { void operator()(int64_t index) { LOG(INFO) << "Hello from " << index << "!"; } }; static void user_main(int * args) { LOG(INFO) << "beginning user main.... (" << SoftXMT_mynode() << ")"; { size_t N = 128; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } { size_t N = 101; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } { func_hello f; fork_join_custom(&f); } { size_t N = 128 + 13; GlobalAddress<int64_t> data = SoftXMT_typed_malloc<int64_t>(N); func_initialize a; a.base_addr = data; a.value = 0; fork_join(&a, 0, N); VLOG(2) << "done with init"; for (size_t i=0; i<N; i++) { Incoherent<int64_t>::RO c(data+i, 1); VLOG(2) << i << " == " << *c; BOOST_CHECK_EQUAL(i, *c); } SoftXMT_free(data); } } BOOST_AUTO_TEST_CASE( test1 ) { SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv), 1<<20); SoftXMT_activate(); SoftXMT_run_user_main(&user_main, (int*)NULL); LOG(INFO) << "finishing..."; SoftXMT_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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 "iceoryx_posh/popo/modern_api/typed_subscriber.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_posh/runtime/posh_runtime.hpp" #include "topic_data.hpp" #include <chrono> #include <csignal> #include <iostream> bool killswitch = false; static void sigHandler(int f_sig [[gnu::unused]]) { // caught SIGINT, now exit gracefully killswitch = true; } int main() { // register sigHandler for SIGINT signal(SIGINT, sigHandler); // initialize runtime iox::runtime::PoshRuntime::getInstance("/iox-ex-subscriber-typed-modern"); // initialized subscribers iox::popo::TypedSubscriber<Position> typedSubscriber({"Odometry", "Position", "Vehicle"}); typedSubscriber.subscribe(); // set up waitset iox::popo::WaitSet waitSet{}; waitSet.attachCondition(typedSubscriber); // run until interrupted while(!killswitch) { auto triggeredConditions = waitSet.wait(); for(auto& condition : triggeredConditions) { /// @todo How to ensure the condition is a subscriber ? What about guard conditions? auto subscriber = dynamic_cast<iox::popo::TypedSubscriber<Position>*>(condition); subscriber->receive().and_then([](iox::cxx::optional<iox::popo::Sample<const Position>>& maybePosition){ if(maybePosition.has_value()) { auto& position = maybePosition.value(); std::cout << "Got value: (" << position->x << ", " << position->y << ", " << position->z << ")" << std::endl; } }); } } waitSet.detachAllConditions(); return (EXIT_SUCCESS); } <commit_msg>iox-#252 Move subscriber handling logic to own thread and set up guard condition to shutdown gracefully.<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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 "iceoryx_posh/popo/modern_api/typed_subscriber.hpp" #include "iceoryx_posh/popo/guard_condition.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_posh/runtime/posh_runtime.hpp" #include "topic_data.hpp" #include <chrono> #include <csignal> #include <iostream> bool killswitch = false; iox::popo::GuardCondition shutdownGuard; static void sigHandler(int f_sig [[gnu::unused]]) { // caught SIGINT, now exit gracefully killswitch = true; shutdownGuard.trigger(); // unblock waitsets } void handler(iox::popo::WaitSet& waitSet) { // run until interrupted while(!killswitch) { auto triggeredConditions = waitSet.wait(); for(auto& condition : triggeredConditions) { auto subscriber = dynamic_cast<iox::popo::TypedSubscriber<Position>*>(condition); if(subscriber) { // new data received on an attached subscriber subscriber->receive().and_then([](iox::cxx::optional<iox::popo::Sample<const Position>>& maybePosition){ if(maybePosition.has_value()) { auto& position = maybePosition.value(); std::cout << "Got value: (" << position->x << ", " << position->y << ", " << position->z << ")" << std::endl; } }); } else { // shutdown guard has triggered std::cout << "Shutdown Guard triggered. Shutting down." << std::endl; } } } } int main() { // register sigHandler for SIGINT signal(SIGINT, sigHandler); // initialize runtime iox::runtime::PoshRuntime::getInstance("/iox-ex-subscriber-typed-modern"); // initialized subscribers iox::popo::TypedSubscriber<Position> typedSubscriber({"Odometry", "Position", "Vehicle"}); typedSubscriber.subscribe(); // set up waitset iox::popo::WaitSet waitSet{}; waitSet.attachCondition(typedSubscriber); waitSet.attachCondition(shutdownGuard); // delegate handling of received data to another thread std::thread handlerThread(handler, std::ref(waitSet)); handlerThread.join(); // clean up waitSet.detachAllConditions(); return (EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vie_autotest.h" #include "base_primitives.h" #include "general_primitives.h" #include "tb_interfaces.h" #include "vie_autotest_defines.h" #include "video_capture_factory.h" class BaseObserver : public webrtc::ViEBaseObserver { public: BaseObserver() : cpu_load_(0) {} virtual void PerformanceAlarm(const unsigned int cpu_load) { cpu_load_ = cpu_load; } unsigned int cpu_load_; }; void ViEAutoTest::ViEBaseStandardTest() { // *************************************************************** // Begin create/initialize WebRTC Video Engine for testing // *************************************************************** TbInterfaces interfaces("ViEBaseStandardTest"); // *************************************************************** // Engine ready. Set up the test case: // *************************************************************** int video_channel = -1; EXPECT_EQ(0, interfaces.base->CreateChannel(video_channel)); webrtc::VideoCaptureModule* video_capture_module(NULL); const unsigned int kMaxDeviceNameLength = 128; char device_name[kMaxDeviceNameLength]; memset(device_name, 0, kMaxDeviceNameLength); int capture_id; webrtc::ViEBase *base_interface = interfaces.base; webrtc::ViERender *render_interface = interfaces.render; webrtc::ViECapture *capture_interface = interfaces.capture; FindCaptureDeviceOnSystem(capture_interface, device_name, kMaxDeviceNameLength, &capture_id, &video_capture_module); EXPECT_EQ(0, capture_interface->ConnectCaptureDevice(capture_id, video_channel)); EXPECT_EQ(0, capture_interface->StartCapture(capture_id)); ConfigureRtpRtcp(interfaces.rtp_rtcp, video_channel); EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm1)); EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm2)); RenderInWindow(render_interface, capture_id, _window1, 0); RenderInWindow(render_interface, video_channel, _window2, 1); // *************************************************************** // Run the actual test: // *************************************************************** ViETest::Log("You should shortly see a local preview from camera %s" " in window 1 and the remote video in window 2.", device_name); ::TestI420CallSetup(interfaces.codec, interfaces.video_engine, base_interface, interfaces.network, video_channel, device_name); // *************************************************************** // Testing finished. Tear down Video Engine // *************************************************************** EXPECT_EQ(0, capture_interface->StopCapture(capture_id)); EXPECT_EQ(0, base_interface->StopReceive(video_channel)); StopAndRemoveRenderers(base_interface, render_interface, video_channel, capture_id); EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm1)); EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm2)); EXPECT_EQ(0, capture_interface->ReleaseCaptureDevice(capture_id)); video_capture_module->Release(); video_capture_module = NULL; EXPECT_EQ(0, base_interface->DeleteChannel(video_channel)); } void ViEAutoTest::ViEBaseExtendedTest() { // Start with standard test ViEBaseAPITest(); ViEBaseStandardTest(); // *************************************************************** // Test BaseObserver // *************************************************************** // TODO(mflodman) Add test for base observer. Cpu load must be over 75%. // BaseObserver base_observer; // EXPECT_EQ(ptrViEBase->RegisterObserver(base_observer), 0); // // AutoTestSleep(KAutoTestSleepTimeMs); // // EXPECT_EQ(ptrViEBase->DeregisterObserver(), 0); // EXPECT_GT(base_observer.cpu_load, 0); } void ViEAutoTest::ViEBaseAPITest() { // *************************************************************** // Begin create/initialize WebRTC Video Engine for testing // *************************************************************** // Get the ViEBase API webrtc::ViEBase* ptrViEBase = webrtc::ViEBase::GetInterface(NULL); EXPECT_EQ(NULL, ptrViEBase) << "Should return null for a bad ViE pointer"; webrtc::VideoEngine* ptrViE = webrtc::VideoEngine::Create(); EXPECT_TRUE(NULL != ptrViE); std::string trace_file_path = ViETest::GetResultOutputPath() + "ViEBaseAPI_trace.txt"; EXPECT_EQ(0, ptrViE->SetTraceFile(trace_file_path.c_str())); ptrViEBase = webrtc::ViEBase::GetInterface(ptrViE); EXPECT_TRUE(NULL != ptrViEBase); // *************************************************************** // Engine ready. Begin testing class // *************************************************************** char version[1024] = ""; EXPECT_EQ(0, ptrViEBase->GetVersion(version)); EXPECT_EQ(0, ptrViEBase->LastError()); // Create without init int videoChannel = -1; EXPECT_NE(0, ptrViEBase->CreateChannel(videoChannel)) << "Should fail since Init has not been called yet"; EXPECT_EQ(0, ptrViEBase->Init()); EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel)); int videoChannel2 = -1; EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2)); EXPECT_NE(videoChannel, videoChannel2) << "Should allocate new number for independent channel"; EXPECT_EQ(0, ptrViEBase->DeleteChannel(videoChannel2)); EXPECT_EQ(-1, ptrViEBase->CreateChannel(videoChannel2, videoChannel + 1)) << "Should fail since neither channel exists (the second must)"; EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2, videoChannel)); // Test Voice Engine integration with Video Engine. webrtc::VoiceEngine* ptrVoE = NULL; webrtc::VoEBase* ptrVoEBase = NULL; int audioChannel = -1; ptrVoE = webrtc::VoiceEngine::Create(); EXPECT_TRUE(NULL != ptrVoE); ptrVoEBase = webrtc::VoEBase::GetInterface(ptrVoE); EXPECT_TRUE(NULL != ptrVoEBase); EXPECT_EQ(0, ptrVoEBase->Init()); audioChannel = ptrVoEBase->CreateChannel(); EXPECT_NE(-1, audioChannel); // Connect before setting VoE. EXPECT_NE(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)) << "Should fail since Voice Engine is not set yet."; // Then do it right. EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(ptrVoE)); EXPECT_EQ(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)); // *************************************************************** // Testing finished. Tear down Video Engine // *************************************************************** EXPECT_NE(0, ptrViEBase->DisconnectAudioChannel(videoChannel + 5)) << "Should fail: disconnecting bogus channel"; EXPECT_EQ(0, ptrViEBase->DisconnectAudioChannel(videoChannel)); // Clean up voice engine EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(NULL)); EXPECT_EQ(0, ptrVoEBase->Release()); EXPECT_TRUE(webrtc::VoiceEngine::Delete(ptrVoE)); webrtc::ViEBase* ptrViEBase2 = webrtc::ViEBase::GetInterface(ptrViE); EXPECT_TRUE(NULL != ptrViEBase2); EXPECT_EQ(1, ptrViEBase->Release()) << "There should be one interface left."; EXPECT_FALSE(webrtc::VideoEngine::Delete(ptrViE)) << "Should fail since there are interfaces left."; EXPECT_EQ(0, ptrViEBase->Release()); EXPECT_TRUE(webrtc::VideoEngine::Delete(ptrViE)); } <commit_msg>nits<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vie_autotest.h" #include "base_primitives.h" #include "general_primitives.h" #include "tb_interfaces.h" #include "vie_autotest_defines.h" #include "video_capture_factory.h" class BaseObserver : public webrtc::ViEBaseObserver { public: BaseObserver() : cpu_load_(0) {} virtual void PerformanceAlarm(const unsigned int cpu_load) { cpu_load_ = cpu_load; } unsigned int cpu_load_; }; void ViEAutoTest::ViEBaseStandardTest() { // *************************************************************** // Begin create/initialize WebRTC Video Engine for testing // *************************************************************** TbInterfaces interfaces("ViEBaseStandardTest"); // *************************************************************** // Engine ready. Set up the test case: // *************************************************************** int video_channel = -1; EXPECT_EQ(0, interfaces.base->CreateChannel(video_channel)); webrtc::VideoCaptureModule* video_capture_module(NULL); const unsigned int kMaxDeviceNameLength = 128; char device_name[kMaxDeviceNameLength]; memset(device_name, 0, kMaxDeviceNameLength); int capture_id; webrtc::ViEBase *base_interface = interfaces.base; webrtc::ViERender *render_interface = interfaces.render; webrtc::ViECapture *capture_interface = interfaces.capture; FindCaptureDeviceOnSystem(capture_interface, device_name, kMaxDeviceNameLength, &capture_id, &video_capture_module); EXPECT_EQ(0, capture_interface->ConnectCaptureDevice(capture_id, video_channel)); EXPECT_EQ(0, capture_interface->StartCapture(capture_id)); ConfigureRtpRtcp(interfaces.rtp_rtcp, video_channel); EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm1)); EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm2)); RenderInWindow(render_interface, capture_id, _window1, 0); RenderInWindow(render_interface, video_channel, _window2, 1); // *************************************************************** // Run the actual test: // *************************************************************** ViETest::Log("You should shortly see a local preview from camera %s" " in window 1 and the remote video in window 2.", device_name); ::TestI420CallSetup(interfaces.codec, interfaces.video_engine, base_interface, interfaces.network, video_channel, device_name); // *************************************************************** // Testing finished. Tear down Video Engine // *************************************************************** EXPECT_EQ(0, capture_interface->StopCapture(capture_id)); EXPECT_EQ(0, base_interface->StopReceive(video_channel)); StopAndRemoveRenderers(base_interface, render_interface, video_channel, capture_id); EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm1)); EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm2)); EXPECT_EQ(0, capture_interface->ReleaseCaptureDevice(capture_id)); video_capture_module->Release(); video_capture_module = NULL; EXPECT_EQ(0, base_interface->DeleteChannel(video_channel)); } void ViEAutoTest::ViEBaseExtendedTest() { // Start with standard test ViEBaseAPITest(); ViEBaseStandardTest(); // *************************************************************** // Test BaseObserver // *************************************************************** // TODO(mflodman) Add test for base observer. Cpu load must be over 75%. // BaseObserver base_observer; // EXPECT_EQ(ptrViEBase->RegisterObserver(base_observer), 0); // // AutoTestSleep(KAutoTestSleepTimeMs); // // EXPECT_EQ(ptrViEBase->DeregisterObserver(), 0); // EXPECT_GT(base_observer.cpu_load, 0); } void ViEAutoTest::ViEBaseAPITest() { // *************************************************************** // Begin create/initialize WebRTC Video Engine for testing // *************************************************************** // Get the ViEBase API webrtc::ViEBase* ptrViEBase = webrtc::ViEBase::GetInterface(NULL); EXPECT_EQ(NULL, ptrViEBase) << "Should return null for a bad ViE pointer"; webrtc::VideoEngine* ptrViE = webrtc::VideoEngine::Create(); EXPECT_TRUE(NULL != ptrViE); std::string trace_file_path = ViETest::GetResultOutputPath() + "ViEBaseAPI_trace.txt"; EXPECT_EQ(0, ptrViE->SetTraceFile(trace_file_path.c_str())); ptrViEBase = webrtc::ViEBase::GetInterface(ptrViE); EXPECT_TRUE(NULL != ptrViEBase); // *************************************************************** // Engine ready. Begin testing class // *************************************************************** char version[1024] = ""; EXPECT_EQ(0, ptrViEBase->GetVersion(version)); EXPECT_EQ(0, ptrViEBase->LastError()); // Create without init int videoChannel = -1; EXPECT_NE(0, ptrViEBase->CreateChannel(videoChannel)) << "Should fail since Init has not been called yet"; EXPECT_EQ(0, ptrViEBase->Init()); EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel)); int videoChannel2 = -1; EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2)); EXPECT_NE(videoChannel, videoChannel2) << "Should allocate new number for independent channel"; EXPECT_EQ(0, ptrViEBase->DeleteChannel(videoChannel2)); EXPECT_EQ(-1, ptrViEBase->CreateChannel(videoChannel2, videoChannel + 1)) << "Should fail since neither channel exists (the second must)"; EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2, videoChannel)); // Test Voice Engine integration with Video Engine. webrtc::VoiceEngine* ptrVoE = NULL; webrtc::VoEBase* ptrVoEBase = NULL; int audioChannel = -1; ptrVoE = webrtc::VoiceEngine::Create(); EXPECT_TRUE(NULL != ptrVoE); ptrVoEBase = webrtc::VoEBase::GetInterface(ptrVoE); EXPECT_TRUE(NULL != ptrVoEBase); EXPECT_EQ(0, ptrVoEBase->Init()); audioChannel = ptrVoEBase->CreateChannel(); EXPECT_NE(-1, audioChannel); // Connect before setting VoE. EXPECT_NE(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)) << "Should fail since Voice Engine is not set yet."; // Then do it right. EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(ptrVoE)); EXPECT_EQ(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)); // *************************************************************** // Testing finished. Tear down Video Engine // *************************************************************** EXPECT_NE(0, ptrViEBase->DisconnectAudioChannel(videoChannel + 5)) << "Should fail: disconnecting bogus channel"; EXPECT_EQ(0, ptrViEBase->DisconnectAudioChannel(videoChannel)); // Clean up voice engine EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(NULL)); EXPECT_EQ(0, ptrVoEBase->Release()); EXPECT_TRUE(webrtc::VoiceEngine::Delete(ptrVoE)); webrtc::ViEBase* ptrViEBase2 = webrtc::ViEBase::GetInterface(ptrViE); EXPECT_TRUE(NULL != ptrViEBase2); EXPECT_EQ(1, ptrViEBase->Release()) << "There should be one interface left."; EXPECT_FALSE(webrtc::VideoEngine::Delete(ptrViE)) << "Should fail since there are interfaces left."; EXPECT_EQ(0, ptrViEBase->Release()); EXPECT_TRUE(webrtc::VideoEngine::Delete(ptrViE)); } <|endoftext|>
<commit_before>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <ghoul/filesystem/directory.h> #include <ghoul/filesystem/filesystem.h> #include <algorithm> #include <stack> #ifdef WIN32 #include <windows.h> #include <tchar.h> #include <direct.h> #else #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <dirent.h> #endif using std::string; using std::vector; namespace ghoul { namespace filesystem { namespace { #ifdef WIN32 const char pathSeparator = '\\'; #else const char pathSeparator = '/'; #endif } Directory::Directory() : _directoryPath(FileSys.absolutePath(".")) {} Directory::Directory(const char* path, bool isRawPath) { if (isRawPath) _directoryPath = string(path); else _directoryPath = FileSys.absolutePath(string(path)); } Directory::Directory(std::string path, bool isRawPath) { if (isRawPath) _directoryPath = path.empty() ? "." : std::move(path); else _directoryPath = std::move(FileSys.absolutePath(path.empty() ? "." : path)); } Directory::operator const std::string&() const { return _directoryPath; } const std::string& Directory::path() const { return _directoryPath; } Directory Directory::parentDirectory(bool absolutePath) const { #ifdef WIN32 if (_directoryPath.back() == pathSeparator) return Directory(_directoryPath + "..", !absolutePath); else return Directory(_directoryPath + pathSeparator + "..", !absolutePath); #else size_t length = _directoryPath.length(); size_t position = _directoryPath.find_last_of(pathSeparator); if(position == length && length > 1) position = _directoryPath.find_last_of(pathSeparator, length-1); return Directory(_directoryPath.substr(0, position)); #endif } std::vector<std::string> Directory::read(bool recursiveSearch, bool sort) const { vector<string> result; readDirectories(result, _directoryPath, recursiveSearch); readFiles(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } std::vector<std::string> Directory::readFiles(bool recursiveSearch, bool sort) const { vector<string> result; readFiles(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } void Directory::readFiles(std::vector<std::string>& result, const std::string& path, bool recursiveSearch) const { std::stack<string> directories; #ifdef WIN32 WIN32_FIND_DATA findFileData = {0}; const string& directory = path + "\\*"; HANDLE findHandle = FindFirstFile(directory.c_str(), &findFileData); if (findHandle != INVALID_HANDLE_VALUE) { do { string file(findFileData.cFileName); const DWORD isDir = findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if (!isDir) result.push_back(path + "/" + file); if (recursiveSearch && isDir && file != "." && file != "..") directories.push(path + "/" + file); } while (FindNextFile(findHandle, &findFileData) != 0); } FindClose(findHandle); #else DIR* dir = opendir(path.c_str()); struct dirent* ent; if (dir != NULL) { string name; while ((ent = readdir(dir))) { name = ent->d_name; if ((name != ".") && (name != "..")) { if (ent->d_type != DT_DIR) result.push_back(path + "/" + ent->d_name); if (recursiveSearch && (ent->d_type == DT_DIR)) directories.push(path + "/" + ent->d_name); } } } closedir(dir); #endif while (!directories.empty()) { const string& directory = directories.top(); readFiles(result, directory, recursiveSearch); directories.pop(); } } std::vector<std::string> Directory::readDirectories(bool recursiveSearch, bool sort) const { std::vector<std::string> result; readDirectories(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } void Directory::readDirectories( std::vector<std::string>& result, const std::string& path, bool recursiveSearch) const { std::stack<string> directories; #ifdef WIN32 WIN32_FIND_DATA findFileData = {0}; std::string directory = path + "\\*"; HANDLE findHandle = FindFirstFile(directory.c_str(), &findFileData); if (findHandle != INVALID_HANDLE_VALUE) { do { string file(findFileData.cFileName); const DWORD isDir = findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if (isDir && (file != ".") && (file != "..")) { result.push_back(path + "\\" + file); if (recursiveSearch) directories.push(path + "\\" + file); } } while (FindNextFile(findHandle, &findFileData) != 0); } FindClose(findHandle); #else DIR* dir = opendir(path.c_str()); struct dirent* ent; if (dir != NULL) { string name; while ((ent = readdir(dir))) { name = ent->d_name; if ((ent->d_type == DT_DIR) && (name != ".") && (name != "..")) { result.push_back(path + "/" + ent->d_name); if (recursiveSearch) directories.push(path + "/" + ent->d_name); } } } closedir(dir); #endif while (!directories.empty()) { const string& directory = directories.top(); readDirectories(result, directory, recursiveSearch); directories.pop(); } } std::ostream& operator<<(std::ostream& os, const Directory& d) { return os << d.path(); } } // filesystem } // ghoul <commit_msg>Trying to remove a compiler warning<commit_after>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <ghoul/filesystem/directory.h> #include <ghoul/filesystem/filesystem.h> #include <algorithm> #include <stack> #ifdef WIN32 #include <windows.h> #include <tchar.h> #include <direct.h> #else #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <dirent.h> #endif using std::string; using std::vector; namespace ghoul { namespace filesystem { namespace { #ifdef WIN32 const char pathSeparator = '\\'; #else const char pathSeparator = '/'; #endif } Directory::Directory() : _directoryPath(FileSys.absolutePath(".")) {} Directory::Directory(const char* path, bool isRawPath) { if (isRawPath) _directoryPath = string(path); else _directoryPath = FileSys.absolutePath(string(path)); } Directory::Directory(std::string path, bool isRawPath) { if (isRawPath) _directoryPath = path.empty() ? "." : std::move(path); else _directoryPath = std::move(FileSys.absolutePath(path.empty() ? "." : path)); } Directory::operator const std::string&() const { return _directoryPath; } const std::string& Directory::path() const { return _directoryPath; } Directory Directory::parentDirectory(bool absolutePath) const { #ifdef WIN32 if (_directoryPath.back() == pathSeparator) return Directory(_directoryPath + "..", !absolutePath); else return Directory(_directoryPath + pathSeparator + "..", !absolutePath); #else #pragma unused (absolutePath) size_t length = _directoryPath.length(); size_t position = _directoryPath.find_last_of(pathSeparator); if(position == length && length > 1) position = _directoryPath.find_last_of(pathSeparator, length-1); return Directory(_directoryPath.substr(0, position)); #endif } std::vector<std::string> Directory::read(bool recursiveSearch, bool sort) const { vector<string> result; readDirectories(result, _directoryPath, recursiveSearch); readFiles(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } std::vector<std::string> Directory::readFiles(bool recursiveSearch, bool sort) const { vector<string> result; readFiles(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } void Directory::readFiles(std::vector<std::string>& result, const std::string& path, bool recursiveSearch) const { std::stack<string> directories; #ifdef WIN32 WIN32_FIND_DATA findFileData = {0}; const string& directory = path + "\\*"; HANDLE findHandle = FindFirstFile(directory.c_str(), &findFileData); if (findHandle != INVALID_HANDLE_VALUE) { do { string file(findFileData.cFileName); const DWORD isDir = findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if (!isDir) result.push_back(path + "/" + file); if (recursiveSearch && isDir && file != "." && file != "..") directories.push(path + "/" + file); } while (FindNextFile(findHandle, &findFileData) != 0); } FindClose(findHandle); #else DIR* dir = opendir(path.c_str()); struct dirent* ent; if (dir != NULL) { string name; while ((ent = readdir(dir))) { name = ent->d_name; if ((name != ".") && (name != "..")) { if (ent->d_type != DT_DIR) result.push_back(path + "/" + ent->d_name); if (recursiveSearch && (ent->d_type == DT_DIR)) directories.push(path + "/" + ent->d_name); } } } closedir(dir); #endif while (!directories.empty()) { const string& directory = directories.top(); readFiles(result, directory, recursiveSearch); directories.pop(); } } std::vector<std::string> Directory::readDirectories(bool recursiveSearch, bool sort) const { std::vector<std::string> result; readDirectories(result, _directoryPath, recursiveSearch); if (sort) std::sort(result.begin(), result.end()); return result; } void Directory::readDirectories( std::vector<std::string>& result, const std::string& path, bool recursiveSearch) const { std::stack<string> directories; #ifdef WIN32 WIN32_FIND_DATA findFileData = {0}; std::string directory = path + "\\*"; HANDLE findHandle = FindFirstFile(directory.c_str(), &findFileData); if (findHandle != INVALID_HANDLE_VALUE) { do { string file(findFileData.cFileName); const DWORD isDir = findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if (isDir && (file != ".") && (file != "..")) { result.push_back(path + "\\" + file); if (recursiveSearch) directories.push(path + "\\" + file); } } while (FindNextFile(findHandle, &findFileData) != 0); } FindClose(findHandle); #else DIR* dir = opendir(path.c_str()); struct dirent* ent; if (dir != NULL) { string name; while ((ent = readdir(dir))) { name = ent->d_name; if ((ent->d_type == DT_DIR) && (name != ".") && (name != "..")) { result.push_back(path + "/" + ent->d_name); if (recursiveSearch) directories.push(path + "/" + ent->d_name); } } } closedir(dir); #endif while (!directories.empty()) { const string& directory = directories.top(); readDirectories(result, directory, recursiveSearch); directories.pop(); } } std::ostream& operator<<(std::ostream& os, const Directory& d) { return os << d.path(); } } // filesystem } // ghoul <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/browser/remoting/remoting_options_handler.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/service/service_process_control_manager.h" #include "chrome/common/remoting/chromoting_host_info.h" #include "content/browser/webui/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace remoting { RemotingOptionsHandler::RemotingOptionsHandler() : web_ui_(NULL), process_control_(NULL) { } RemotingOptionsHandler::~RemotingOptionsHandler() { if (process_control_) process_control_->RemoveMessageHandler(this); } void RemotingOptionsHandler::Init(WebUI* web_ui) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); web_ui_ = web_ui; process_control_ = ServiceProcessControlManager::GetInstance()->GetProcessControl( web_ui_->GetProfile()); process_control_->AddMessageHandler(this); if (!process_control_->RequestRemotingHostStatus()) { // Assume that host is not started if we can't request status. SetStatus(false, ""); } } // ServiceProcessControl::MessageHandler interface void RemotingOptionsHandler::OnRemotingHostInfo( const remoting::ChromotingHostInfo& host_info) { SetStatus(host_info.enabled, host_info.login); } void RemotingOptionsHandler::SetStatus( bool enabled, const std::string& login) { string16 status; if (enabled) { status = l10n_util::GetStringFUTF16(IDS_REMOTING_STATUS_ENABLED_TEXT, UTF8ToUTF16(login)); } else { status = l10n_util::GetStringUTF16(IDS_REMOTING_STATUS_DISABLED_TEXT); } FundamentalValue enabled_value(enabled); StringValue status_value(status); web_ui_->CallJavascriptFunction(L"options.AdvancedOptions.SetRemotingStatus", enabled_value, status_value); } } // namespace remoting <commit_msg>Fix build failure in remoting option handler<commit_after>// Copyright (c) 2011 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 "chrome/browser/remoting/remoting_options_handler.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/service/service_process_control_manager.h" #include "chrome/common/remoting/chromoting_host_info.h" #include "content/browser/webui/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace remoting { RemotingOptionsHandler::RemotingOptionsHandler() : web_ui_(NULL), process_control_(NULL) { } RemotingOptionsHandler::~RemotingOptionsHandler() { if (process_control_) process_control_->RemoveMessageHandler(this); } void RemotingOptionsHandler::Init(WebUI* web_ui) { web_ui_ = web_ui; process_control_ = ServiceProcessControlManager::GetInstance()->GetProcessControl( web_ui_->GetProfile()); process_control_->AddMessageHandler(this); if (!process_control_->RequestRemotingHostStatus()) { // Assume that host is not started if we can't request status. SetStatus(false, ""); } } // ServiceProcessControl::MessageHandler interface void RemotingOptionsHandler::OnRemotingHostInfo( const remoting::ChromotingHostInfo& host_info) { SetStatus(host_info.enabled, host_info.login); } void RemotingOptionsHandler::SetStatus( bool enabled, const std::string& login) { string16 status; if (enabled) { status = l10n_util::GetStringFUTF16(IDS_REMOTING_STATUS_ENABLED_TEXT, UTF8ToUTF16(login)); } else { status = l10n_util::GetStringUTF16(IDS_REMOTING_STATUS_DISABLED_TEXT); } FundamentalValue enabled_value(enabled); StringValue status_value(status); web_ui_->CallJavascriptFunction(L"options.AdvancedOptions.SetRemotingStatus", enabled_value, status_value); } } // namespace remoting <|endoftext|>
<commit_before>// FRAGMENT(includes) #include <iostream> #include <seqan/align.h> #include <seqan/index.h> #include <seqan/misc/misc_random.h> using namespace seqan; // FRAGMENT(matrix_init) template <typename TStringSet, typename TIndexSpec> void qgramCounting(TStringSet &set, TIndexSpec) { typedef Index<TStringSet, TIndexSpec> TIndex; typedef typename Fibre<TIndex, QGram_Counts>::Type TCounts; typedef typename Fibre<TIndex, QGram_CountsDir>::Type TCountsDir; typedef typename Value<TCountsDir>::Type TDirValue; typedef typename Iterator<TCounts, Standard>::Type TIterCounts; typedef typename Iterator<TCountsDir, Standard>::Type TIterCountsDir; TIndex index(set); indexRequire(index, QGram_Counts()); // initialize distance matrix int seqNum = countSequences(index); Matrix<int, 2> distMat; setLength(distMat, 0, seqNum); setLength(distMat, 1, seqNum); fill(distMat, 0); std::cout << std::endl << "Length of the CountsDir fibre: " << length(indexCountsDir(index)) << std::endl; TIterCountsDir itCountsDir = begin(indexCountsDir(index), Standard()); TIterCountsDir itCountsDirEnd = end(indexCountsDir(index), Standard()); TIterCounts itCountsBegin = begin(indexCounts(index), Standard()); // FRAGMENT(matrix_calculation) // for each bucket count common q-grams for each sequence pair TDirValue bucketBegin = *itCountsDir; for(++itCountsDir; itCountsDir != itCountsDirEnd; ++itCountsDir) { TDirValue bucketEnd = *itCountsDir; // q-gram must occur in at least 2 different sequences if (bucketBegin != bucketEnd) { TIterCounts itA = itCountsBegin + bucketBegin; TIterCounts itEnd = itCountsBegin + bucketEnd; for(; itA != itEnd; ++itA) for(TIterCounts itB = itA; itB != itEnd; ++itB) distMat((*itA).i1, (*itB).i1) += _min((*itA).i2, (*itB).i2); } bucketBegin = bucketEnd; } std::cout << std::endl << "Common 5-mers for Seq_i, Seq_j" << std::endl; std::cout << distMat; } // FRAGMENT(initialization) int main () { // for the sake of reproducibility mtRandInit(false); // create StringSet of 3 random sequences StringSet<DnaString> stringSet; reserve(stringSet, 3); for (int seqNo = 0; seqNo < 3; ++seqNo) { DnaString tmp; int len = mtRand() % 100 + 10; for (int i = 0; i < len; ++i) appendValue(tmp, Dna(mtRand() % 4)); appendValue(stringSet, tmp); std::cout << ">Seq" << seqNo << std::endl << tmp << std::endl; } qgramCounting(stringSet, Index_QGram<UngappedShape<5> >()); qgramCounting(stringSet, Index_QGram<UngappedShape<5>, OpenAddressing>()); return 0; } <commit_msg>switched to the new RNG<commit_after>// FRAGMENT(includes) #include <iostream> #include <seqan/align.h> #include <seqan/index.h> #include <seqan/random.h> using namespace seqan; // FRAGMENT(matrix_init) template <typename TStringSet, typename TIndexSpec> void qgramCounting(TStringSet &set, TIndexSpec) { typedef Index<TStringSet, TIndexSpec> TIndex; typedef typename Fibre<TIndex, QGram_Counts>::Type TCounts; typedef typename Fibre<TIndex, QGram_CountsDir>::Type TCountsDir; typedef typename Value<TCountsDir>::Type TDirValue; typedef typename Iterator<TCounts, Standard>::Type TIterCounts; typedef typename Iterator<TCountsDir, Standard>::Type TIterCountsDir; TIndex index(set); indexRequire(index, QGram_Counts()); // initialize distance matrix int seqNum = countSequences(index); Matrix<int, 2> distMat; setLength(distMat, 0, seqNum); setLength(distMat, 1, seqNum); fill(distMat, 0); std::cout << std::endl << "Length of the CountsDir fibre: " << length(indexCountsDir(index)) << std::endl; TIterCountsDir itCountsDir = begin(indexCountsDir(index), Standard()); TIterCountsDir itCountsDirEnd = end(indexCountsDir(index), Standard()); TIterCounts itCountsBegin = begin(indexCounts(index), Standard()); // FRAGMENT(matrix_calculation) // for each bucket count common q-grams for each sequence pair TDirValue bucketBegin = *itCountsDir; for(++itCountsDir; itCountsDir != itCountsDirEnd; ++itCountsDir) { TDirValue bucketEnd = *itCountsDir; // q-gram must occur in at least 2 different sequences if (bucketBegin != bucketEnd) { TIterCounts itA = itCountsBegin + bucketBegin; TIterCounts itEnd = itCountsBegin + bucketEnd; for(; itA != itEnd; ++itA) for(TIterCounts itB = itA; itB != itEnd; ++itB) distMat((*itA).i1, (*itB).i1) += _min((*itA).i2, (*itB).i2); } bucketBegin = bucketEnd; } std::cout << std::endl << "Common 5-mers for Seq_i, Seq_j" << std::endl; std::cout << distMat; } // FRAGMENT(initialization) int main () { // for the sake of reproducibility RNG<MersenneTwister> rng; // create StringSet of 3 random sequences StringSet<DnaString> stringSet; reserve(stringSet, 3); for (int seqNo = 0; seqNo < 3; ++seqNo) { DnaString tmp; int len = pickRandomNumber(rng) % 100 + 10; for (int i = 0; i < len; ++i) appendValue(tmp, Dna(pickRandomNumber(rng) % 4)); appendValue(stringSet, tmp); std::cout << ">Seq" << seqNo << std::endl << tmp << std::endl; } qgramCounting(stringSet, Index_QGram<UngappedShape<5> >()); qgramCounting(stringSet, Index_QGram<UngappedShape<5>, OpenAddressing>()); return 0; } <|endoftext|>
<commit_before>#ifndef b_array_View_hxx_ #define b_array_View_hxx_ #include "b/b_assert.hxx" #include "b/Unsigned.hxx" namespace b { namespace array { template <typename Element> struct View { //--------------------------------------------------------------------------------------------// // Constructors constexpr View(Element* data, Unsigned length) : __0(data) , __n(data + length) { } template <Unsigned length> constexpr explicit View(Element(& data)[length]) : View(data, length) { } //--------------------------------------------------------------------------------------------// // Sized constexpr Unsigned length() const { return (reinterpret_cast<Unsigned>(this->__n) - reinterpret_cast<Unsigned>(this->__0)); } //--------------------------------------------------------------------------------------------// // Iterable constexpr Element* begin() const { return this->__0; } constexpr Element* end() const { return this->__n; } //--------------------------------------------------------------------------------------------// // Container constexpr Element& operator [](Unsigned offset) const { b_assert(offset < this->length(), "out of bounds"); return this->__0[offset]; } private: Element* __0; Element* __n; }; } // namespace array } // namespace b #endif <commit_msg>array::View.contains<commit_after>#ifndef b_array_View_hxx_ #define b_array_View_hxx_ #include "b/b_assert.hxx" #include "b/Unsigned.hxx" namespace b { namespace array { template <typename Element> struct View { //--------------------------------------------------------------------------------------------// // Constructors constexpr View(Element* data, Unsigned length) : __0(data) , __n(data + length) { } template <Unsigned length> constexpr explicit View(Element(& data)[length]) : View(data, length) { } //--------------------------------------------------------------------------------------------// // Sized constexpr Unsigned length() const { return (reinterpret_cast<Unsigned>(this->__n) - reinterpret_cast<Unsigned>(this->__0)); } //--------------------------------------------------------------------------------------------// // Iterable constexpr Element* begin() const { return this->__0; } constexpr Element* end() const { return this->__n; } //--------------------------------------------------------------------------------------------// // Container constexpr bool contains(const Element& element) const noexcept { for (auto curr : *this) if (curr == element) return true; return false; } constexpr Element& operator [](Unsigned offset) const { b_assert(offset < this->length(), "out of bounds"); return this->__0[offset]; } private: Element* __0; Element* __n; }; } // namespace array } // namespace b #endif <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef THROTTLING_SEMAPHORE_HPP_ #define THROTTLING_SEMAPHORE_HPP_ #include "containers/scoped.hpp" #include "concurrency/semaphore.hpp" #include "concurrency/signal.hpp" #include "concurrency/wait_any.hpp" #include "containers/intrusive_list.hpp" #include "arch/timing.hpp" /* TODO (daniel): Document * It attempts to meet the following design goals: * - No lock is ever granted if the given capacity is currently violated (except when using lock_force). * If necessary, lock requests are delayed indefinitely. Note that the capacity requirements * of the issued lock itself are not considered in this guarantee (so no request is * hold back indefinitely if its own count is higher than the capacity). * - throttling_semaphore_t does adapt to changing conditions. If locks are released * earlier or later than expected, the delay times of queued lock requests are re-evaluated * automatically. * - The configuration of delay times is robust, i.e. throttling_semaphore_t works reasonably well * for a wide range of `delay_at_half` values. */ class throttling_semaphore_t : public repeating_timer_callback_t { struct lock_request_t : public intrusive_list_node_t<lock_request_t> { semaphore_available_callback_t *cb; int count; int64_t target_delay; int64_t total_time_waited; int64_t time_since_recalc; int64_t recalc_delay; void on_available() { cb->on_semaphore_available(); delete this; } void progress(int64_t time_passed) { total_time_waited += time_passed; time_since_recalc += time_passed; } }; int capacity, current; double throttling_threshold; // No throttling if current < capacity * throttling_threshold. int64_t delay_granularity; int64_t delay_at_half; intrusive_list_t<lock_request_t> waiters; scoped_ptr_t<repeating_timer_t> timer; bool maintain_ordering; public: /* throttling_semaphore_t starts throttling transactions when current >= cap * thre. * The granularity in which delays are processed is gran (smaller = higher resolution, more overhead). * If current is halfway in between (cap - (cap * thre)) and cap, the delay will be d_half. */ explicit throttling_semaphore_t(int cap, double thre = 0.5, int64_t gran = 25, int64_t d_half = 100) : capacity(cap), current(0), throttling_threshold(thre), delay_granularity(gran), delay_at_half(d_half), maintain_ordering(true) { rassert(throttling_threshold >= 0.0 && throttling_threshold <= 1.0); rassert(delay_granularity > 0); rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT); } void lock(semaphore_available_callback_t *cb, int count = 1); void co_lock(int count = 1); void co_lock_interruptible(signal_t *interruptor, int count = 1); void unlock(int count = 1); void force_lock(int count = 1); // This does not trigger any request to be re-scheduled immediately. // Instead the new capacity will become effective as part of the regular // re-calculation schedule. void set_capacity(int new_capacity) { capacity = new_capacity; } int get_capacity() const { return capacity; } virtual void on_ring(); // Called periodically by timer private: void on_waiters_changed(); // Should be called after a change to waiters int64_t compute_target_delay() const; // The "heart" of throttling_semaphore_t. }; class throttling_semaphore_acq_t { public: throttling_semaphore_acq_t(throttling_semaphore_t *_acquiree, int c = 1) : acquiree(_acquiree), count(c) { acquiree->co_lock(count); } throttling_semaphore_acq_t(throttling_semaphore_acq_t &&movee) : acquiree(movee.acquiree) { movee.acquiree = NULL; } ~throttling_semaphore_acq_t() { if (acquiree) { acquiree->unlock(count); } } private: throttling_semaphore_t *acquiree; int count; DISABLE_COPYING(throttling_semaphore_acq_t); }; #endif /* THROTTLING_SEMAPHORE_HPP_ */ <commit_msg>Allow using throttling_semaphore_acq_t for force_lock.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef THROTTLING_SEMAPHORE_HPP_ #define THROTTLING_SEMAPHORE_HPP_ #include "containers/scoped.hpp" #include "concurrency/semaphore.hpp" #include "concurrency/signal.hpp" #include "concurrency/wait_any.hpp" #include "containers/intrusive_list.hpp" #include "arch/timing.hpp" /* TODO (daniel): Document * It attempts to meet the following design goals: * - No lock is ever granted if the given capacity is currently violated (except when using lock_force). * If necessary, lock requests are delayed indefinitely. Note that the capacity requirements * of the issued lock itself are not considered in this guarantee (so no request is * hold back indefinitely if its own count is higher than the capacity). * - throttling_semaphore_t does adapt to changing conditions. If locks are released * earlier or later than expected, the delay times of queued lock requests are re-evaluated * automatically. * - The configuration of delay times is robust, i.e. throttling_semaphore_t works reasonably well * for a wide range of `delay_at_half` values. */ class throttling_semaphore_t : public repeating_timer_callback_t { struct lock_request_t : public intrusive_list_node_t<lock_request_t> { semaphore_available_callback_t *cb; int count; int64_t target_delay; int64_t total_time_waited; int64_t time_since_recalc; int64_t recalc_delay; void on_available() { cb->on_semaphore_available(); delete this; } void progress(int64_t time_passed) { total_time_waited += time_passed; time_since_recalc += time_passed; } }; int capacity, current; double throttling_threshold; // No throttling if current < capacity * throttling_threshold. int64_t delay_granularity; int64_t delay_at_half; intrusive_list_t<lock_request_t> waiters; scoped_ptr_t<repeating_timer_t> timer; bool maintain_ordering; public: /* throttling_semaphore_t starts throttling transactions when current >= cap * thre. * The granularity in which delays are processed is gran (smaller = higher resolution, more overhead). * If current is halfway in between (cap - (cap * thre)) and cap, the delay will be d_half. */ explicit throttling_semaphore_t(int cap, double thre = 0.5, int64_t gran = 25, int64_t d_half = 100) : capacity(cap), current(0), throttling_threshold(thre), delay_granularity(gran), delay_at_half(d_half), maintain_ordering(true) { rassert(throttling_threshold >= 0.0 && throttling_threshold <= 1.0); rassert(delay_granularity > 0); rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT); } void lock(semaphore_available_callback_t *cb, int count = 1); void co_lock(int count = 1); void co_lock_interruptible(signal_t *interruptor, int count = 1); void unlock(int count = 1); void force_lock(int count = 1); // This does not trigger any request to be re-scheduled immediately. // Instead the new capacity will become effective as part of the regular // re-calculation schedule. void set_capacity(int new_capacity) { capacity = new_capacity; } int get_capacity() const { return capacity; } virtual void on_ring(); // Called periodically by timer private: void on_waiters_changed(); // Should be called after a change to waiters int64_t compute_target_delay() const; // The "heart" of throttling_semaphore_t. }; class throttling_semaphore_acq_t { public: throttling_semaphore_acq_t(throttling_semaphore_t *_acquiree, int c = 1, bool use_the_force = false) : acquiree(_acquiree), count(c) { if (use_the_force) acquiree->force_lock(count); else acquiree->co_lock(count); } throttling_semaphore_acq_t(throttling_semaphore_acq_t &&movee) : acquiree(movee.acquiree) { movee.acquiree = NULL; } ~throttling_semaphore_acq_t() { if (acquiree) { acquiree->unlock(count); } } private: throttling_semaphore_t *acquiree; int count; DISABLE_COPYING(throttling_semaphore_acq_t); }; #endif /* THROTTLING_SEMAPHORE_HPP_ */ <|endoftext|>
<commit_before>#include <sstream> #include <vector> #include <limits> #include "person.hpp" #include "PersonsFile.hpp" using Buckets = std::vector<std::vector<person>>; using Persons = std::vector<person>; using Output_Files = std::vector<std::ofstream>; class Database_Sorter { bool is_database_empty; std::string database_file_name; std::string vault_name; public: Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount, std::string _vault_name = "F:\\1\\temp_files\\") : database_file_name(database_file_name), database_file(database_file_name), output_file(output_file_name), RAM_amount(_RAM_amount * 1024 * 1024), is_database_empty(true), vault_name(_vault_name) { ; } void sortDatabase() { database_file.seekg(0, std::ios::end); size_t database_size = static_cast<size_t>(database_file.tellg()); database_file.seekg(0, std::ios::beg); sortFile(database_file_name, database_size, 0); } void closeDatabase() { database_file.close(); output_file.close(); } private: void outputFile(std::string const & file_name) { if (is_database_empty) { is_database_empty = false; } else { output_file << std::endl; } std::ifstream file(file_name); char ch; while (file.get(ch)) { output_file.put(ch); } file.close(); } void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) { if (file_size < RAM_amount) { RAMsort(file_name, sort_i); } else { std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i); for (size_t i = 0; i < persons_files.size(); i++) { if (!persons_files[i].is_empty) { if (persons_files[i].is_same) { outputFile(persons_files[i].file_name); } else { sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1); } } } } } void RAMsort(std::string const & file_name, size_t sort_i) { persons.clear(); readFileIntoRAM(file_name); sortPersons(persons, sort_i); } void readFileIntoRAM(std::string const & file_name) { /*std::string str; std::ifstream file(file_name, std::ios::in | std::ios::ate); if (file) { std::ifstream::streampos filesize = file.tellg(); str.reserve(filesize); file.seekg(0); while (!file.eof()) { str += file.get(); } }*/ std::ifstream is(file_name, std::ifstream::binary); if (is) { // get length of file: is.seekg(0, is.end); size_t length = is.tellg(); is.seekg(0, is.beg); char * buffer = new char[length]; // read data as a block: is.read(buffer, length); is.close(); size_t previous_i = 0; size_t i = 0; bool state = false; person current_person; while (i < length) { if (buffer[i] == ' ') { if (!state) { current_person.name_i = i - previous_i + 1; state = true; } else { current_person.name_length = i - previous_i - current_person.name_i; state = false; } } else if (buffer[i] == '\r') { current_person.str = new char[i - previous_i + 1]; strncpy(current_person.str, &(buffer[previous_i]), i - previous_i); current_person.str[i - previous_i] = '\0'; persons.push_back(current_person); previous_i = i + 2; i++; } i++; } persons.shrink_to_fit(); delete[] buffer; } /*std::ifstream file(file_name); std::stringstream s; person current_person; while (!file.eof()) { file >> current_person; current_person.name.shrink_to_fit(); current_person.surname.shrink_to_fit(); persons.push_back(current_person); }*/ } void sortPersons(Persons & entered_persons, size_t sort_i) { size_t full_bucket_i; Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i); if (full_bucket_i != std::numeric_limits<size_t>::max()) { outputBucket(buckets[full_bucket_i], output_file); } else { for (auto bucket : buckets) { if (!bucket.empty()) { sortPersons(bucket, sort_i + 1); } } } } Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) { bool is_same = true; char * key = new char[persons[0].name_length + 1]; strncpy(key, persons[0].getName(), persons[0].name_length); key[persons[0].name_length] = '\0'; full_bucket_i = persons[0].i(sort_i); size_t persons_size = persons.size(); Buckets buckets(n_literals); for (auto person : persons) { size_t currentI = person.i(sort_i); full_bucket_i = currentI; buckets[currentI].push_back(std::move(person)); if (is_same) { if (strcmp(key, person.getName()) != 0) { is_same = false; } } } persons.clear(); persons.shrink_to_fit(); if (!is_same) { full_bucket_i = std::numeric_limits<size_t>::max(); } delete[] key; return buckets; } void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) { for (auto person : bucket) { outputPerson(person); } } void outputPerson(person _person) { if (is_database_empty) { is_database_empty = false; } else { output_file << std::endl; } output_file << _person.str; } std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */ std::string base_file_name, size_t sort_i) { std::ifstream base_file(base_file_name); bool is_same = true; std::vector<Persons_File> files(n_literals); person current_person; size_t currentTargetFileI; std::string str1, str2, str3; while (!base_file.eof()) { base_file >> str1; current_person.name_i = str1.length() + 1; base_file >> str2; current_person.name_length = str2.length(); base_file >> str3; str1 += " " + str2 + " " + str3; current_person.str = new char[str1.length() + 1]; strncpy(current_person.str, str1.c_str(), str1.length()); current_person.str[str1.length()] = '\0'; currentTargetFileI = current_person.i(sort_i); if (files[currentTargetFileI].is_empty) { files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI)); files[currentTargetFileI].is_empty = false; files[currentTargetFileI].key = new char[current_person.name_length + 1]; strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length); files[currentTargetFileI].key[current_person.name_length] = '\0'; files[currentTargetFileI].is_same = true; } else { if (files[currentTargetFileI].is_same) { //char * temp = current_person.getName(); if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) { files[currentTargetFileI].is_same = false; } } files[currentTargetFileI].stream << std::endl; } files[currentTargetFileI].stream << current_person; } for (size_t i = 0; i < files.size(); i++) { if (!files[i].is_empty) { files[i].file_size = static_cast<size_t>(files[i].stream.tellg()); } files[i].stream.close(); } base_file.close(); return files; } std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) { std::vector<Persons_File> files(n_literals); for (size_t i = 0; i < files.size(); i++) { std::string str; if (base_file_name == database_file_name) { str = vault_name + static_cast<char>(i + 64) + ".txt"; } else { str = base_file_name + static_cast<char>(i + 64) + ".txt"; } files[i].openNew(str); } return files; } std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) { std::string derived_file_name; if (base_file_name == database_file_name) { derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt"; } else { derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt"; } return derived_file_name; } std::vector<person> persons; std::ifstream database_file; std::ofstream output_file; const size_t RAM_amount; }; //memory: max 27 files, <commit_msg>Update Database_Sorter.hpp<commit_after>#include <sstream> #include <vector> #include <limits> #include "person.hpp" #include "PersonsFile.hpp" using Buckets = std::vector<std::vector<person>>; using Persons = std::vector<person>; using Output_Files = std::vector<std::ofstream>; class Database_Sorter { bool is_database_empty; std::string database_file_name; std::string vault_name; public: Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount, std::string _vault_name = "F:\\1\\temp_files\\") : database_file_name(database_file_name), //database_file(database_file_name), output_file(output_file_name), RAM_amount(_RAM_amount * 1024 * 1024), is_database_empty(true), vault_name(_vault_name) { ; } void sortDatabase() { std::fstream database_file(database_file_name); database_file.seekg(0, std::ios::end); size_t database_size = static_cast<size_t>(database_file.tellg()); database_file.seekg(0, std::ios::beg); sortFile(database_file_name, database_size, 0); } void closeDatabase() { database_file.close(); output_file.close(); } private: void outputFile(std::string const & file_name) { if (is_database_empty) { is_database_empty = false; } else { output_file << std::endl; } std::ifstream file(file_name); char ch; while (file.get(ch)) { output_file.put(ch); } file.close(); } void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) { if (file_size < RAM_amount) { RAMsort(file_name, sort_i); } else { std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i); for (size_t i = 0; i < persons_files.size(); i++) { if (!persons_files[i].is_empty) { if (persons_files[i].is_same) { outputFile(persons_files[i].file_name); } else { sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1); } } } } } void RAMsort(std::string const & file_name, size_t sort_i) { persons.clear(); readFileIntoRAM(file_name); sortPersons(persons, sort_i); } void readFileIntoRAM(std::string const & file_name) { std::ifstream is(file_name, std::ifstream::binary); if (is) { // get length of file: is.seekg(0, is.end); size_t length = is.tellg(); is.seekg(0, is.beg); char * buffer = new char[length]; // read data as a block: is.read(buffer, length); is.close(); size_t previous_i = 0; size_t i = 0; bool state = false; person current_person; while (i < length) { if (buffer[i] == ' ') { if (!state) { current_person.name_i = i - previous_i + 1; state = true; } else { current_person.name_length = i - previous_i - current_person.name_i; state = false; } } else if (buffer[i] == '\r') { current_person.str = new char[i - previous_i + 1]; strncpy(current_person.str, &(buffer[previous_i]), i - previous_i); current_person.str[i - previous_i] = '\0'; persons.push_back(current_person); previous_i = i + 2; i++; } i++; } persons.shrink_to_fit(); delete[] buffer; } } void sortPersons(Persons & entered_persons, size_t sort_i) { size_t full_bucket_i; Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i); if (full_bucket_i != std::numeric_limits<size_t>::max()) { outputBucket(buckets[full_bucket_i], output_file); } else { for (auto bucket : buckets) { if (!bucket.empty()) { sortPersons(bucket, sort_i + 1); } } } } Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) { bool is_same = true; char * key = new char[persons[0].name_length + 1]; strncpy(key, persons[0].getName(), persons[0].name_length); key[persons[0].name_length] = '\0'; full_bucket_i = persons[0].i(sort_i); size_t persons_size = persons.size(); Buckets buckets(n_literals); for (auto person : persons) { size_t currentI = person.i(sort_i); full_bucket_i = currentI; buckets[currentI].push_back(std::move(person)); if (is_same) { if (strcmp(key, person.getName()) != 0) { is_same = false; } } } persons.clear(); persons.shrink_to_fit(); if (!is_same) { full_bucket_i = std::numeric_limits<size_t>::max(); } delete[] key; return buckets; } void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) { for (auto person : bucket) { outputPerson(person); } } void outputPerson(person _person) { if (is_database_empty) { is_database_empty = false; } else { output_file << std::endl; } output_file << _person.str; } std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */ std::string base_file_name, size_t sort_i) { std::ifstream base_file(base_file_name); bool is_same = true; std::vector<Persons_File> files(n_literals); person current_person; size_t currentTargetFileI; std::string str1, str2, str3; while (!base_file.eof()) { base_file >> str1; current_person.name_i = str1.length() + 1; base_file >> str2; current_person.name_length = str2.length(); base_file >> str3; str1 += " " + str2 + " " + str3; current_person.str = new char[str1.length() + 1]; strncpy(current_person.str, str1.c_str(), str1.length()); current_person.str[str1.length()] = '\0'; currentTargetFileI = current_person.i(sort_i); if (files[currentTargetFileI].is_empty) { files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI)); files[currentTargetFileI].is_empty = false; files[currentTargetFileI].key = new char[current_person.name_length + 1]; strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length); files[currentTargetFileI].key[current_person.name_length] = '\0'; files[currentTargetFileI].is_same = true; } else { if (files[currentTargetFileI].is_same) { //char * temp = current_person.getName(); if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) { files[currentTargetFileI].is_same = false; } } files[currentTargetFileI].stream << std::endl; } files[currentTargetFileI].stream << current_person; } for (size_t i = 0; i < files.size(); i++) { if (!files[i].is_empty) { files[i].file_size = static_cast<size_t>(files[i].stream.tellg()); } files[i].stream.close(); } base_file.close(); return files; } std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) { std::vector<Persons_File> files(n_literals); for (size_t i = 0; i < files.size(); i++) { std::string str; if (base_file_name == database_file_name) { str = vault_name + static_cast<char>(i + 64) + ".txt"; } else { str = base_file_name + static_cast<char>(i + 64) + ".txt"; } files[i].openNew(str); } return files; } std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) { std::string derived_file_name; if (base_file_name == database_file_name) { derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt"; } else { derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt"; } return derived_file_name; } std::vector<person> persons; //std::ifstream database_file; std::ofstream output_file; const size_t RAM_amount; }; //memory: max 27 files, <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file joint_observation_model_iid.hpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #ifndef FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP #define FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP #include <Eigen/Dense> #include <memory> #include <type_traits> #include <fl/util/traits.hpp> #include <fl/util/meta.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/adaptive_model.hpp> #include <fl/model/observation/observation_model_interface.hpp> namespace fl { // Forward declarations template <typename...Models> class JointObservationModel; /** * Traits of JointObservationModel<MultipleOf<ObservationModel, Count>> */ template < typename ObsrvModel, int Count > struct Traits< JointObservationModel<MultipleOf<ObsrvModel, Count>, Adaptive<>> > { enum : signed int { ModelCount = Count }; typedef ObsrvModel LocalObsrvModel; typedef typename Traits<ObsrvModel>::Scalar Scalar; typedef typename Traits<ObsrvModel>::Obsrv LocalObsrv; typedef typename Traits<ObsrvModel>::State LocalState; typedef typename Traits<ObsrvModel>::Param LocalParam; typedef typename Traits<ObsrvModel>::Noise LocalNoise; enum : signed int { StateDim = LocalState::SizeAtCompileTime, ObsrvDim = ExpandSizes<LocalObsrv::SizeAtCompileTime, Count>::Size, NoiseDim = ExpandSizes<LocalNoise::SizeAtCompileTime, Count>::Size, ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size }; typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv; typedef Eigen::Matrix<Scalar, StateDim, 1> State; typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise; typedef Eigen::Matrix<Scalar, ParamDim, 1> Param; typedef ObservationModelInterface< Obsrv, State, Noise > ObservationModelBase; }; /** * \ingroup observation_models * * \brief JointObservationModel itself is an observati * on model which contains * internally multiple models all of the \em same type. The joint model can be * simply summarized as \f$ h(x, \theta, w) = [ h_{local}(x, \theta_1, w_1), * h_{local}(x, \theta_2, w_2), \ldots, h_{local}(x, \theta_n, w_n) ]^T \f$ * * where \f$x\f$ is the state variate, \f$\theta = [ \theta_1, \theta_2, \ldots, * \theta_n ]^T\f$ and \f$w = [ w_1, w_2, \ldots, w_n ]^T\f$ are the the * parameters and noise terms of each of the \f$n\f$ models. * * JointObservationModel implements the ObservationModelInterface and the * AdaptiveModel interface. That being said, the JointObservationModel can be * used as a regular observation model or even as an adaptive observation model * which provides a set of parameters that can be changed at any time. This * implies that all sub-models must implement the the AdaptiveModel * interface. However, if the sub-model is not adaptive, JointObservationModel * applies a decorator call the NotAdaptive operator on the sub-model. This * operator enables any model to be treated as if it is adaptive without * effecting the model behaviour. */ template < typename LocalObsrvModel, int Count > class JointObservationModel<MultipleOf<LocalObsrvModel, Count>> : public JointObservationModel< MultipleOf<typename MakeAdaptive<LocalObsrvModel>::Type, Count>, Adaptive<> > { }; template < typename LocalObsrvModel, int Count > class JointObservationModel<MultipleOf<LocalObsrvModel, Count>, Adaptive<>> : public Traits< JointObservationModel<MultipleOf<LocalObsrvModel, Count>> >::ObservationModelBase { public: typedef JointObservationModel<MultipleOf<LocalObsrvModel,Count>> This; typedef typename Traits<This>::Obsrv Obsrv; typedef typename Traits<This>::State State; typedef typename Traits<This>::Noise Noise; public: explicit JointObservationModel( const LocalObsrvModel& local_obsrv_model, int count = ToDimension<Count>::Value) : local_obsrv_model_(local_obsrv_model), count_(count) { assert(count_ > 0); } explicit JointObservationModel(const MultipleOf<LocalObsrvModel, Count>& mof) : local_obsrv_model_(mof.instance), count_(mof.count) { assert(count_ > 0); } /** * \brief Overridable default destructor */ ~JointObservationModel() { } /** * \copydoc ObservationModelInterface::predict_obsrv */ virtual Obsrv predict_obsrv(const State& state, const Noise& noise, double delta_time) { Obsrv y = Obsrv::Zero(obsrv_dimension(), 1); int obsrv_dim = local_obsrv_model_.obsrv_dimension(); int noise_dim = local_obsrv_model_.noise_dimension(); const int count = count_; for (int i = 0; i < count; ++i) { y.middleRows(i * obsrv_dim, obsrv_dim) = local_obsrv_model_.predict_obsrv( state, noise.middleRows(i * noise_dim, noise_dim), delta_time); } return y; } virtual int obsrv_dimension() const { return local_obsrv_model_.obsrv_dimension() * count_; } virtual int noise_dimension() const { return local_obsrv_model_.noise_dimension() * count_; } virtual int state_dimension() const { return local_obsrv_model_.state_dimension(); } LocalObsrvModel& local_observation_model() { return local_obsrv_model_; } protected: LocalObsrvModel local_obsrv_model_; int count_; }; ///** // * Traits of the \em Adaptive JointObservationModel // */ //template < // typename ObsrvModel, // int Count //> //struct Traits< // JointObservationModel<MultipleOf<Adaptive<ObsrvModel>, Count>> // > // : Traits<JointObservationModel<MultipleOf<ObsrvModel, Count>>> //{ // typedef Traits<JointObservationModel<MultipleOf<ObsrvModel, Count>>> Base; // typedef typename Traits<ObsrvModel>::Param LocalParam; // enum : signed int // { // ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size // }; // typedef Eigen::Matrix<typename Base::Scalar, ParamDim, 1> Param; // typedef ObservationModelInterface< // typename Base::Obsrv, // typename Base::State, // typename Base::Noise // > ObservationModelBase; // typedef AdaptiveModel<Param> AdaptiveModelBase; //}; ///** // * \ingroup observation_models // * // * JointObservationModel for adaptive local observation models // */ //template < // typename LocalObsrvModel, // int Count> //class JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>> // : public Traits< // JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>> // >::ObservationModelBase, // public Traits< // JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>> // >::AdaptiveModelBase //{ //public: // typedef JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>> This; // typedef typename Traits<This>::Param Param; //public: // virtual Param param() const { return param_; } // virtual void param(Param new_param) { param_ = new_param; } // virtual int param_dimension() const { return param_.rows(); } //protected: // Param param_; //}; } #endif <commit_msg>Added ForwardAdaptive<LocalModel> to decorate non-aadptive models<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file joint_observation_model_iid.hpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #ifndef FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP #define FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP #include <Eigen/Dense> #include <memory> #include <type_traits> #include <fl/util/traits.hpp> #include <fl/util/meta.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/adaptive_model.hpp> #include <fl/model/observation/observation_model_interface.hpp> namespace fl { // Forward declarations template <typename...Models> class JointObservationModel; /** * Traits of JointObservationModel<MultipleOf<ObservationModel, Count>> */ template < typename ObsrvModel, int Count > struct Traits< JointObservationModel<MultipleOf<ObsrvModel, Count>, Adaptive<>> > { enum : signed int { ModelCount = Count }; typedef ObsrvModel LocalObsrvModel; typedef typename Traits<ObsrvModel>::Scalar Scalar; typedef typename Traits<ObsrvModel>::Obsrv LocalObsrv; typedef typename Traits<ObsrvModel>::State LocalState; typedef typename Traits<ObsrvModel>::Param LocalParam; typedef typename Traits<ObsrvModel>::Noise LocalNoise; enum : signed int { StateDim = LocalState::SizeAtCompileTime, ObsrvDim = ExpandSizes<LocalObsrv::SizeAtCompileTime, Count>::Size, NoiseDim = ExpandSizes<LocalNoise::SizeAtCompileTime, Count>::Size, ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size }; typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv; typedef Eigen::Matrix<Scalar, StateDim, 1> State; typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise; typedef Eigen::Matrix<Scalar, ParamDim, 1> Param; typedef ObservationModelInterface< Obsrv, State, Noise > ObservationModelBase; }; /** * \ingroup observation_models * * \brief JointObservationModel itself is an observation model which contains * internally multiple models all of the \em same type. The joint model can be * simply summarized as \f$ h(x, \theta, w) = [ h_{local}(x, \theta_1, w_1), * h_{local}(x, \theta_2, w_2), \ldots, h_{local}(x, \theta_n, w_n) ]^T \f$ * * where \f$x\f$ is the state variate, \f$\theta = [ \theta_1, \theta_2, \ldots, * \theta_n ]^T\f$ and \f$w = [ w_1, w_2, \ldots, w_n ]^T\f$ are the the * parameters and noise terms of each of the \f$n\f$ models. * * JointObservationModel implements the ObservationModelInterface and the * AdaptiveModel interface. That being said, the JointObservationModel can be * used as a regular observation model or even as an adaptive observation model * which provides a set of parameters that can be changed at any time. This * implies that all sub-models must implement the the AdaptiveModel * interface. However, if the sub-model is not adaptive, JointObservationModel * applies a decorator call the NotAdaptive operator on the sub-model. This * operator enables any model to be treated as if it is adaptive without * effecting the model behaviour. */ template < typename LocalObsrvModel, int Count > #ifdef GENERATING_DOCUMENTATION class JointObservationModel<MultipleOf<LocalObsrvModel, Count>> #else class JointObservationModel<MultipleOf<LocalObsrvModel, Count>, Adaptive<>> #endif : public Traits< JointObservationModel<MultipleOf<LocalObsrvModel, Count>> >::ObservationModelBase { public: typedef JointObservationModel<MultipleOf<LocalObsrvModel,Count>> This; typedef typename Traits<This>::Obsrv Obsrv; typedef typename Traits<This>::State State; typedef typename Traits<This>::Noise Noise; public: explicit JointObservationModel( const LocalObsrvModel& local_obsrv_model, int count = ToDimension<Count>::Value) : local_obsrv_model_(local_obsrv_model), count_(count) { assert(count_ > 0); } explicit JointObservationModel(const MultipleOf<LocalObsrvModel, Count>& mof) : local_obsrv_model_(mof.instance), count_(mof.count) { assert(count_ > 0); } /** * \brief Overridable default destructor */ ~JointObservationModel() { } /** * \copydoc ObservationModelInterface::predict_obsrv */ virtual Obsrv predict_obsrv(const State& state, const Noise& noise, double delta_time) { Obsrv y = Obsrv::Zero(obsrv_dimension(), 1); int obsrv_dim = local_obsrv_model_.obsrv_dimension(); int noise_dim = local_obsrv_model_.noise_dimension(); const int count = count_; for (int i = 0; i < count; ++i) { y.middleRows(i * obsrv_dim, obsrv_dim) = local_obsrv_model_.predict_obsrv( state, noise.middleRows(i * noise_dim, noise_dim), delta_time); } return y; } virtual int obsrv_dimension() const { return local_obsrv_model_.obsrv_dimension() * count_; } virtual int noise_dimension() const { return local_obsrv_model_.noise_dimension() * count_; } virtual int state_dimension() const { return local_obsrv_model_.state_dimension(); } LocalObsrvModel& local_observation_model() { return local_obsrv_model_; } protected: LocalObsrvModel local_obsrv_model_; int count_; }; /** * \internal * \ingroup observation_models * * Forwards an adaptive LocalObsrvModel type to the JointObservationModel * implementation. \sa ForwardAdaptive for more details. */ template < typename LocalObsrvModel, int Count > class JointObservationModel<MultipleOf<LocalObsrvModel, Count>> : public JointObservationModel< MultipleOf<typename ForwardAdaptive<LocalObsrvModel>::Type, Count>, Adaptive<> > { }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #pragma once #include "iceoryx_utils/platform/types.hpp" #include <cstdlib> #include <stdio.h> #include <type_traits> #define _WINSOCKAPI_ #define WIN32_LEAN_AND_MEAN #include <windows.h> #define SEM_FAILED 0 using sem_t = PVOID; static constexpr LONG MAX_SEMAPHORE_VALUE = LONG_MAX; static constexpr int MAX_SEMAPHORE_NAME_LENGTH = 128; inline int sem_getvalue(sem_t* sem, int* sval) { return -1; } inline int sem_post(sem_t* sem) { int retVal = (ReleaseSemaphore(sem, 1, nullptr) == 0) ? -1 : 0; return retVal; } inline int sem_wait(sem_t* sem) { int retVal = (WaitForSingleObject(sem, INFINITE) == WAIT_FAILED) ? -1 : 0; return retVal; } inline int sem_trywait(sem_t* sem) { if (WaitForSingleObject(sem, 0) == WAIT_FAILED) { return -1; } return 0; } inline int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout) { DWORD timeoutInMilliseconds = static_cast<DWORD>(1); int retVal = (WaitForSingleObject(sem, timeoutInMilliseconds) == WAIT_FAILED) ? -1 : 0; return retVal; } inline int sem_close(sem_t* sem) { int retVal = CloseHandle(sem) ? 0 : -1; return retVal; } inline int sem_destroy(sem_t* sem) { // semaphores are closed in windows when the last process which is // holding a semaphore calls CloseHandle return 0; } inline int sem_init(sem_t* sem, int pshared, unsigned int value) { *sem = CreateSemaphore(nullptr, static_cast<LONG>(value), MAX_SEMAPHORE_VALUE, nullptr); if (sem != nullptr) return 0; return -1; } inline sem_t* sem_open(const char* name, int oflag) { return nullptr; } inline sem_t* sem_open(const char* name, int oflag, mode_t mode, unsigned int value) { wchar_t semaphoreName[MAX_SEMAPHORE_NAME_LENGTH]; mbstowcs(semaphoreName, name, MAX_SEMAPHORE_NAME_LENGTH); return static_cast<sem_t*>(OpenSemaphoreW(0, false, semaphoreName)); } inline int sem_unlink(const char* name) { // semaphores are closed in windows when the last process which is // holding a semaphore calls CloseHandle return 0; } <commit_msg>iox-#33 semaphore partially runs<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #pragma once #include "iceoryx_utils/platform/types.hpp" #include <cstdlib> #include <stdio.h> #include <type_traits> #define _WINSOCKAPI_ #define WIN32_LEAN_AND_MEAN #include <windows.h> #define SEM_FAILED 0 using sem_t = PVOID; static constexpr LONG MAX_SEMAPHORE_VALUE = LONG_MAX; static constexpr int MAX_SEMAPHORE_NAME_LENGTH = 128; inline int sem_getvalue(sem_t* sem, int* sval) { return -1; } inline int sem_post(sem_t* sem) { int retVal = (ReleaseSemaphore(sem, 1, nullptr) == 0) ? -1 : 0; return retVal; } inline int sem_wait(sem_t* sem) { int retVal = (WaitForSingleObject(sem, INFINITE) == WAIT_FAILED) ? -1 : 0; return retVal; } inline int sem_trywait(sem_t* sem) { if (WaitForSingleObject(sem, 0) == WAIT_FAILED) { return -1; } return 0; } inline int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout) { DWORD timeoutInMilliseconds = static_cast<DWORD>(1); int retVal = (WaitForSingleObject(sem, timeoutInMilliseconds) == WAIT_FAILED) ? -1 : 0; return retVal; } inline int sem_close(sem_t* sem) { int retVal = CloseHandle(sem) ? 0 : -1; return retVal; } inline int sem_destroy(sem_t* sem) { // semaphores are closed in windows when the last process which is // holding a semaphore calls CloseHandle return 0; } inline int sem_init(sem_t* sem, int pshared, unsigned int value) { *sem = CreateSemaphore(nullptr, static_cast<LONG>(value), MAX_SEMAPHORE_VALUE, nullptr); if (sem != nullptr) return 0; return -1; } inline sem_t* sem_open(const char* name, int oflag) { return static_cast<sem_t*>(CreateSemaphore(nullptr, 0, MAX_SEMAPHORE_VALUE, name)); } inline sem_t* sem_open(const char* name, int oflag, mode_t mode, unsigned int value) { // GetLastError returns ERROR_ALREADY_EXISTS ... when specific O_FLAG is set use // this return static_cast<sem_t*>(CreateSemaphore(nullptr, value, MAX_SEMAPHORE_VALUE, name)); } inline int sem_unlink(const char* name) { // semaphores are closed in windows when the last process which is // holding a semaphore calls CloseHandle return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <datastreamdlg.hxx> #include <sfx2/filedlghelper.hxx> #include <svtools/inettbc.hxx> #include <vcl/layout.hxx> #include <address.hxx> #include <docsh.hxx> namespace sc { DataStreamDlg::DataStreamDlg(ScDocShell *pDocShell, Window* pParent) : ModalDialog(pParent, "DataStreamDialog", "modules/scalc/ui/datastreams.ui") , mpDocShell(pDocShell) { get(m_pCbUrl, "url"); get(m_pBtnBrowse, "browse"); get(m_pRBScriptData, "scriptdata"); get(m_pRBValuesInLine, "valuesinline"); get(m_pRBAddressValue, "addressvalue"); get(m_pCBRefreshOnEmpty, "refresh_ui"); get(m_pRBDataDown, "datadown"); get(m_pRBRangeDown, "rangedown"); get(m_pRBNoMove, "nomove"); get(m_pRBMaxLimit, "maxlimit"); get(m_pEdRange, "range"); get(m_pEdLimit, "limit"); get(m_pBtnOk, "ok"); get(m_pVclFrameLimit, "framelimit"); get(m_pVclFrameMove, "framemove"); m_pCbUrl->SetSelectHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pRBAddressValue->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pRBAddressValue->Enable(false); m_pRBNoMove->Hide(); m_pRBValuesInLine->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pEdRange->SetModifyHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pBtnBrowse->SetClickHdl( LINK( this, DataStreamDlg, BrowseHdl ) ); UpdateEnable(); } IMPL_LINK_NOARG(DataStreamDlg, BrowseHdl) { sfx2::FileDialogHelper aFileDialog(0, 0); if ( aFileDialog.Execute() != ERRCODE_NONE ) return 0; m_pCbUrl->SetText( aFileDialog.GetPath() ); UpdateEnable(); return 0; } IMPL_LINK_NOARG(DataStreamDlg, UpdateHdl) { UpdateEnable(); return 0; } void DataStreamDlg::UpdateEnable() { bool bOk = !m_pCbUrl->GetURL().isEmpty(); if (m_pRBAddressValue->IsChecked()) { m_pVclFrameLimit->Disable(); m_pVclFrameMove->Disable(); m_pEdRange->Disable(); } else { m_pVclFrameLimit->Enable(); m_pVclFrameMove->Enable(); m_pEdRange->Enable(); if (bOk) { // Check the given range to make sure it's valid. ScRange aTest = GetStartRange(); if (!aTest.IsValid()) bOk = false; } } m_pBtnOk->Enable(bOk); setOptimalLayoutSize(); } ScRange DataStreamDlg::GetStartRange() { OUString aStr = m_pEdRange->GetText(); ScDocument* pDoc = mpDocShell->GetDocument(); ScRange aRange; sal_uInt16 nRes = aRange.Parse(aStr, pDoc); if ((nRes & SCA_VALID) != SCA_VALID || !aRange.IsValid()) { // Invalid range. aRange.SetInvalid(); return aRange; } // Make sure it's only one row tall. if (aRange.aStart.Row() != aRange.aEnd.Row()) aRange.SetInvalid(); return aRange; } void DataStreamDlg::Init( const OUString& rURL, const ScRange& rRange, const sal_Int32 nLimit, DataStream::MoveType eMove, const sal_uInt32 nSettings) { m_pEdLimit->SetText(OUString::number(nLimit)); m_pCbUrl->SetText(rURL); if (nSettings & DataStream::SCRIPT_STREAM) m_pRBScriptData->Check(); if (!(nSettings & DataStream::VALUES_IN_LINE)) m_pRBAddressValue->Check(); OUString aStr = rRange.Format(SCA_VALID); m_pEdRange->SetText(aStr); switch (eMove) { case DataStream::MOVE_DOWN: m_pRBDataDown->Check(); break; break; case DataStream::RANGE_DOWN: m_pRBRangeDown->Check(); break; case DataStream::MOVE_UP: case DataStream::NO_MOVE: default: ; } UpdateEnable(); } void DataStreamDlg::StartStream(DataStream *pStream) { ScRange aStartRange = GetStartRange(); if (!aStartRange.IsValid()) // Don't start the stream without a valid range. return; sal_Int32 nLimit = 0; if (m_pRBMaxLimit->IsChecked()) nLimit = m_pEdLimit->GetText().toInt32(); OUString rURL = m_pCbUrl->GetText(); sal_uInt32 nSettings = 0; if (m_pRBScriptData->IsChecked()) nSettings |= DataStream::SCRIPT_STREAM; if (m_pRBValuesInLine->IsChecked()) nSettings |= DataStream::VALUES_IN_LINE; DataStream::MoveType eMove = m_pRBRangeDown->IsChecked() ? DataStream::RANGE_DOWN : DataStream::MOVE_DOWN; if (pStream) { pStream->Decode(rURL, aStartRange, nLimit, eMove, nSettings); pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked()); return; } pStream = DataStream::Set(mpDocShell, rURL, aStartRange, nLimit, eMove, nSettings); pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked()); DataStream::MakeToolbarVisible(); pStream->StartImport(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Disable script source option.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <datastreamdlg.hxx> #include <sfx2/filedlghelper.hxx> #include <svtools/inettbc.hxx> #include <vcl/layout.hxx> #include <address.hxx> #include <docsh.hxx> namespace sc { DataStreamDlg::DataStreamDlg(ScDocShell *pDocShell, Window* pParent) : ModalDialog(pParent, "DataStreamDialog", "modules/scalc/ui/datastreams.ui") , mpDocShell(pDocShell) { get(m_pCbUrl, "url"); get(m_pBtnBrowse, "browse"); get(m_pRBScriptData, "scriptdata"); get(m_pRBValuesInLine, "valuesinline"); get(m_pRBAddressValue, "addressvalue"); get(m_pCBRefreshOnEmpty, "refresh_ui"); get(m_pRBDataDown, "datadown"); get(m_pRBRangeDown, "rangedown"); get(m_pRBNoMove, "nomove"); get(m_pRBMaxLimit, "maxlimit"); get(m_pEdRange, "range"); get(m_pEdLimit, "limit"); get(m_pBtnOk, "ok"); get(m_pVclFrameLimit, "framelimit"); get(m_pVclFrameMove, "framemove"); m_pCbUrl->SetSelectHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pRBAddressValue->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pRBAddressValue->Enable(false); m_pRBScriptData->Enable(false); m_pRBNoMove->Hide(); m_pRBValuesInLine->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pEdRange->SetModifyHdl( LINK( this, DataStreamDlg, UpdateHdl ) ); m_pBtnBrowse->SetClickHdl( LINK( this, DataStreamDlg, BrowseHdl ) ); UpdateEnable(); } IMPL_LINK_NOARG(DataStreamDlg, BrowseHdl) { sfx2::FileDialogHelper aFileDialog(0, 0); if ( aFileDialog.Execute() != ERRCODE_NONE ) return 0; m_pCbUrl->SetText( aFileDialog.GetPath() ); UpdateEnable(); return 0; } IMPL_LINK_NOARG(DataStreamDlg, UpdateHdl) { UpdateEnable(); return 0; } void DataStreamDlg::UpdateEnable() { bool bOk = !m_pCbUrl->GetURL().isEmpty(); if (m_pRBAddressValue->IsChecked()) { m_pVclFrameLimit->Disable(); m_pVclFrameMove->Disable(); m_pEdRange->Disable(); } else { m_pVclFrameLimit->Enable(); m_pVclFrameMove->Enable(); m_pEdRange->Enable(); if (bOk) { // Check the given range to make sure it's valid. ScRange aTest = GetStartRange(); if (!aTest.IsValid()) bOk = false; } } m_pBtnOk->Enable(bOk); setOptimalLayoutSize(); } ScRange DataStreamDlg::GetStartRange() { OUString aStr = m_pEdRange->GetText(); ScDocument* pDoc = mpDocShell->GetDocument(); ScRange aRange; sal_uInt16 nRes = aRange.Parse(aStr, pDoc); if ((nRes & SCA_VALID) != SCA_VALID || !aRange.IsValid()) { // Invalid range. aRange.SetInvalid(); return aRange; } // Make sure it's only one row tall. if (aRange.aStart.Row() != aRange.aEnd.Row()) aRange.SetInvalid(); return aRange; } void DataStreamDlg::Init( const OUString& rURL, const ScRange& rRange, const sal_Int32 nLimit, DataStream::MoveType eMove, const sal_uInt32 nSettings) { m_pEdLimit->SetText(OUString::number(nLimit)); m_pCbUrl->SetText(rURL); if (nSettings & DataStream::SCRIPT_STREAM) m_pRBScriptData->Check(); if (!(nSettings & DataStream::VALUES_IN_LINE)) m_pRBAddressValue->Check(); OUString aStr = rRange.Format(SCA_VALID); m_pEdRange->SetText(aStr); switch (eMove) { case DataStream::MOVE_DOWN: m_pRBDataDown->Check(); break; break; case DataStream::RANGE_DOWN: m_pRBRangeDown->Check(); break; case DataStream::MOVE_UP: case DataStream::NO_MOVE: default: ; } UpdateEnable(); } void DataStreamDlg::StartStream(DataStream *pStream) { ScRange aStartRange = GetStartRange(); if (!aStartRange.IsValid()) // Don't start the stream without a valid range. return; sal_Int32 nLimit = 0; if (m_pRBMaxLimit->IsChecked()) nLimit = m_pEdLimit->GetText().toInt32(); OUString rURL = m_pCbUrl->GetText(); sal_uInt32 nSettings = 0; if (m_pRBScriptData->IsChecked()) nSettings |= DataStream::SCRIPT_STREAM; if (m_pRBValuesInLine->IsChecked()) nSettings |= DataStream::VALUES_IN_LINE; DataStream::MoveType eMove = m_pRBRangeDown->IsChecked() ? DataStream::RANGE_DOWN : DataStream::MOVE_DOWN; if (pStream) { pStream->Decode(rURL, aStartRange, nLimit, eMove, nSettings); pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked()); return; } pStream = DataStream::Set(mpDocShell, rURL, aStartRange, nLimit, eMove, nSettings); pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked()); DataStream::MakeToolbarVisible(); pStream->StartImport(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <image_cloud/common/small_helpers.hpp> #include <image_cloud/common/type.hpp> #include <image_cloud/common/calibration/multi_score.hpp> #include <image_cloud/common/calibration/structs.hpp> #include <deque> #include <opencv2/core/core.hpp> #include <math.h> #ifndef SEARCH_GRID_6D_H_ #define SEARCH_GRID_6D_H_ namespace search { inline void grid_setup(Search_setup setup, std::vector<Search_value>& results){ for(int x=0; x < setup.x.steps_max; ++x) { for(int y=0; y < setup.y.steps_max; ++y) { for(int z=0; z < setup.z.steps_max; ++z) { for(int roll=0; roll < setup.roll.steps_max; ++roll) { for(int pitch=0; pitch < setup.pitch.steps_max; ++pitch) { for(int yaw=0; yaw < setup.yaw.steps_max; ++yaw) { results.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw))); } } } } } } } template <typename PointT, typename ImageT> inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector<pcl::PointCloud<PointT> > &pointclouds, const std::vector<cv::Mat> &edge_images, std::vector<Search_value>& results){ for(int i=0; i < results.size(); ++i){ score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } } template <typename PointT, typename ImageT> inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &edge_images, std::vector<Search_value>& results){ for(int i=0; i < results.size(); ++i){ score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } } template <typename PointT, typename ImageT> inline void get_best_tf( tf::Transform in, tf::Transform &out, const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &images, float range = 0.5, int steps = 3) { Search_setup search_range; std::vector<Search_value> results; double r,p,y; in.getBasis().getRPY(r, p, y); search_range.x.init_range(in.getOrigin()[0], range, steps); search_range.y.init_range(in.getOrigin()[1], range, steps); search_range.z.init_range(in.getOrigin()[2], range, steps); search_range.roll.init_range(r, range, steps); search_range.pitch.init_range(p, range, steps); search_range.yaw.init_range(y, range, steps); grid_setup(search_range, results); calculate<PointT, ImageT>( camera_model, pointclouds, images, results ); int best_result_idx = 0; long unsigned int best_result = 0; for(int i=0; i< results.size(); ++i){ if(results.at(i).result > best_result){ best_result_idx = i; best_result = results.at(i).result; } } //printf("%d: \t%s\n", best_result_idx, results.at(best_result_idx).to_string().c_str()); results.at(best_result_idx).get_transform(out); } } #endif <commit_msg>add origin point to calculation list if not present<commit_after>#include <image_cloud/common/small_helpers.hpp> #include <image_cloud/common/type.hpp> #include <image_cloud/common/calibration/multi_score.hpp> #include <image_cloud/common/calibration/structs.hpp> #include <deque> #include <opencv2/core/core.hpp> #include <math.h> #ifndef SEARCH_GRID_6D_H_ #define SEARCH_GRID_6D_H_ namespace search { inline void grid_setup(Search_setup setup, std::vector<Search_value>& results){ for(int x=0; x < setup.x.steps_max; ++x) { for(int y=0; y < setup.y.steps_max; ++y) { for(int z=0; z < setup.z.steps_max; ++z) { for(int roll=0; roll < setup.roll.steps_max; ++roll) { for(int pitch=0; pitch < setup.pitch.steps_max; ++pitch) { for(int yaw=0; yaw < setup.yaw.steps_max; ++yaw) { results.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw))); } } } } } } } template <typename PointT, typename ImageT> inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector<pcl::PointCloud<PointT> > &pointclouds, const std::vector<cv::Mat> &edge_images, std::vector<Search_value>& results, bool pre_filtred=true){ for(int i=0; i < results.size(); ++i){ if(pre_filtred) { score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } else{ score::multi_score_filter_depth<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } } } template <typename PointT, typename ImageT> inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &edge_images, std::vector<Search_value>& results, bool pre_filtred=true){ for(int i=0; i < results.size(); ++i){ if(pre_filtred) { score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } else{ score::multi_score_filter_depth<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i)); } } } template <typename PointT, typename ImageT> inline void get_best_tf( tf::Transform in, tf::Transform &out, const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &images, float range_axis = 0.5, float range_rot = 0.5, int steps = 3, bool pre_filtred = true, Multi_search_result *multi_result = NULL) { Search_setup search_range; std::vector<Search_value> result_list; double r,p,y; in.getBasis().getRPY(r, p, y); search_range.x.init_range(in.getOrigin()[0], range_axis, steps); search_range.y.init_range(in.getOrigin()[1], range_axis, steps); search_range.z.init_range(in.getOrigin()[2], range_axis, steps); search_range.roll.init_range(r, range_rot, steps); search_range.pitch.init_range(p, range_rot, steps); search_range.yaw.init_range(y, range_rot, steps); grid_setup(search_range, result_list); Search_value origin_empty; origin_empty.init(in); // Add origin if(result_list.size() %2 == 0){ result_list.insert(result_list.begin()+(result_list.size()/2), origin_empty); } calculate<PointT, ImageT>( camera_model, pointclouds, images, result_list, pre_filtred); // get origin Search_value origin = result_list.at( (result_list.size()) / 2); std::cout << "center"<< spacer << origin.to_string() << "\n"; std::cout << "empty" << spacer << origin_empty.to_string() << "\n"; // assert(origin.x == origin_empty.x); assert(origin.y == origin_empty.y); assert(origin.z == origin_empty.z); assert(origin.roll == origin_empty.roll); assert(origin.pitch == origin_empty.pitch); assert(origin.yaw == origin_empty.yaw); assert(origin.result != origin_empty.result); long unsigned int worse = 0; long unsigned int best_result = 0; long unsigned int best_result_idx = 0; for(int i=0; i< result_list.size(); ++i){ if(result_list.at(i).result > best_result){ best_result_idx = i; best_result = result_list.at(i).result; } if( origin.result > result_list.at(i).result ){ ++worse; } } result_list.at(best_result_idx).get_transform(out); if(multi_result != NULL){ multi_result->best = result_list.at(best_result_idx); multi_result->in = origin; multi_result->nr_worse = worse; multi_result->nr_total = result_list.size(); } } } #endif <|endoftext|>
<commit_before>#include "VideoArea.h" #include "ui_VideoArea.h" #include "tcam_qt4.h" #include <iostream> using namespace tcam; VideoArea::VideoArea (QWidget* parent, DeviceInfo* i) : QWidget(parent), ui(new Ui::VideoArea), device(nullptr), received_new_image(false), playing(false) { ui->setupUi(this); if (i != nullptr) { device = std::make_shared<tcam::CaptureDevice>(*i); } //new QShortcut(QKeySequence(tr("Ctrl-SPACE")), this, SLOT(action()), 0, Qt::WidgetShortcut); } VideoArea::~VideoArea () { delete ui; } void VideoArea::start () { if (device == nullptr) { return; } sink = std::make_shared<ImageSink>(); sink->registerCallback(this->callback, this); bool ret = device->start_stream(sink); if (ret == true) { std::cout << "RUNNING..." << std::endl; playing = true; } } void VideoArea::stop () { device->stop_stream(); playing = false; } bool VideoArea::setVideoFormat (const tcam::VideoFormat& format) { if (playing) { return false; } return device->set_video_format(format); } tcam::VideoFormat VideoArea::getVideoFormat () const { return device->get_active_video_format(); } std::vector<tcam::VideoFormatDescription> VideoArea::getAvailableVideoFormats () const { return device->get_available_video_formats(); } QTreeWidget* VideoArea::get_property_tree (QWidget* p) { return create_property_tree(p, device->get_available_properties()); } void VideoArea::callback (MemoryBuffer* buffer, void* user_data) { VideoArea* self = static_cast<VideoArea*>(user_data); self->internal_callback(buffer); } void VideoArea::internal_callback(MemoryBuffer* buffer) { if (buffer->get_data() == NULL || buffer->getImageBuffer().length == 0) { return; } // if (buffer->getImageBuffer().format.height != active_format.getSize().height|| buffer->getImageBuffer().format.width != active_format.getSize().width) // { // std::cout << "Faulty format!!!" << std::endl; // return; // } // TODO: if (buffer->getImageBuffer().pitch == 0 ) { return; } auto buf = buffer->getImageBuffer(); unsigned int height = buffer->getImageBuffer().format.height; unsigned int width = buffer->getImageBuffer().format.width; if (buf.format.fourcc == FOURCC_Y800) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_Indexed8)); } else if (buf.format.fourcc == FOURCC_Y16) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_Mono)); } else if (buf.format.fourcc == FOURCC_RGB24) { QImage image = QImage(buf.pData, width, height, QImage::Format_RGB888); // rgb24 is really bgr, thus swap r <-> b this->m = QPixmap::fromImage(image.rgbSwapped()); } else if (buf.format.fourcc == FOURCC_RGB32) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_RGB32)); } else { std::cout << "Unable to interpret buffer format" << std::endl; return; } this->received_new_image = true; this->update(); } void VideoArea::paintEvent (QPaintEvent* e) { if (m.width() == 0) { return; } if (received_new_image) { unsigned int w = ui->label->width(); unsigned int h = ui->label->height(); auto l = this->layout(); int margin = l->margin(); // ui->label->setPixmap(m.scaled(w - margin, // h -margin, // Qt::KeepAspectRatio, // Qt::FastTransformation )); ui->label->setPixmap(m); // ui->label->setPixmap(m.scaled(w, // h, // Qt::KeepAspectRatio)); // , // Qt::FastTransformation )); new_image=false; received_new_image = false; } } void VideoArea::resizeEvent (QResizeEvent* event) { //std::cout << "RESIZE!!!" << std::endl; // get label dimensions int w = ui->label->width(); int h = ui->label->height(); // set a scaled pixmap to a w x h window keeping its aspect ratio // ui->label->setPixmap(m.scaled(w, h, Qt::KeepAspectRatio)); ui->label->setPixmap(m); //ui->label->adjustSize(); } <commit_msg>Remove commented code<commit_after>#include "VideoArea.h" #include "ui_VideoArea.h" #include "tcam_qt4.h" #include <iostream> using namespace tcam; VideoArea::VideoArea (QWidget* parent, DeviceInfo* i) : QWidget(parent), ui(new Ui::VideoArea), device(nullptr), received_new_image(false), playing(false) { ui->setupUi(this); if (i != nullptr) { device = std::make_shared<tcam::CaptureDevice>(*i); } //new QShortcut(QKeySequence(tr("Ctrl-SPACE")), this, SLOT(action()), 0, Qt::WidgetShortcut); } VideoArea::~VideoArea () { delete ui; } void VideoArea::start () { if (device == nullptr) { return; } sink = std::make_shared<ImageSink>(); sink->registerCallback(this->callback, this); bool ret = device->start_stream(sink); if (ret == true) { std::cout << "RUNNING..." << std::endl; playing = true; } } void VideoArea::stop () { device->stop_stream(); playing = false; } bool VideoArea::setVideoFormat (const tcam::VideoFormat& format) { if (playing) { return false; } return device->set_video_format(format); } tcam::VideoFormat VideoArea::getVideoFormat () const { return device->get_active_video_format(); } std::vector<tcam::VideoFormatDescription> VideoArea::getAvailableVideoFormats () const { return device->get_available_video_formats(); } QTreeWidget* VideoArea::get_property_tree (QWidget* p) { return create_property_tree(p, device->get_available_properties()); } void VideoArea::callback (MemoryBuffer* buffer, void* user_data) { VideoArea* self = static_cast<VideoArea*>(user_data); self->internal_callback(buffer); } void VideoArea::internal_callback(MemoryBuffer* buffer) { if (buffer->get_data() == NULL || buffer->getImageBuffer().length == 0) { return; } // if (buffer->getImageBuffer().format.height != active_format.getSize().height|| buffer->getImageBuffer().format.width != active_format.getSize().width) // { // std::cout << "Faulty format!!!" << std::endl; // return; // } // TODO: if (buffer->getImageBuffer().pitch == 0 ) { return; } auto buf = buffer->getImageBuffer(); unsigned int height = buffer->getImageBuffer().format.height; unsigned int width = buffer->getImageBuffer().format.width; if (buf.format.fourcc == FOURCC_Y800) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_Indexed8)); } else if (buf.format.fourcc == FOURCC_Y16) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_Mono)); } else if (buf.format.fourcc == FOURCC_RGB24) { QImage image = QImage(buf.pData, width, height, QImage::Format_RGB888); // rgb24 is really bgr, thus swap r <-> b this->m = QPixmap::fromImage(image.rgbSwapped()); } else if (buf.format.fourcc == FOURCC_RGB32) { this->m = QPixmap::fromImage(QImage(buf.pData, width, height, QImage::Format_RGB32)); } else { std::cout << "Unable to interpret buffer format" << std::endl; return; } this->received_new_image = true; this->update(); } void VideoArea::paintEvent (QPaintEvent* e) { if (m.width() == 0) { return; } if (received_new_image) { ui->label->setPixmap(m); new_image=false; received_new_image = false; } } void VideoArea::resizeEvent (QResizeEvent* /* event */) { // set a scaled pixmap to a w x h window keeping its aspect ratio // ui->label->setPixmap(m.scaled(w, h, Qt::KeepAspectRatio)); ui->label->setPixmap(m); //ui->label->adjustSize(); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_daemon_core.h" // for 'param' function #include "condor_config.h" #include "BaseReplicaTransferer.h" #include "FilesOperations.h" #include "Utils.h" BaseReplicaTransferer::BaseReplicaTransferer( const MyString& pDaemonSinfulString, const MyString& pVersionFilePath, //const MyString& pStateFilePath ): const StringList& pStateFilePathsList ): m_daemonSinfulString( pDaemonSinfulString ), m_versionFilePath( pVersionFilePath ), //m_stateFilePathsList( pStateFilePathsList ), m_socket( 0 ), m_connectionTimeout( DEFAULT_SEND_COMMAND_TIMEOUT ), m_maxTransferLifetime( DEFAULT_MAX_TRANSFER_LIFETIME ) { // 'malloc'-allocated string char* stateFilePathsAsString = const_cast<StringList&>(pStateFilePathsList).print_to_string(); // copying the string lists if ( stateFilePathsAsString ) { m_stateFilePathsList.initializeFromString( stateFilePathsAsString ); } free( stateFilePathsAsString ); } BaseReplicaTransferer::~BaseReplicaTransferer() { delete m_socket; } int BaseReplicaTransferer::reinitialize( ) { dprintf( D_ALWAYS, "BaseReplicaTransferer::reinitialize started\n" ); char* buffer = param( "HAD_CONNECTION_TIMEOUT" ); if( buffer ) { bool result = false; m_connectionTimeout = utilAtoi( buffer, &result ); //strtol( buffer, 0, 10 ); if( ! result || m_connectionTimeout <= 0 ) { utilCrucialError( utilConfigurationError("HAD_CONNECTION_TIMEOUT", "HAD").Value( ) ); } free( buffer ); } else { utilCrucialError( utilNoParameterError("HAD_CONNECTION_TIMEOUT", "HAD").Value( ) ); } m_maxTransferLifetime = param_integer( "MAX_TRANSFER_LIFETIME", DEFAULT_MAX_TRANSFER_LIFETIME ); return TRANSFERER_TRUE; } void BaseReplicaTransferer::safeUnlinkStateAndVersionFiles( const StringList& stateFilePathsList, const MyString& versionFilePath, const MyString& extension) { FilesOperations::safeUnlinkFile( versionFilePath.Value( ), extension.Value( ) ); StringList& stateFilePathsListRef = const_cast<StringList&>(stateFilePathsList); stateFilePathsListRef.rewind(); char* stateFilePath = NULL; while( ( stateFilePath = stateFilePathsListRef.next( ) ) ) { FilesOperations::safeUnlinkFile( stateFilePath, extension.Value( ) ); } stateFilePathsListRef.rewind(); } <commit_msg>param+nonsense -> param_integer for HAD_CONNECTION_TIMEOUT, documentation said default was 5, code didn't agree in all cases<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_daemon_core.h" // for 'param' function #include "condor_config.h" #include "BaseReplicaTransferer.h" #include "FilesOperations.h" #include "Utils.h" BaseReplicaTransferer::BaseReplicaTransferer( const MyString& pDaemonSinfulString, const MyString& pVersionFilePath, //const MyString& pStateFilePath ): const StringList& pStateFilePathsList ): m_daemonSinfulString( pDaemonSinfulString ), m_versionFilePath( pVersionFilePath ), //m_stateFilePathsList( pStateFilePathsList ), m_socket( 0 ), m_connectionTimeout( DEFAULT_SEND_COMMAND_TIMEOUT ), m_maxTransferLifetime( DEFAULT_MAX_TRANSFER_LIFETIME ) { // 'malloc'-allocated string char* stateFilePathsAsString = const_cast<StringList&>(pStateFilePathsList).print_to_string(); // copying the string lists if ( stateFilePathsAsString ) { m_stateFilePathsList.initializeFromString( stateFilePathsAsString ); } free( stateFilePathsAsString ); } BaseReplicaTransferer::~BaseReplicaTransferer() { delete m_socket; } int BaseReplicaTransferer::reinitialize( ) { dprintf( D_ALWAYS, "BaseReplicaTransferer::reinitialize started\n" ); m_connectionTimeout = param_integer("HAD_CONNECTION_TIMEOUT", DEFAULT_SEND_COMMAND_TIMEOUT, 0); // min value m_maxTransferLifetime = param_integer( "MAX_TRANSFER_LIFETIME", DEFAULT_MAX_TRANSFER_LIFETIME ); return TRANSFERER_TRUE; } void BaseReplicaTransferer::safeUnlinkStateAndVersionFiles( const StringList& stateFilePathsList, const MyString& versionFilePath, const MyString& extension) { FilesOperations::safeUnlinkFile( versionFilePath.Value( ), extension.Value( ) ); StringList& stateFilePathsListRef = const_cast<StringList&>(stateFilePathsList); stateFilePathsListRef.rewind(); char* stateFilePath = NULL; while( ( stateFilePath = stateFilePathsListRef.next( ) ) ) { FilesOperations::safeUnlinkFile( stateFilePath, extension.Value( ) ); } stateFilePathsListRef.rewind(); } <|endoftext|>
<commit_before>#ifndef UTIL_RECT_H__ #define UTIL_RECT_H__ #include <sstream> #include <iostream> #include "point.hpp" namespace util { template <typename T> struct rect { /** * Default constructor. */ rect() {}; rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) : minX(minX_), minY(minY_), maxX(maxX_), maxY(maxY_) {}; T minX; T minY; T maxX; T maxY; T width() const { return maxX - minX; } T height() const { return maxY - minY; } bool intersects(const rect<T>& other) const { // two non-intersecting rectanlges are separated by a line parallel to // either x or y // separated by x-line if (maxX < other.minX || minX > other.maxX) return false; // separated by y-line if (maxY < other.minY || minY > other.maxY) return false; return true; } bool contains(const point<T>& point) const { return minX <= point.x && minY <= point.y && maxX >= point.x && maxY >= point.y; } template <typename S> rect<T>& operator+=(const point<S>& other) { minX += other.x; maxX += other.x; minY += other.y; maxY += other.y; return *this; } template <typename S> rect<T>& operator-=(const point<S>& other) { minX -= other.x; maxX -= other.x; minY -= other.y; maxY -= other.y; return *this; } template <typename S> rect<T>& operator*=(const S& s) { minX *= s; maxX *= s; minY *= s; maxY *= s; return *this; } template <typename S> rect<T>& operator/=(const S& s) { minX /= s; maxX /= s; minY /= s; maxY /= s; return *this; } template <typename S> rect<T>& operator*=(const point<S>& p) { minX *= p.x; maxX *= p.x; minY *= p.y; maxY *= p.y; return *this; } template <typename S> rect<T>& operator/=(const point<S>& p) { minX /= p.x; maxX /= p.x; minY /= p.y; maxY /= p.y; return *this; } template <typename S> bool operator==(const rect<S>& other) const { return minX == other.minX && minY == other.minY && maxX == other.maxX && maxY == other.maxY; } template <typename S> bool operator!=(const rect<S>& other) const { return !(*this == other); } }; template <typename T, typename S> rect<T> operator+(const rect<T>& p, const point<S>& o) { rect<T> result(p); return result += o; } template <typename T, typename S> rect<T> operator-(const rect<T>& p, const point<S>& o) { rect<T> result(p); return result -= o; } template <typename T, typename S> rect<T> operator*(const rect<T>& p, const S& s) { rect<T> result(p); return result *= s; } template <typename T, typename S> rect<T> operator/(const rect<T>& p, const S& s) { rect<T> result(p); return result /= s; } template <typename T> std::ostream& operator<<(std::ostream& os, const rect<T>& rect) { os << "[" << rect.minX << ", " << rect.minY << ", " << rect.maxX << ", " << rect.maxY << "]"; return os; } } // namespace util #endif // UTIL_RECT_H__ <commit_msg>made 'contains' query in rect exclude left and bottom border<commit_after>#ifndef UTIL_RECT_H__ #define UTIL_RECT_H__ #include <sstream> #include <iostream> #include "point.hpp" namespace util { template <typename T> struct rect { /** * Default constructor. */ rect() {}; template <typename S> rect(const rect<S>& other) : minX(other.minX), minY(other.minY), maxX(other.maxX), maxY(other.maxY) {}; rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) : minX(minX_), minY(minY_), maxX(maxX_), maxY(maxY_) {}; T minX; T minY; T maxX; T maxY; T width() const { return maxX - minX; } T height() const { return maxY - minY; } bool intersects(const rect<T>& other) const { // two non-intersecting rectanlges are separated by a line parallel to // either x or y // separated by x-line if (maxX < other.minX || minX > other.maxX) return false; // separated by y-line if (maxY < other.minY || minY > other.maxY) return false; return true; } bool contains(const point<T>& point) const { return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y; } template <typename S> rect<T>& operator+=(const point<S>& other) { minX += other.x; maxX += other.x; minY += other.y; maxY += other.y; return *this; } template <typename S> rect<T>& operator-=(const point<S>& other) { minX -= other.x; maxX -= other.x; minY -= other.y; maxY -= other.y; return *this; } template <typename S> rect<T>& operator*=(const S& s) { minX *= s; maxX *= s; minY *= s; maxY *= s; return *this; } template <typename S> rect<T>& operator/=(const S& s) { minX /= s; maxX /= s; minY /= s; maxY /= s; return *this; } template <typename S> rect<T>& operator*=(const point<S>& p) { minX *= p.x; maxX *= p.x; minY *= p.y; maxY *= p.y; return *this; } template <typename S> rect<T>& operator/=(const point<S>& p) { minX /= p.x; maxX /= p.x; minY /= p.y; maxY /= p.y; return *this; } template <typename S> bool operator==(const rect<S>& other) const { return minX == other.minX && minY == other.minY && maxX == other.maxX && maxY == other.maxY; } template <typename S> bool operator!=(const rect<S>& other) const { return !(*this == other); } }; template <typename T, typename S> rect<T> operator+(const rect<T>& p, const point<S>& o) { rect<T> result(p); return result += o; } template <typename T, typename S> rect<T> operator-(const rect<T>& p, const point<S>& o) { rect<T> result(p); return result -= o; } template <typename T, typename S> rect<T> operator*(const rect<T>& p, const S& s) { rect<T> result(p); return result *= s; } template <typename T, typename S> rect<T> operator/(const rect<T>& p, const S& s) { rect<T> result(p); return result /= s; } template <typename T> std::ostream& operator<<(std::ostream& os, const rect<T>& rect) { os << "[" << rect.minX << ", " << rect.minY << ", " << rect.maxX << ", " << rect.maxY << "]"; return os; } } // namespace util #endif // UTIL_RECT_H__ <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////// // nth_prime.cpp // Find the nth prime. // Usage: $ ./nth_prime 999 #include <primesieve/soe/PrimeSieve.h> #include <iostream> #include <cstdlib> #include <limits> #include <exception> class stop_primesieve : public std::exception { }; int n = 100000000; int count = 0; void nthprime(unsigned int prime) { if (++count == n) { std::cout << n << "th prime = " << prime << std::endl; throw stop_primesieve(); } } int main(int, char** argv) { if (argv[1]) n = atoi(argv[1]); try { PrimeSieve ps; ps.generatePrimes(0, std::numeric_limits<int>::max(), nthprime); } catch (stop_primesieve&) { } return 0; } <commit_msg>count variable name conflicts with std::count from <algorithm> (pgcpp compiler)<commit_after>//////////////////////////////////////////////////////////////////// // nth_prime.cpp // Find the nth prime. // Usage: $ ./nth_prime 999 #include <primesieve/soe/PrimeSieve.h> #include <iostream> #include <cstdlib> #include <limits> #include <exception> class stop_primesieve : public std::exception { }; int n = 100000000; int i = 0; void nthprime(unsigned int prime) { if (++i == n) { std::cout << n << "th prime = " << prime << std::endl; throw stop_primesieve(); } } int main(int, char** argv) { if (argv[1]) n = atoi(argv[1]); try { PrimeSieve ps; ps.generatePrimes(0, std::numeric_limits<int>::max(), nthprime); } catch (stop_primesieve&) { } return 0; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2020 BMW Car IT GmbH * %% * 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. * #L% */ #include <memory> #include <string> #include "tests/utils/Gtest.h" #include "tests/utils/Gmock.h" #include "joynr/Settings.h" #include "joynr/LibjoynrSettings.h" #include "joynr/system/RoutingProxy.h" #include "joynr/serializer/Serializer.h" #include "tests/JoynrTest.h" #include "tests/mock/MockTransportMessageReceiver.h" #include "tests/mock/MockTransportMessageSender.h" #include "tests/mock/TestJoynrClusterControllerRuntime.h" #include "tests/utils/PtrUtils.h" using namespace joynr; using ::testing::Mock; class SystemServicesRoutingTest : public ::testing::Test { public: SystemServicesRoutingTest() : settingsFilename("test-resources/SystemServicesRoutingTest.settings"), settings(std::make_unique<Settings>(settingsFilename)), routingDomain(), routingProviderParticipantId(), runtime(nullptr), mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()), discoveryQos(), routingProxyBuilder(nullptr), routingProxy(nullptr), globalMqttTopic("mqtt_SystemServicesRoutingTest.topic"), globalMqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl"), mqttGlobalAddress() { SystemServicesSettings systemSettings(*settings); systemSettings.printSettings(); routingDomain = systemSettings.getDomain(); routingProviderParticipantId = systemSettings.getCcRoutingProviderParticipantId(); discoveryQos.setCacheMaxAgeMs(1000); discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); discoveryQos.addCustomParameter("fixedParticipantId", routingProviderParticipantId); discoveryQos.setDiscoveryTimeoutMs(50); std::string serializedMqttAddress = joynr::serializer::serializeToJson(mqttGlobalAddress); EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>( mockMessageReceiverMqtt).get()), getSerializedGlobalClusterControllerAddress()) .WillRepeatedly(::testing::Return(serializedMqttAddress)); EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>( mockMessageReceiverMqtt).get()), getGlobalClusterControllerAddress()) .WillRepeatedly(::testing::ReturnRef(mqttGlobalAddress)); // runtime can only be created, after MockMessageReceiver has been told to return // a channelId for getReceiveChannelId. runtime = std::make_unique<TestJoynrClusterControllerRuntime>( std::move(settings), failOnFatalRuntimeError, nullptr, nullptr); // routing provider is normally registered in JoynrClusterControllerRuntime::create runtime->init(); } ~SystemServicesRoutingTest() { runtime->stopExternalCommunication(); runtime->shutdown(); runtime.reset(); EXPECT_TRUE(Mock::VerifyAndClearExpectations( std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt) .get())); test::util::resetAndWaitUntilDestroyed(runtime); test::util::resetAndWaitUntilDestroyed(mockMessageReceiverMqtt); std::remove(settingsFilename.c_str()); // Delete persisted files std::remove(ClusterControllerSettings:: DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str()); std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str()); } void SetUp() { participantId = util::createUuid(); isGloballyVisible = true; routingProxyBuilder = runtime->createProxyBuilder<joynr::system::RoutingProxy>(routingDomain); } protected: std::string settingsFilename; std::unique_ptr<Settings> settings; std::string routingDomain; std::string routingProviderParticipantId; std::shared_ptr<TestJoynrClusterControllerRuntime> runtime; std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt; DiscoveryQos discoveryQos; std::shared_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder; std::shared_ptr<joynr::system::RoutingProxy> routingProxy; std::string participantId; bool isGloballyVisible; private: DISALLOW_COPY_AND_ASSIGN(SystemServicesRoutingTest); const std::string globalMqttTopic; const std::string globalMqttBrokerUrl; const system::RoutingTypes::MqttAddress mqttGlobalAddress; }; TEST_F(SystemServicesRoutingTest, routingProviderIsAvailable) { JOYNR_EXPECT_NO_THROW(routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build()); } TEST_F(SystemServicesRoutingTest, unknowParticipantIsNotResolvable) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); } TEST_F(SystemServicesRoutingTest, addNextHopMqtt) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); joynr::system::RoutingTypes::MqttAddress address( "brokerUri", "SystemServicesRoutingTest.ChanneldId.A"); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); try { routingProxy->addNextHop(participantId, address, isGloballyVisible); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "addNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_TRUE(isResolvable); } TEST_F(SystemServicesRoutingTest, removeNextHopMqtt) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); joynr::system::RoutingTypes::MqttAddress address( "brokerUri", "SystemServicesRoutingTest.ChanneldId.A"); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); try { routingProxy->addNextHop(participantId, address, isGloballyVisible); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "addNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_TRUE(isResolvable); try { routingProxy->removeNextHop(participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "removeNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); } <commit_msg>[C++] Fixed SystemServicesRoutingTest<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2020 BMW Car IT GmbH * %% * 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. * #L% */ #include <memory> #include <string> #include "tests/utils/Gtest.h" #include "tests/utils/Gmock.h" #include "joynr/Settings.h" #include "joynr/LibjoynrSettings.h" #include "joynr/system/RoutingProxy.h" #include "joynr/serializer/Serializer.h" #include "tests/JoynrTest.h" #include "tests/mock/MockTransportMessageReceiver.h" #include "tests/mock/MockTransportMessageSender.h" #include "tests/mock/TestJoynrClusterControllerRuntime.h" #include "tests/utils/PtrUtils.h" using namespace joynr; using ::testing::Mock; class SystemServicesRoutingTest : public ::testing::Test { public: SystemServicesRoutingTest() : settingsFilename("test-resources/SystemServicesRoutingTest.settings"), settings(std::make_unique<Settings>(settingsFilename)), routingDomain(), routingProviderParticipantId(), runtime(nullptr), mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()), discoveryQos(), routingProxyBuilder(nullptr), routingProxy(nullptr), globalMqttTopic("mqtt_SystemServicesRoutingTest.topic"), globalMqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl"), mqttGlobalAddress() { SystemServicesSettings systemSettings(*settings); systemSettings.printSettings(); routingDomain = systemSettings.getDomain(); routingProviderParticipantId = systemSettings.getCcRoutingProviderParticipantId(); discoveryQos.setCacheMaxAgeMs(1000); discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); discoveryQos.addCustomParameter("fixedParticipantId", routingProviderParticipantId); discoveryQos.setDiscoveryTimeoutMs(1000); std::string serializedMqttAddress = joynr::serializer::serializeToJson(mqttGlobalAddress); EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>( mockMessageReceiverMqtt).get()), getSerializedGlobalClusterControllerAddress()) .WillRepeatedly(::testing::Return(serializedMqttAddress)); EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>( mockMessageReceiverMqtt).get()), getGlobalClusterControllerAddress()) .WillRepeatedly(::testing::ReturnRef(mqttGlobalAddress)); // runtime can only be created, after MockMessageReceiver has been told to return // a channelId for getReceiveChannelId. runtime = std::make_unique<TestJoynrClusterControllerRuntime>( std::move(settings), failOnFatalRuntimeError, nullptr, nullptr); // routing provider is normally registered in JoynrClusterControllerRuntime::create runtime->init(); } ~SystemServicesRoutingTest() { runtime->stopExternalCommunication(); runtime->shutdown(); runtime.reset(); EXPECT_TRUE(Mock::VerifyAndClearExpectations( std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt) .get())); test::util::resetAndWaitUntilDestroyed(runtime); test::util::resetAndWaitUntilDestroyed(mockMessageReceiverMqtt); std::remove(settingsFilename.c_str()); // Delete persisted files std::remove(ClusterControllerSettings:: DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str()); std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str()); } void SetUp() { participantId = util::createUuid(); isGloballyVisible = true; routingProxyBuilder = runtime->createProxyBuilder<joynr::system::RoutingProxy>(routingDomain); } protected: std::string settingsFilename; std::unique_ptr<Settings> settings; std::string routingDomain; std::string routingProviderParticipantId; std::shared_ptr<TestJoynrClusterControllerRuntime> runtime; std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt; DiscoveryQos discoveryQos; std::shared_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder; std::shared_ptr<joynr::system::RoutingProxy> routingProxy; std::string participantId; bool isGloballyVisible; private: DISALLOW_COPY_AND_ASSIGN(SystemServicesRoutingTest); const std::string globalMqttTopic; const std::string globalMqttBrokerUrl; const system::RoutingTypes::MqttAddress mqttGlobalAddress; }; TEST_F(SystemServicesRoutingTest, routingProviderIsAvailable) { JOYNR_EXPECT_NO_THROW(routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build()); } TEST_F(SystemServicesRoutingTest, unknowParticipantIsNotResolvable) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); } TEST_F(SystemServicesRoutingTest, addNextHopMqtt) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); joynr::system::RoutingTypes::MqttAddress address( "brokerUri", "SystemServicesRoutingTest.ChanneldId.A"); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); try { routingProxy->addNextHop(participantId, address, isGloballyVisible); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "addNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_TRUE(isResolvable); } TEST_F(SystemServicesRoutingTest, removeNextHopMqtt) { routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(5000)) ->setDiscoveryQos(discoveryQos) ->build(); joynr::system::RoutingTypes::MqttAddress address( "brokerUri", "SystemServicesRoutingTest.ChanneldId.A"); bool isResolvable = false; try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); try { routingProxy->addNextHop(participantId, address, isGloballyVisible); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "addNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_TRUE(isResolvable); try { routingProxy->removeNextHop(participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "removeNextHop was not successful"; } try { routingProxy->resolveNextHop(isResolvable, participantId); } catch (const exceptions::JoynrException& e) { ADD_FAILURE() << "resolveNextHop was not successful"; } EXPECT_FALSE(isResolvable); } <|endoftext|>
<commit_before>/* Copyright (C) 1998, 1999 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "soundraw.h" IMPLEMENT_IBASE(csSoundDataRaw); IMPLEMENTS_INTERFACE(iSoundData); IMPLEMENT_IBASE_END; csSoundDataRaw::csSoundDataRaw(iBase *iParent, void *d, long n, csSoundFormat f) { CONSTRUCT_IBASE(iParent); Data = d; NumSamples = n; Format = f; } csSoundDataRaw::~csSoundDataRaw() { unsigned char* const p = (unsigned char*)Data; delete[] p; } long csSoundDataRaw::GetNumSamples() { return NumSamples; } const csSoundFormat *csSoundDataRaw::GetFormat() { return &Format; } iSoundStream *csSoundDataRaw::CreateStream() { return new csSoundStreamRaw(this); } #define REPLACE_DATA(x) { \ unsigned char* const p = (unsigned char*)Data; \ delete[] p; \ Data = x; \ } void *ConvertBuffer8To16Bit(void *buf, unsigned long Num) { unsigned char *in=(unsigned char *)buf; short *out=new short[Num]; for (unsigned long i=0;i<Num;i++) { out[i]=((short)in[i]-128)*256; } return out; } void *ConvertBuffer16To8Bit(void *buf, unsigned long Num) { short *in=(short *)buf; unsigned char *out=new unsigned char[Num]; for (unsigned long i=0;i<Num;i++) { out[i]=(in[i]/256)+128; } return out; } #define CONVERT_CHANNELS_TYPE(Type) { \ Type *OldData=(Type*)d; \ if (newfmt->Channels==1) { \ Type *NewData=new Type[NumSamples]; \ for (long i=0;i<NumSamples;i++) { \ NewData[i]=(OldData[2*i]+OldData[2*i+1])/2; \ } \ return NewData; \ } else { \ Type *NewData=new Type[NumSamples*2]; \ for (long i=0;i<NumSamples;i++) { \ NewData[2*i]=NewData[2*i+1]=OldData[i]; \ } \ return NewData; \ } \ } void *ConvertChannels(void *d, const csSoundFormat *oldfmt, const csSoundFormat *newfmt, long NumSamples) { if (oldfmt->Bits == 8) { CONVERT_CHANNELS_TYPE(unsigned char); } else { CONVERT_CHANNELS_TYPE(short); } } // @@@ ConvertFreq() : quality loss! Need to use a filter. #define CONVERT_FREQ_TYPE(Type,Channels) { \ Type *NewData=new Type[NewNumSamples*Channels]; \ Type *OldData=(Type*)d; \ for (unsigned long i=0;i<NewNumSamples;i++) { \ int samppos = (int)(i/Factor); \ if (Channels==1) { \ NewData[i]=OldData[samppos]; \ } else { \ NewData[2*i]=OldData[2*samppos]; \ NewData[2*i+1]=OldData[2*samppos+1]; \ } \ } \ NumSamples = NewNumSamples; \ return NewData; \ } void *ConvertFreq(void *d, const csSoundFormat *oldfmt, const csSoundFormat *newfmt, long &NumSamples) { float Factor=newfmt->Freq/oldfmt->Freq; unsigned long NewNumSamples=(unsigned long)(NumSamples*Factor); if (oldfmt->Bits==16) { CONVERT_FREQ_TYPE(short,oldfmt->Channels); } else { CONVERT_FREQ_TYPE(unsigned char,oldfmt->Channels); } } void csSoundDataRaw::Convert(const csSoundFormat *RequestFormat) { if (Format.Bits==16 && RequestFormat->Bits==8) { REPLACE_DATA(ConvertBuffer16To8Bit(Data, NumSamples * Format.Channels)); Format.Bits = 8; } else if (Format.Bits==8 && RequestFormat->Bits==16) { REPLACE_DATA(ConvertBuffer8To16Bit(Data, NumSamples * Format.Channels)); Format.Bits = 16; } if (Format.Channels != RequestFormat->Channels && RequestFormat->Channels != -1) { REPLACE_DATA(ConvertChannels(Data, &Format, RequestFormat, NumSamples)); Format.Channels = RequestFormat->Channels; } if (RequestFormat->Freq != Format.Freq && RequestFormat->Freq != -1) { REPLACE_DATA(ConvertFreq(Data, &Format, RequestFormat, NumSamples)); Format.Freq = RequestFormat->Freq; } } /***************************************************************************/ IMPLEMENT_IBASE(csSoundStreamRaw) IMPLEMENTS_INTERFACE(iSoundStream) IMPLEMENT_IBASE_END csSoundStreamRaw::csSoundStreamRaw(csSoundDataRaw *sd) { CONSTRUCT_IBASE(NULL); Data=sd; Data->IncRef(); Position=0; } csSoundStreamRaw::~csSoundStreamRaw() { Data->DecRef(); } const csSoundFormat *csSoundStreamRaw::GetFormat() { return &Data->Format; } bool csSoundStreamRaw::MayPrecache() { return true; } void csSoundStreamRaw::Restart() { Position=0; } void *csSoundStreamRaw::Read(long &Num) { // test if we should return as much data as possible if (Num == -1) Num = Data->NumSamples - Position; // decrease size of data if we reached the end of the sound if (Position + Num > Data->NumSamples) Num = Data->NumSamples-Position; // set up return data void *d; if (Data->Format.Bits==16) { d=(short*)Data->Data+Position*Data->Format.Channels; } else { d=(unsigned char *)Data->Data+Position*Data->Format.Channels; } Position+=Num; // the data buffer is like another reference to this stream IncRef(); return d; } void csSoundStreamRaw::DiscardBuffer(void *buf) { (void)buf; DecRef(); } <commit_msg>fixed a bug in the sound loader<commit_after>/* Copyright (C) 1998, 1999 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "soundraw.h" IMPLEMENT_IBASE(csSoundDataRaw); IMPLEMENTS_INTERFACE(iSoundData); IMPLEMENT_IBASE_END; csSoundDataRaw::csSoundDataRaw(iBase *iParent, void *d, long n, csSoundFormat f) { CONSTRUCT_IBASE(iParent); Data = d; NumSamples = n; Format = f; } csSoundDataRaw::~csSoundDataRaw() { unsigned char* const p = (unsigned char*)Data; delete[] p; } long csSoundDataRaw::GetNumSamples() { return NumSamples; } const csSoundFormat *csSoundDataRaw::GetFormat() { return &Format; } iSoundStream *csSoundDataRaw::CreateStream() { return new csSoundStreamRaw(this); } #define REPLACE_DATA(x) { \ unsigned char* const p = (unsigned char*)Data; \ Data = x; \ delete[] p; \ } void *ConvertBuffer8To16Bit(void *buf, unsigned long Num) { unsigned char *in=(unsigned char *)buf; short *out=new short[Num]; for (unsigned long i=0;i<Num;i++) { out[i]=((short)in[i]-128)*256; } return out; } void *ConvertBuffer16To8Bit(void *buf, unsigned long Num) { short *in=(short *)buf; unsigned char *out=new unsigned char[Num]; for (unsigned long i=0;i<Num;i++) { out[i]=(in[i]/256)+128; } return out; } #define CONVERT_CHANNELS_TYPE(Type) { \ Type *OldData=(Type*)d; \ if (newfmt->Channels==1) { \ Type *NewData=new Type[NumSamples]; \ for (long i=0;i<NumSamples;i++) { \ NewData[i]=(OldData[2*i]+OldData[2*i+1])/2; \ } \ return NewData; \ } else { \ Type *NewData=new Type[NumSamples*2]; \ for (long i=0;i<NumSamples;i++) { \ NewData[2*i]=NewData[2*i+1]=OldData[i]; \ } \ return NewData; \ } \ } void *ConvertChannels(void *d, const csSoundFormat *oldfmt, const csSoundFormat *newfmt, long NumSamples) { if (oldfmt->Bits == 8) { CONVERT_CHANNELS_TYPE(unsigned char); } else { CONVERT_CHANNELS_TYPE(short); } } // @@@ ConvertFreq() : quality loss! Need to use a filter. #define CONVERT_FREQ_TYPE(Type,Channels) { \ Type *NewData=new Type[NewNumSamples*Channels]; \ Type *OldData=(Type*)d; \ for (unsigned long i=0;i<NewNumSamples;i++) { \ int samppos = (int)(i/Factor); \ if (Channels==1) { \ NewData[i]=OldData[samppos]; \ } else { \ NewData[2*i]=OldData[2*samppos]; \ NewData[2*i+1]=OldData[2*samppos+1]; \ } \ } \ NumSamples = NewNumSamples; \ return NewData; \ } void *ConvertFreq(void *d, const csSoundFormat *oldfmt, const csSoundFormat *newfmt, long &NumSamples) { float Factor=newfmt->Freq/oldfmt->Freq; unsigned long NewNumSamples=(unsigned long)(NumSamples*Factor); if (oldfmt->Bits==16) { CONVERT_FREQ_TYPE(short,oldfmt->Channels); } else { CONVERT_FREQ_TYPE(unsigned char,oldfmt->Channels); } } void csSoundDataRaw::Convert(const csSoundFormat *RequestFormat) { if (Format.Bits==16 && RequestFormat->Bits==8) { REPLACE_DATA(ConvertBuffer16To8Bit(Data, NumSamples * Format.Channels)); Format.Bits = 8; } else if (Format.Bits==8 && RequestFormat->Bits==16) { REPLACE_DATA(ConvertBuffer8To16Bit(Data, NumSamples * Format.Channels)); Format.Bits = 16; } if (Format.Channels != RequestFormat->Channels && RequestFormat->Channels != -1) { REPLACE_DATA(ConvertChannels(Data, &Format, RequestFormat, NumSamples)); Format.Channels = RequestFormat->Channels; } if (RequestFormat->Freq != Format.Freq && RequestFormat->Freq != -1) { REPLACE_DATA(ConvertFreq(Data, &Format, RequestFormat, NumSamples)); Format.Freq = RequestFormat->Freq; } } /***************************************************************************/ IMPLEMENT_IBASE(csSoundStreamRaw) IMPLEMENTS_INTERFACE(iSoundStream) IMPLEMENT_IBASE_END csSoundStreamRaw::csSoundStreamRaw(csSoundDataRaw *sd) { CONSTRUCT_IBASE(NULL); Data=sd; Data->IncRef(); Position=0; } csSoundStreamRaw::~csSoundStreamRaw() { Data->DecRef(); } const csSoundFormat *csSoundStreamRaw::GetFormat() { return &Data->Format; } bool csSoundStreamRaw::MayPrecache() { return true; } void csSoundStreamRaw::Restart() { Position=0; } void *csSoundStreamRaw::Read(long &Num) { // test if we should return as much data as possible if (Num == -1) Num = Data->NumSamples - Position; // decrease size of data if we reached the end of the sound if (Position + Num > Data->NumSamples) Num = Data->NumSamples-Position; // set up return data void *d; if (Data->Format.Bits==16) { d=(short*)Data->Data+Position*Data->Format.Channels; } else { d=(unsigned char *)Data->Data+Position*Data->Format.Channels; } Position+=Num; // the data buffer is like another reference to this stream IncRef(); return d; } void csSoundStreamRaw::DiscardBuffer(void *buf) { (void)buf; DecRef(); } <|endoftext|>
<commit_before>#ifndef ORM_ATTR_HPP #define ORM_ATTR_HPP #include <ostream> #include <utility> #include <string> #include <ORM/fields/private/VAttr.hpp> namespace orm { class Query; /** * \brief Store a value ass database row **/ template<typename T> class Attr : public VAttr { public: /** * \brief Make a Attr * * \param value value to store * \param column Column in bdd **/ Attr(const T& value,const std::string& column); /** * \brief Make a Attr * * \param column Column in bdd **/ Attr(const std::string& column); Attr(const Attr&) = delete; typedef T type; ///< type of stored object T value; ///< value stored /** * \brief assignement operator * * \param v value to copy * * \return value **/ template<typename U> T& operator=(const U& v){value=v;modify=true;return value;}; /** * \brief assignement operator * * \param v value to copy * * \return *this **/ Attr<T>& operator=(const Attr<T>& v) {value=v.value;modify=true;return*this;}; /** * \brief addition operator * * \param v value to add * * \return value+v **/ template<typename U> auto operator+(const U& v) -> decltype(value+v) const {return value+v;}; /** * \brief sub operator * * \param v value to sub * * \return value-v **/ template<typename U> auto operator-(const U& v) -> decltype(value-v) const {return value-v;}; /** * \brief multiply operator * * \param v value to multiply by * * \return value*v **/ template<typename U> auto operator*(const U& v) -> decltype(value*v) const {return value*v;}; /** * \brief div operator * * \param v value to div by * * \return value/v **/ template<typename U> auto operator/(const U& v) -> decltype(value/v) const {return value/v;}; /** * \brief mod operator * * \param v value to mod by * * \return v%value **/ template<typename U> auto operator%(const U& v) -> decltype(value%v) const {return value%v;}; /** * \brief post increment operator * * \return *this **/ Attr<T>& operator++(){++value;modify=true;return *this;}; /** * \brief pre increment operator * * \return *this **/ Attr<T>& operator++(int){value++;modify=true;return*this;}; /** * \brief post deincrement operator * * \return *this **/ Attr<T>& operator--(){--value;modify=true;return*this;}; /** * \brief pre deincrement operator * * \return *this **/ Attr<T>& operator--(int){value--;modify=true;return*this;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value == v **/ template<typename U> auto operator==(const U& v) -> decltype(value==v) const {return value==v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value != v **/ template<typename U> auto operator!=(const U& v) -> decltype(value!=v) const {return value!=v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value > v **/ template<typename U> auto operator>(const U& v) -> decltype(value>v) const {return value>v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value < v **/ template<typename U> auto operator<(const U& v) -> decltype(value<v) const {return value<v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value >= v **/ template<typename U> auto operator>=(const U& v) -> decltype(value>=v) const {return value>=v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value <= v **/ template<typename U> auto operator<=(const U& v) -> decltype(value<=v) const {return value<=v;}; /** * \brief negation operator * * \return !value **/ bool operator!()const {return !value;}; /** * \brief addition operator * * \param v value to add * * \return *this **/ template<typename U> Attr<T>& operator+=(const U& v) {value+=v;modify=true;return*this;}; /** * \brief sub operator * * \param v value to sub * * \return *this **/ template<typename U> Attr<T>& operator-=(const U& v) {value-=v;modify=true;return*this;}; /** * \brief multiply operator * * \param v value to multiply * * \return *this **/ template<typename U> Attr<T>& operator*=(const U& v) {value*=v;modify=true;return*this;}; /** * \brief div operator * * \param v value to div * * \return *this **/ template<typename U> Attr<T>& operator/=(const U& v) {value/=v;modify=true;return*this;}; /** * \brief mod operator * * \param v value to mod * * \return *this **/ template<typename U> Attr<T>& operator%=(const U& v) {value%=v;modify=true;return*this;}; /** * \brief cast operator * * \cast this in value **/ //operator T() {return value;}; /** * \brief cast operator * * \cast this in value **/ operator T()const {return value;}; /** * \brief addition operator * * \param v value to add * * \return value+v.value **/ T operator+(const Attr<T>& v) const {return value+v.value;}; /** * \brief sub operator * * \param v value to sub * * \return value-v.value **/ T operator-(const Attr<T>& v) const {return value-v.value;}; /** * \brief multiply operator * * \param v value to multiply * * \return value*v.value **/ T operator*(const Attr<T>& v) const {return value*v.value;}; /** * \brief div operator * * \param v value to div * * \return value/v.value **/ T operator/(const Attr<T>& v) const {return value/v.value;}; /** * \brief mod operator * * \param v value to mod * * \return value%v.value **/ T operator%(const Attr<T>& v) const {return value%v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value == v.value **/ template<typename U> bool operator==(const Attr<U>& v)const {return value==v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value != v.value **/ template<typename U> bool operator!=(const Attr<U>& v)const {return value!=v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value > v.value **/ template<typename U> bool operator>(const Attr<U>& v)const {return value>v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value < v.value **/ template<typename U> bool operator<(const Attr<U>& v)const {return value<v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value >= v.value **/ template<typename U> bool operator>=(const Attr<U>& v)const {return value>=v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value <= v.value **/ template<typename U> bool operator<=(const Attr<U>& v)const {return value<=v.value;}; /** * \brief addition operator * * \param v value to add * * \return *this **/ template<typename U> Attr<T>& operator+=(const Attr<U>& v) {value+=v.value;modify=true;return*this;}; /** * \brief sub operator * * \param v value to sub * * \return *this **/ template<typename U> Attr<T>& operator-=(const Attr<U>& v) {value-=v.value;modify=true;return*this;}; /** * \brief multiply operator * * \param v value to multiply * * \return *this **/ template<typename U> Attr<T>& operator*=(const Attr<U>& v) {value*=v.value;modify=true;return*this;}; /** * \brief div operator * * \param v value to div * * \return *this **/ template<typename U> Attr<T>& operator/=(const Attr<U>& v) {value/=v.value;modify=true;return*this;}; /** * \brief mod operator * * \param v value to mod * * \return *this **/ template<typename U> Attr<T>& operator%=(const Attr<U>& v) {value%=v.value;modify=true;return*this;}; /** * \brief print the stored value * * \param output print in this stream * * \return output **/ virtual std::ostream& print_value(std::ostream& output)const; protected: /** * \brief print the stored value * * \param output print in this stream **/ virtual void print(std::ostream& output) const; /** * \brief Set the value in the query (use for dispatch * * \param query Query to set in * \param column culum number to set * * \return false if fail */ virtual bool set(Query& query,const unsigned int& column); /** * \brief Extracte the value from the query row * * \param query executed query * \param prefix column number to get * \param max_depth max depth of construction recurtion * * \return false if fail **/ virtual bool get(const Query& query,int& prefix,int max_depth); }; // define more common type using IntegerField = Attr<int>; using BooleanField = Attr<bool>; using PositiveIntegerField = Attr<unsigned int>; using BigIntegerField = Attr<long long int>; using FloatField = Attr<float>; using DoubleField = Attr<double>; using BigDoubleField = Attr<long double>; using TextField = Attr<std::string>; template<size_t max_length> using CharField = Attr<std::string>; /*template<bool auto_increment> using AutoField = Attr<int>;*/ }; #include <ORM/fields/Attr.tpl> #endif <commit_msg>add mysql type on attr to add<commit_after>#ifndef ORM_ATTR_HPP #define ORM_ATTR_HPP #include <ostream> #include <utility> #include <string> #include <ORM/fields/private/VAttr.hpp> namespace orm { class Query; /** * \brief Store a value ass database row **/ template<typename T> class Attr : public VAttr { public: /** * \brief Make a Attr * * \param value value to store * \param column Column in bdd **/ Attr(const T& value,const std::string& column); /** * \brief Make a Attr * * \param column Column in bdd **/ Attr(const std::string& column); Attr(const Attr&) = delete; typedef T type; ///< type of stored object T value; ///< value stored /** * \brief assignement operator * * \param v value to copy * * \return value **/ template<typename U> T& operator=(const U& v){value=v;modify=true;return value;}; /** * \brief assignement operator * * \param v value to copy * * \return *this **/ Attr<T>& operator=(const Attr<T>& v) {value=v.value;modify=true;return*this;}; /** * \brief addition operator * * \param v value to add * * \return value+v **/ template<typename U> auto operator+(const U& v) -> decltype(value+v) const {return value+v;}; /** * \brief sub operator * * \param v value to sub * * \return value-v **/ template<typename U> auto operator-(const U& v) -> decltype(value-v) const {return value-v;}; /** * \brief multiply operator * * \param v value to multiply by * * \return value*v **/ template<typename U> auto operator*(const U& v) -> decltype(value*v) const {return value*v;}; /** * \brief div operator * * \param v value to div by * * \return value/v **/ template<typename U> auto operator/(const U& v) -> decltype(value/v) const {return value/v;}; /** * \brief mod operator * * \param v value to mod by * * \return v%value **/ template<typename U> auto operator%(const U& v) -> decltype(value%v) const {return value%v;}; /** * \brief post increment operator * * \return *this **/ Attr<T>& operator++(){++value;modify=true;return *this;}; /** * \brief pre increment operator * * \return *this **/ Attr<T>& operator++(int){value++;modify=true;return*this;}; /** * \brief post deincrement operator * * \return *this **/ Attr<T>& operator--(){--value;modify=true;return*this;}; /** * \brief pre deincrement operator * * \return *this **/ Attr<T>& operator--(int){value--;modify=true;return*this;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value == v **/ template<typename U> auto operator==(const U& v) -> decltype(value==v) const {return value==v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value != v **/ template<typename U> auto operator!=(const U& v) -> decltype(value!=v) const {return value!=v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value > v **/ template<typename U> auto operator>(const U& v) -> decltype(value>v) const {return value>v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value < v **/ template<typename U> auto operator<(const U& v) -> decltype(value<v) const {return value<v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value >= v **/ template<typename U> auto operator>=(const U& v) -> decltype(value>=v) const {return value>=v;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value <= v **/ template<typename U> auto operator<=(const U& v) -> decltype(value<=v) const {return value<=v;}; /** * \brief negation operator * * \return !value **/ bool operator!()const {return !value;}; /** * \brief addition operator * * \param v value to add * * \return *this **/ template<typename U> Attr<T>& operator+=(const U& v) {value+=v;modify=true;return*this;}; /** * \brief sub operator * * \param v value to sub * * \return *this **/ template<typename U> Attr<T>& operator-=(const U& v) {value-=v;modify=true;return*this;}; /** * \brief multiply operator * * \param v value to multiply * * \return *this **/ template<typename U> Attr<T>& operator*=(const U& v) {value*=v;modify=true;return*this;}; /** * \brief div operator * * \param v value to div * * \return *this **/ template<typename U> Attr<T>& operator/=(const U& v) {value/=v;modify=true;return*this;}; /** * \brief mod operator * * \param v value to mod * * \return *this **/ template<typename U> Attr<T>& operator%=(const U& v) {value%=v;modify=true;return*this;}; /** * \brief cast operator * * \cast this in value **/ //operator T() {return value;}; /** * \brief cast operator * * \cast this in value **/ operator T()const {return value;}; /** * \brief addition operator * * \param v value to add * * \return value+v.value **/ T operator+(const Attr<T>& v) const {return value+v.value;}; /** * \brief sub operator * * \param v value to sub * * \return value-v.value **/ T operator-(const Attr<T>& v) const {return value-v.value;}; /** * \brief multiply operator * * \param v value to multiply * * \return value*v.value **/ T operator*(const Attr<T>& v) const {return value*v.value;}; /** * \brief div operator * * \param v value to div * * \return value/v.value **/ T operator/(const Attr<T>& v) const {return value/v.value;}; /** * \brief mod operator * * \param v value to mod * * \return value%v.value **/ T operator%(const Attr<T>& v) const {return value%v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value == v.value **/ template<typename U> bool operator==(const Attr<U>& v)const {return value==v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value != v.value **/ template<typename U> bool operator!=(const Attr<U>& v)const {return value!=v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value > v.value **/ template<typename U> bool operator>(const Attr<U>& v)const {return value>v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value < v.value **/ template<typename U> bool operator<(const Attr<U>& v)const {return value<v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value >= v.value **/ template<typename U> bool operator>=(const Attr<U>& v)const {return value>=v.value;}; /** * \brief Comparaison operator * * \param v value to compare with * * \return value <= v.value **/ template<typename U> bool operator<=(const Attr<U>& v)const {return value<=v.value;}; /** * \brief addition operator * * \param v value to add * * \return *this **/ template<typename U> Attr<T>& operator+=(const Attr<U>& v) {value+=v.value;modify=true;return*this;}; /** * \brief sub operator * * \param v value to sub * * \return *this **/ template<typename U> Attr<T>& operator-=(const Attr<U>& v) {value-=v.value;modify=true;return*this;}; /** * \brief multiply operator * * \param v value to multiply * * \return *this **/ template<typename U> Attr<T>& operator*=(const Attr<U>& v) {value*=v.value;modify=true;return*this;}; /** * \brief div operator * * \param v value to div * * \return *this **/ template<typename U> Attr<T>& operator/=(const Attr<U>& v) {value/=v.value;modify=true;return*this;}; /** * \brief mod operator * * \param v value to mod * * \return *this **/ template<typename U> Attr<T>& operator%=(const Attr<U>& v) {value%=v.value;modify=true;return*this;}; /** * \brief print the stored value * * \param output print in this stream * * \return output **/ virtual std::ostream& print_value(std::ostream& output)const; protected: /** * \brief print the stored value * * \param output print in this stream **/ virtual void print(std::ostream& output) const; /** * \brief Set the value in the query (use for dispatch * * \param query Query to set in * \param column culum number to set * * \return false if fail */ virtual bool set(Query& query,const unsigned int& column); /** * \brief Extracte the value from the query row * * \param query executed query * \param prefix column number to get * \param max_depth max depth of construction recurtion * * \return false if fail **/ virtual bool get(const Query& query,int& prefix,int max_depth); }; // define more common type using IntegerField = Attr<int>; using BooleanField = Attr<bool>; using PositiveIntegerField = Attr<unsigned int>; using BigIntegerField = Attr<long long int>; using FloatField = Attr<float>; using DoubleField = Attr<double>; using BigDoubleField = Attr<long double>; using TextField = Attr<std::string>; template<size_t max_length> using CharField = Attr<std::string>; /*template<bool auto_increment> using AutoField = Attr<int>;*/ /* TINYINT[(length)] [UNSIGNED] [ZEROFILL] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] | INT[(length)] [UNSIGNED] [ZEROFILL] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL] | NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL] | DATE | TIME | TIMESTAMP | DATETIME | CHAR(length) [BINARY | ASCII | UNICODE] | VARCHAR(length) [BINARY] | TINYBLOB | BLOB | MEDIUMBLOB | LONGBLOB | TINYTEXT | TEXT | spatial_type*/ }; #include <ORM/fields/Attr.tpl> #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: regactivex.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: mav $ $Date: 2004-05-27 14:47:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 ( 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor( s ): _______________________________________ * * ************************************************************************/ #define UNICODE #include <windows.h> #include <msiquery.h> #include <string.h> #include <malloc.h> #define CHART_COMPONENT 1 #define DRAW_COMPONENT 2 #define IMPRESS_COMPONENT 4 #define CALC_COMPONENT 8 #define WRITER_COMPONENT 16 typedef int ( __stdcall * DllNativeProc ) ( int, BOOL ); BOOL UnicodeEquals( wchar_t* pStr1, wchar_t* pStr2 ) { if ( pStr1 == NULL && pStr2 == NULL ) return TRUE; else if ( pStr1 == NULL || pStr2 == NULL ) return FALSE; while( *pStr1 == *pStr2 && *pStr1 && *pStr2 ) pStr1++, pStr2++; return ( *pStr1 == 0 && *pStr2 == 0 ); } //---------------------------------------------------------- char* UnicodeToAnsiString( wchar_t* pUniString ) { int len = WideCharToMultiByte( CP_ACP, 0, pUniString, -1, 0, 0, 0, 0 ); char* buff = reinterpret_cast<char*>( malloc( len ) ); WideCharToMultiByte( CP_ACP, 0, pUniString, -1, buff, len, 0, 0 ); return buff; } //---------------------------------------------------------- void RegisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser ) { HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) ) { DllNativeProc pNativeProc = ( DllNativeProc )GetProcAddress( hModule, "DllRegisterServerNative" ); if( pNativeProc!=NULL ) ( *pNativeProc )( nMode, InstallForAllUser ); FreeLibrary( hModule ); } } //---------------------------------------------------------- void UnregisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser ) { HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) ) { DllNativeProc pNativeProc = ( DllNativeProc )GetProcAddress( hModule, "DllUnregisterServerNative" ); if( pNativeProc!=NULL ) ( *pNativeProc )( nMode, InstallForAllUser ); FreeLibrary( hModule ); } } //---------------------------------------------------------- BOOL GetMsiProp( MSIHANDLE hMSI, const wchar_t* pPropName, wchar_t** ppValue ) { DWORD sz = 0; if ( MsiGetProperty( hMSI, pPropName, L"", &sz ) == ERROR_MORE_DATA ) { sz++; DWORD nbytes = sz * sizeof( wchar_t ); wchar_t* buff = reinterpret_cast<wchar_t*>( malloc( nbytes ) ); ZeroMemory( buff, nbytes ); MsiGetProperty( hMSI, pPropName, buff, &sz ); *ppValue = buff; return TRUE; } return FALSE; } //---------------------------------------------------------- BOOL GetActiveXControlPath( MSIHANDLE hMSI, char** ppActiveXPath ) { wchar_t* pProgPath = NULL; if ( GetMsiProp( hMSI, L"OfficeFolder", &pProgPath ) && pProgPath ) { char* pCharProgPath = UnicodeToAnsiString( pProgPath ); if ( pCharProgPath ) { int nLen = strlen( pCharProgPath ); *ppActiveXPath = reinterpret_cast<char*>( malloc( nLen + 23 ) ); strncpy( *ppActiveXPath, pCharProgPath, nLen ); strncpy( (*ppActiveXPath) + nLen, "program\\so_activex.dll", 22 ); (*ppActiveXPath)[nLen+22] = 0; free( pCharProgPath ); return TRUE; } free( pProgPath ); } return FALSE; } //---------------------------------------------------------- BOOL GetDelta( MSIHANDLE hMSI, int& nOldInstallMode, int& nInstallMode, int& nDeinstallMode ) { // for now the chart is always installed nOldInstallMode = CHART_COMPONENT; nInstallMode = CHART_COMPONENT; nDeinstallMode = 0; INSTALLSTATE current_state; INSTALLSTATE future_state; if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Wrt_Bin", &current_state, &future_state ) ) { // analyze writer installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= WRITER_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= WRITER_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= WRITER_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Calc_Bin", &current_state, &future_state ) ) { // analyze calc installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= CALC_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= CALC_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= CALC_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Draw_Bin", &current_state, &future_state ) ) { // analyze draw installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= DRAW_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= DRAW_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= DRAW_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Impress_Bin", &current_state, &future_state ) ) { // analyze impress installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= IMPRESS_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= IMPRESS_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= IMPRESS_COMPONENT; } else { // assert( FALSE ); } return TRUE; } //---------------------------------------------------------- BOOL MakeInstallForAllUsers( MSIHANDLE hMSI ) { BOOL bResult = FALSE; wchar_t* pVal = NULL; if ( GetMsiProp( hMSI, L"ALLUSERS", &pVal ) && pVal ) { bResult = UnicodeEquals( pVal , L"1" ); free( pVal ); } return bResult; } //---------------------------------------------------------- extern "C" UINT __stdcall InstallActiveXControl( MSIHANDLE hMSI ) { int nOldInstallMode = 0; int nInstallMode = 0; int nDeinstallMode = 0; // MessageBox(NULL, L"InstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION); INSTALLSTATE current_state; INSTALLSTATE future_state; if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", &current_state, &future_state ) ) { BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI ); char* pActiveXPath = NULL; if ( GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath && GetDelta( hMSI, nOldInstallMode, nInstallMode, nDeinstallMode ) ) { if ( future_state == INSTALLSTATE_LOCAL ) { // the control is installed in the new selected configuration if ( current_state == INSTALLSTATE_LOCAL && nDeinstallMode ) UnregisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser ); if ( nInstallMode ) RegisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser ); } else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) { if ( nOldInstallMode ) UnregisterActiveXNative( pActiveXPath, nOldInstallMode, bInstallForAllUser ); } } if ( pActiveXPath ) free( pActiveXPath ); } else { // assert( FALSE ); } return ERROR_SUCCESS; } //---------------------------------------------------------- extern "C" __stdcall UINT DeinstallActiveXControl( MSIHANDLE hMSI ) { INSTALLSTATE current_state; INSTALLSTATE future_state; // MessageBox(NULL, L"DeinstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION); if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", &current_state, &future_state ) ) { char* pActiveXPath = NULL; if ( current_state == INSTALLSTATE_LOCAL && GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath ) { BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI ); wchar_t* rm = NULL; if ( GetMsiProp( hMSI, L"REMOVE", &rm ) && rm && UnicodeEquals( rm, L"ALL" ) ) { UnregisterActiveXNative( pActiveXPath, CHART_COMPONENT | DRAW_COMPONENT | IMPRESS_COMPONENT | CALC_COMPONENT | WRITER_COMPONENT, bInstallForAllUser ); } if ( rm ) free( rm ); free( pActiveXPath ); } } return ERROR_SUCCESS; } <commit_msg>INTEGRATION: CWS customizer (1.4.14); FILE MERGED 2004/08/24 15:52:40 is 1.4.14.1: #i33203# INSTALLLOCATION instead of OfficeFolder<commit_after>/************************************************************************* * * $RCSfile: regactivex.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2004-09-08 15:03:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 ( 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor( s ): _______________________________________ * * ************************************************************************/ #define UNICODE #include <windows.h> #include <msiquery.h> #include <string.h> #include <malloc.h> #define CHART_COMPONENT 1 #define DRAW_COMPONENT 2 #define IMPRESS_COMPONENT 4 #define CALC_COMPONENT 8 #define WRITER_COMPONENT 16 typedef int ( __stdcall * DllNativeProc ) ( int, BOOL ); BOOL UnicodeEquals( wchar_t* pStr1, wchar_t* pStr2 ) { if ( pStr1 == NULL && pStr2 == NULL ) return TRUE; else if ( pStr1 == NULL || pStr2 == NULL ) return FALSE; while( *pStr1 == *pStr2 && *pStr1 && *pStr2 ) pStr1++, pStr2++; return ( *pStr1 == 0 && *pStr2 == 0 ); } //---------------------------------------------------------- char* UnicodeToAnsiString( wchar_t* pUniString ) { int len = WideCharToMultiByte( CP_ACP, 0, pUniString, -1, 0, 0, 0, 0 ); char* buff = reinterpret_cast<char*>( malloc( len ) ); WideCharToMultiByte( CP_ACP, 0, pUniString, -1, buff, len, 0, 0 ); return buff; } //---------------------------------------------------------- void RegisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser ) { HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) ) { DllNativeProc pNativeProc = ( DllNativeProc )GetProcAddress( hModule, "DllRegisterServerNative" ); if( pNativeProc!=NULL ) ( *pNativeProc )( nMode, InstallForAllUser ); FreeLibrary( hModule ); } } //---------------------------------------------------------- void UnregisterActiveXNative( const char* pActiveXPath, int nMode, BOOL InstallForAllUser ) { HINSTANCE hModule = LoadLibraryExA( pActiveXPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); if( !( hModule <= ( HINSTANCE )HINSTANCE_ERROR ) ) { DllNativeProc pNativeProc = ( DllNativeProc )GetProcAddress( hModule, "DllUnregisterServerNative" ); if( pNativeProc!=NULL ) ( *pNativeProc )( nMode, InstallForAllUser ); FreeLibrary( hModule ); } } //---------------------------------------------------------- BOOL GetMsiProp( MSIHANDLE hMSI, const wchar_t* pPropName, wchar_t** ppValue ) { DWORD sz = 0; if ( MsiGetProperty( hMSI, pPropName, L"", &sz ) == ERROR_MORE_DATA ) { sz++; DWORD nbytes = sz * sizeof( wchar_t ); wchar_t* buff = reinterpret_cast<wchar_t*>( malloc( nbytes ) ); ZeroMemory( buff, nbytes ); MsiGetProperty( hMSI, pPropName, buff, &sz ); *ppValue = buff; return TRUE; } return FALSE; } //---------------------------------------------------------- BOOL GetActiveXControlPath( MSIHANDLE hMSI, char** ppActiveXPath ) { wchar_t* pProgPath = NULL; if ( GetMsiProp( hMSI, L"INSTALLLOCATION", &pProgPath ) && pProgPath ) { char* pCharProgPath = UnicodeToAnsiString( pProgPath ); if ( pCharProgPath ) { int nLen = strlen( pCharProgPath ); *ppActiveXPath = reinterpret_cast<char*>( malloc( nLen + 23 ) ); strncpy( *ppActiveXPath, pCharProgPath, nLen ); strncpy( (*ppActiveXPath) + nLen, "program\\so_activex.dll", 22 ); (*ppActiveXPath)[nLen+22] = 0; free( pCharProgPath ); return TRUE; } free( pProgPath ); } return FALSE; } //---------------------------------------------------------- BOOL GetDelta( MSIHANDLE hMSI, int& nOldInstallMode, int& nInstallMode, int& nDeinstallMode ) { // for now the chart is always installed nOldInstallMode = CHART_COMPONENT; nInstallMode = CHART_COMPONENT; nDeinstallMode = 0; INSTALLSTATE current_state; INSTALLSTATE future_state; if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Wrt_Bin", &current_state, &future_state ) ) { // analyze writer installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= WRITER_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= WRITER_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= WRITER_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Calc_Bin", &current_state, &future_state ) ) { // analyze calc installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= CALC_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= CALC_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= CALC_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Draw_Bin", &current_state, &future_state ) ) { // analyze draw installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= DRAW_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= DRAW_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= DRAW_COMPONENT; } else { // assert( FALSE ); } if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_p_Impress_Bin", &current_state, &future_state ) ) { // analyze impress installation mode if ( current_state == INSTALLSTATE_LOCAL ) nOldInstallMode |= IMPRESS_COMPONENT; if ( future_state == INSTALLSTATE_LOCAL ) nInstallMode |= IMPRESS_COMPONENT; else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) nDeinstallMode |= IMPRESS_COMPONENT; } else { // assert( FALSE ); } return TRUE; } //---------------------------------------------------------- BOOL MakeInstallForAllUsers( MSIHANDLE hMSI ) { BOOL bResult = FALSE; wchar_t* pVal = NULL; if ( GetMsiProp( hMSI, L"ALLUSERS", &pVal ) && pVal ) { bResult = UnicodeEquals( pVal , L"1" ); free( pVal ); } return bResult; } //---------------------------------------------------------- extern "C" UINT __stdcall InstallActiveXControl( MSIHANDLE hMSI ) { int nOldInstallMode = 0; int nInstallMode = 0; int nDeinstallMode = 0; // MessageBox(NULL, L"InstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION); INSTALLSTATE current_state; INSTALLSTATE future_state; if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", &current_state, &future_state ) ) { BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI ); char* pActiveXPath = NULL; if ( GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath && GetDelta( hMSI, nOldInstallMode, nInstallMode, nDeinstallMode ) ) { if ( future_state == INSTALLSTATE_LOCAL ) { // the control is installed in the new selected configuration if ( current_state == INSTALLSTATE_LOCAL && nDeinstallMode ) UnregisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser ); if ( nInstallMode ) RegisterActiveXNative( pActiveXPath, nInstallMode, bInstallForAllUser ); } else if ( current_state == INSTALLSTATE_LOCAL && future_state == INSTALLSTATE_ABSENT ) { if ( nOldInstallMode ) UnregisterActiveXNative( pActiveXPath, nOldInstallMode, bInstallForAllUser ); } } if ( pActiveXPath ) free( pActiveXPath ); } else { // assert( FALSE ); } return ERROR_SUCCESS; } //---------------------------------------------------------- extern "C" __stdcall UINT DeinstallActiveXControl( MSIHANDLE hMSI ) { INSTALLSTATE current_state; INSTALLSTATE future_state; // MessageBox(NULL, L"DeinstallActiveXControl", L"Information", MB_OK | MB_ICONINFORMATION); if ( ERROR_SUCCESS == MsiGetFeatureState( hMSI, L"gm_o_Activexcontrol", &current_state, &future_state ) ) { char* pActiveXPath = NULL; if ( current_state == INSTALLSTATE_LOCAL && GetActiveXControlPath( hMSI, &pActiveXPath ) && pActiveXPath ) { BOOL bInstallForAllUser = MakeInstallForAllUsers( hMSI ); wchar_t* rm = NULL; if ( GetMsiProp( hMSI, L"REMOVE", &rm ) && rm && UnicodeEquals( rm, L"ALL" ) ) { UnregisterActiveXNative( pActiveXPath, CHART_COMPONENT | DRAW_COMPONENT | IMPRESS_COMPONENT | CALC_COMPONENT | WRITER_COMPONENT, bInstallForAllUser ); } if ( rm ) free( rm ); free( pActiveXPath ); } } return ERROR_SUCCESS; } <|endoftext|>
<commit_before>#include <vw/Plate/ToastDem.h> #include <vw/Plate/PlateManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Core.h> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> using namespace std; using namespace vw; using namespace vw::platefile; // There isn't much abstraction here. A Filter takes a platefile and writes a // new platefile. This rules out lazy filters for the moment. The // col/row/level/transaction_id is for the input value, the output can feel // free to write things elsewhere. // The function will be called for every input tile, including all transaction // ids. The output function should feel no obligation to write a tile for every // input. template <typename ImplT> struct FilterBase { inline ImplT& impl() { return static_cast<ImplT&>(*this); } inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().init(output, input, transaction_id); } inline void fini(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().fini(output, input, transaction_id); } # define lookup(name, type) type name(type data) const { return impl().name(data); } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { impl()(output, input, col, row, level, transaction_id); } }; struct Identity : public FilterBase<Identity> { # define lookup(name, type) type name(type data) const { return data; } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { ImageView<PixelRGBA<double> > tile; TileHeader hdr = input.read(tile, col, row, level, transaction_id); output.write_update(tile, col, row, level, transaction_id); } }; struct ToastDem : public FilterBase<ToastDem> { string mode(string) const { return "toast_dem"; } int tile_size(int) const { return 32; } string filetype(string) const { return "toast_dem_v1"; } PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; } ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { output.write_request(); // Write null tiles for the levels we don't have data for int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5; vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl; uint64 bytes; boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes); for (int level = 0; level < level_difference; ++level) { int region_size = 1 << level; for (int col = 0; col < region_size; ++col) for (int row = 0; row < region_size; ++row) output.write_update(null_tile, bytes, col, row, level, transaction_id); } } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } struct DemWriter : public ToastDemWriter { PlateFile& platefile; DemWriter(PlateFile& output) : platefile(output) { } inline void operator()(const boost::shared_array<uint8> data, uint64 data_size, int32 dem_col, int32 dem_row, int32 dem_level, int32 transaction_id) const { platefile.write_update(data, data_size, dem_col, dem_row, dem_level, transaction_id); } }; inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { DemWriter writer(output); make_toast_dem_tile(writer, input, col, row, level, transaction_id); } }; struct Options { string input_name; string output_name; string mode; string description; int tile_size; string filetype; PixelFormatEnum pixel_format; ChannelTypeEnum channel_type; int bottom_level; string filter; Options() : tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {} }; VW_DEFINE_EXCEPTION(Usage, Exception); void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description options("Options"); options.add_options() ("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.") ("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.") ("file-type", po::value(&opt.filetype), "Output file type") ("mode", po::value(&opt.mode), "Output mode [toast, kml]") ("tile-size", po::value(&opt.tile_size), "Output size, in pixels") ("filter", po::value(&opt.filter), "Filters to run") ("bottom-level", po::value(&opt.bottom_level), "Bottom level to process") ("help,h", "Display this help message."); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(options).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options ); } if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty()) vw_throw(Usage() << options); } template <typename FilterT> void run(Options& opt, FilterBase<FilterT>& filter) { PlateFile input(opt.input_name); // Use given option first, then use filter recommendation (it will probably // just recommend the value from the input platefile) if (opt.mode.empty()) opt.mode = filter.mode(input.index_header().type()); if (opt.tile_size == 0) opt.tile_size = filter.tile_size(input.default_tile_size()); if (opt.filetype.empty()) opt.filetype = filter.filetype(input.default_file_type()); if (opt.pixel_format == VW_PIXEL_UNKNOWN) opt.pixel_format = filter.pixel_format(input.pixel_format()); if (opt.channel_type == VW_CHANNEL_UNKNOWN) opt.channel_type = filter.channel_type(input.channel_type()); PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type); int transaction_id = output.transaction_request("plate2plate, reporting for duty", -1); filter.init(output, input, transaction_id); VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels"); int bottom_level = min(input.num_levels(), opt.bottom_level+1); for (int level = 0; level < bottom_level; ++level) { vw_out(InfoMessage) << "Processing level " << level << " of " << bottom_level-1 << std::endl; TerminalProgressCallback tpc("plate.plate2plate.progress", ""); vw::Timer timer( "Processing time in seconds" ); // The entire region contains 2^level tiles. int32 region_size = 1 << level; int subdivided_region_size = region_size / 32; if (subdivided_region_size < 1) subdivided_region_size = 1; double step = pow(subdivided_region_size/float(region_size),2.0); tpc.print_progress(); BBox2i full_region(0,0,region_size,region_size); std::list<BBox2i> boxes1 = bbox_tiles(full_region, subdivided_region_size, subdivided_region_size); BOOST_FOREACH( const BBox2i& region1, boxes1 ) { std::list<TileHeader> tiles = input.search_by_region(level, region1, 0, std::numeric_limits<int>::max(), 1); BOOST_FOREACH( const TileHeader& tile, tiles ) { filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); } tpc.report_incremental_progress(step); } // for (int32 i = 0; i < region_size; ++i) { // for (int32 j = 0; j < region_size; ++j) { // std::list<TileHeader> tiles; // try { // tiles = input.search_by_location(i, j, level, 0, std::numeric_limits<int>::max()); // } catch (const TileNotFoundErr&) { continue; } // BOOST_FOREACH(const TileHeader& tile, tiles) // filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); // tpc.report_incremental_progress(step); // } // } tpc.report_finished(); output.sync(); } filter.fini(output, input, transaction_id); output.transaction_complete(transaction_id, true); } // Blah blah boilerplate int main(int argc, char *argv[]) { Options opt; try { handle_arguments(argc, argv, opt); boost::to_lower(opt.filter); if (opt.filter == "identity") { Identity f; run(opt, f); } else if (opt.filter == "toast_dem") { ToastDem f; run(opt, f); } } catch (const Usage& e) { std::cout << e.what() << std::endl; return 1; } catch (const Exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } <commit_msg>Pow call was ambiguous<commit_after>#include <vw/Plate/ToastDem.h> #include <vw/Plate/PlateManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Core.h> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> using namespace std; using namespace vw; using namespace vw::platefile; // There isn't much abstraction here. A Filter takes a platefile and writes a // new platefile. This rules out lazy filters for the moment. The // col/row/level/transaction_id is for the input value, the output can feel // free to write things elsewhere. // The function will be called for every input tile, including all transaction // ids. The output function should feel no obligation to write a tile for every // input. template <typename ImplT> struct FilterBase { inline ImplT& impl() { return static_cast<ImplT&>(*this); } inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().init(output, input, transaction_id); } inline void fini(PlateFile& output, const PlateFile& input, int transaction_id) { return impl().fini(output, input, transaction_id); } # define lookup(name, type) type name(type data) const { return impl().name(data); } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { impl()(output, input, col, row, level, transaction_id); } }; struct Identity : public FilterBase<Identity> { # define lookup(name, type) type name(type data) const { return data; } lookup(mode, string); lookup(tile_size, int); lookup(filetype, string); lookup(pixel_format, PixelFormatEnum); lookup(channel_type, ChannelTypeEnum); # undef lookup inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { ImageView<PixelRGBA<double> > tile; TileHeader hdr = input.read(tile, col, row, level, transaction_id); output.write_update(tile, col, row, level, transaction_id); } }; struct ToastDem : public FilterBase<ToastDem> { string mode(string) const { return "toast_dem"; } int tile_size(int) const { return 32; } string filetype(string) const { return "toast_dem_v1"; } PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; } ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; } inline void init(PlateFile& output, const PlateFile& input, int transaction_id) { output.write_request(); // Write null tiles for the levels we don't have data for int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5; vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl; uint64 bytes; boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes); for (int level = 0; level < level_difference; ++level) { int region_size = 1 << level; for (int col = 0; col < region_size; ++col) for (int row = 0; row < region_size; ++row) output.write_update(null_tile, bytes, col, row, level, transaction_id); } } inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); } struct DemWriter : public ToastDemWriter { PlateFile& platefile; DemWriter(PlateFile& output) : platefile(output) { } inline void operator()(const boost::shared_array<uint8> data, uint64 data_size, int32 dem_col, int32 dem_row, int32 dem_level, int32 transaction_id) const { platefile.write_update(data, data_size, dem_col, dem_row, dem_level, transaction_id); } }; inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 transaction_id) { DemWriter writer(output); make_toast_dem_tile(writer, input, col, row, level, transaction_id); } }; struct Options { string input_name; string output_name; string mode; string description; int tile_size; string filetype; PixelFormatEnum pixel_format; ChannelTypeEnum channel_type; int bottom_level; string filter; Options() : tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {} }; VW_DEFINE_EXCEPTION(Usage, Exception); void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description options("Options"); options.add_options() ("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.") ("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.") ("file-type", po::value(&opt.filetype), "Output file type") ("mode", po::value(&opt.mode), "Output mode [toast, kml]") ("tile-size", po::value(&opt.tile_size), "Output size, in pixels") ("filter", po::value(&opt.filter), "Filters to run") ("bottom-level", po::value(&opt.bottom_level), "Bottom level to process") ("help,h", "Display this help message."); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(options).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options ); } if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty()) vw_throw(Usage() << options); } template <typename FilterT> void run(Options& opt, FilterBase<FilterT>& filter) { PlateFile input(opt.input_name); // Use given option first, then use filter recommendation (it will probably // just recommend the value from the input platefile) if (opt.mode.empty()) opt.mode = filter.mode(input.index_header().type()); if (opt.tile_size == 0) opt.tile_size = filter.tile_size(input.default_tile_size()); if (opt.filetype.empty()) opt.filetype = filter.filetype(input.default_file_type()); if (opt.pixel_format == VW_PIXEL_UNKNOWN) opt.pixel_format = filter.pixel_format(input.pixel_format()); if (opt.channel_type == VW_CHANNEL_UNKNOWN) opt.channel_type = filter.channel_type(input.channel_type()); PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type); int transaction_id = output.transaction_request("plate2plate, reporting for duty", -1); filter.init(output, input, transaction_id); VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels"); int bottom_level = min(input.num_levels(), opt.bottom_level+1); for (int level = 0; level < bottom_level; ++level) { vw_out(InfoMessage) << "Processing level " << level << " of " << bottom_level-1 << std::endl; TerminalProgressCallback tpc("plate.plate2plate.progress", ""); vw::Timer timer( "Processing time in seconds" ); // The entire region contains 2^level tiles. int32 region_size = 1 << level; int subdivided_region_size = region_size / 32; if (subdivided_region_size < 1) subdivided_region_size = 1; double step = pow(subdivided_region_size/double(region_size),2.0); tpc.print_progress(); BBox2i full_region(0,0,region_size,region_size); std::list<BBox2i> boxes1 = bbox_tiles(full_region, subdivided_region_size, subdivided_region_size); BOOST_FOREACH( const BBox2i& region1, boxes1 ) { std::list<TileHeader> tiles = input.search_by_region(level, region1, 0, std::numeric_limits<int>::max(), 1); BOOST_FOREACH( const TileHeader& tile, tiles ) { filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); } tpc.report_incremental_progress(step); } // for (int32 i = 0; i < region_size; ++i) { // for (int32 j = 0; j < region_size; ++j) { // std::list<TileHeader> tiles; // try { // tiles = input.search_by_location(i, j, level, 0, std::numeric_limits<int>::max()); // } catch (const TileNotFoundErr&) { continue; } // BOOST_FOREACH(const TileHeader& tile, tiles) // filter(output, input, tile.col(), tile.row(), tile.level(), transaction_id); // tpc.report_incremental_progress(step); // } // } tpc.report_finished(); output.sync(); } filter.fini(output, input, transaction_id); output.transaction_complete(transaction_id, true); } // Blah blah boilerplate int main(int argc, char *argv[]) { Options opt; try { handle_arguments(argc, argv, opt); boost::to_lower(opt.filter); if (opt.filter == "identity") { Identity f; run(opt, f); } else if (opt.filter == "toast_dem") { ToastDem f; run(opt, f); } } catch (const Usage& e) { std::cout << e.what() << std::endl; return 1; } catch (const Exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "UniformCompliance.inl" #include <sofa/defaulttype/VecTypes.h> #include <sofa/core/ObjectFactory.h> namespace sofa { namespace component { namespace forcefield { using namespace sofa::defaulttype; // Register in the Factory int UniformComplianceClass = core::RegisterObject("Uniform compliance") #ifndef SOFA_FLOAT .add< UniformCompliance< Vec1dTypes > >(true) .add< UniformCompliance< Vec3dTypes > >() .add< UniformCompliance< Vec6dTypes > >() #endif #ifndef SOFA_DOUBLE .add< UniformCompliance< Vec1fTypes > >() .add< UniformCompliance< Vec3fTypes > >() .add< UniformCompliance< Vec6fTypes > >() #endif ; SOFA_DECL_CLASS(UniformCompliance) #ifndef SOFA_FLOAT template class SOFA_Compliant_API UniformCompliance<Vec1dTypes>; template class SOFA_Compliant_API UniformCompliance<Vec3dTypes>; template class SOFA_Compliant_API UniformCompliance<Vec6dTypes>; #endif #ifndef SOFA_DOUBLE template class SOFA_Compliant_API UniformCompliance<Vec1fTypes>; template class SOFA_Compliant_API UniformCompliance<Vec3fTypes>; template class SOFA_Compliant_API UniformCompliance<Vec6fTypes>; #endif } } } <commit_msg>Compliant: compiling UniformCompliance for Vec2<commit_after>#include "UniformCompliance.inl" #include <sofa/defaulttype/VecTypes.h> #include <sofa/core/ObjectFactory.h> namespace sofa { namespace component { namespace forcefield { using namespace sofa::defaulttype; // Register in the Factory int UniformComplianceClass = core::RegisterObject("Uniform compliance") #ifndef SOFA_FLOAT .add< UniformCompliance< Vec1dTypes > >(true) .add< UniformCompliance< Vec2dTypes > >() .add< UniformCompliance< Vec3dTypes > >() .add< UniformCompliance< Vec6dTypes > >() #endif #ifndef SOFA_DOUBLE .add< UniformCompliance< Vec1fTypes > >() .add< UniformCompliance< Vec2fTypes > >() .add< UniformCompliance< Vec3fTypes > >() .add< UniformCompliance< Vec6fTypes > >() #endif ; SOFA_DECL_CLASS(UniformCompliance) #ifndef SOFA_FLOAT template class SOFA_Compliant_API UniformCompliance<Vec1dTypes>; template class SOFA_Compliant_API UniformCompliance<Vec2dTypes>; template class SOFA_Compliant_API UniformCompliance<Vec3dTypes>; template class SOFA_Compliant_API UniformCompliance<Vec6dTypes>; #endif #ifndef SOFA_DOUBLE template class SOFA_Compliant_API UniformCompliance<Vec1fTypes>; template class SOFA_Compliant_API UniformCompliance<Vec2fTypes>; template class SOFA_Compliant_API UniformCompliance<Vec3fTypes>; template class SOFA_Compliant_API UniformCompliance<Vec6fTypes>; #endif } } } <|endoftext|>
<commit_before>/* * fiberrenderer.cpp * * Created on: 28.12.2012 * @author Ralph Schurade */ #include "fiberrenderer.h" #include "fiberrendererthread.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/models.h" #include "../../data/datasets/fiberselector.h" #include "../../data/properties/propertygroup.h" #include <QtOpenGL/QGLShaderProgram> #include <QDebug> FiberRenderer::FiberRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData, int numPoints ) : ObjectRenderer(), m_selector( selector ), vbo( 0 ), dataVbo( 0 ), m_data( data ), m_extraData( extraData ), m_numLines( data->size() ), m_numPoints( numPoints ), m_isInitialized( false ) { m_colorField.resize( m_numLines ); } FiberRenderer::~FiberRenderer() { glDeleteBuffers( 1, &vbo ); glDeleteBuffers( 1, &dataVbo ); glDeleteBuffers( 1, &indexVbo ); } void FiberRenderer::init() { glGenBuffers( 1, &vbo ); glGenBuffers( 1, &dataVbo ); glGenBuffers( 1, &indexVbo ); } void FiberRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props ) { float alpha = props->get( Fn::Property::D_ALPHA ).toFloat(); if ( renderMode == 0 ) // picking { return; } else if ( renderMode == 1 ) // we are drawing opaque objects { if ( alpha < 1.0 ) { // obviously not opaque return; } } else // we are drawing tranparent objects { if ( !(alpha < 1.0 ) ) { // not transparent return; } } QGLShaderProgram* program = GLFunctions::getShader( "fiber" ); program->bind(); GLFunctions::setupTextures(); GLFunctions::setTextureUniforms( GLFunctions::getShader( "fiber" ), "maingl" ); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() ); initGeometry(); glBindBuffer( GL_ARRAY_BUFFER, vbo ); setShaderVars( props ); glBindBuffer( GL_ARRAY_BUFFER, dataVbo ); int extraLocation = program->attributeLocation( "a_extra" ); program->enableAttributeArray( extraLocation ); glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); glBindBuffer( GL_ARRAY_BUFFER, indexVbo ); int indexLocation = program->attributeLocation( "a_indexes" ); program->enableAttributeArray( indexLocation ); glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); program->setUniformValue( "C5", 13 ); program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() ); program->setUniformValue( "u_lighting", props->get( Fn::Property::D_LIGHT_SWITCH ).toBool() ); program->setUniformValue( "u_lightAmbient", props->get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() ); program->setUniformValue( "u_lightDiffuse", props->get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() ); program->setUniformValue( "u_materialAmbient", props->get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() ); program->setUniformValue( "u_materialDiffuse", props->get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() ); program->setUniformValue( "u_materialSpecular", props->get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() ); program->setUniformValue( "u_materialShininess", props->get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() ); glLineWidth( props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() ); QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_data->size(); ++i ) { if ( selected->at( i ) ) { program->setUniformValue( "u_color", m_colorField[i].redF(), m_colorField[i].greenF(), m_colorField[i].blueF(), 1.0 ); program->setUniformValue( "u_globalColor", m_globalColors[i].x(), m_globalColors[i].y(), m_globalColors[i].z(), 1.0 ); glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] ); } } glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void FiberRenderer::setupTextures() { } void FiberRenderer::setShaderVars( PropertyGroup* props ) { QGLShaderProgram* program = GLFunctions::getShader( "fiber" ); program->bind(); intptr_t offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int numFloats = 6; int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int normalLocation = program->attributeLocation( "a_normal" ); program->enableAttributeArray( normalLocation ); glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() ); program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() ); program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 ); program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() ); program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() ); program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_dx", props->get( Fn::Property::D_DX ).toFloat() ); program->setUniformValue( "u_dy", props->get( Fn::Property::D_DY ).toFloat() ); program->setUniformValue( "u_dz", props->get( Fn::Property::D_DZ ).toFloat() ); program->setUniformValue( "u_x", props->get( Fn::Property::D_NX ).toFloat() / 10.f ); program->setUniformValue( "u_y", props->get( Fn::Property::D_NY ).toFloat() / 10.f ); program->setUniformValue( "u_z", props->get( Fn::Property::D_NZ ).toFloat() / 10.f ); } void FiberRenderer::initGeometry() { if ( m_isInitialized ) { return; } qDebug() << "create fiber vbo's..."; std::vector<float>verts; try { verts.reserve( m_numPoints * 6 ); m_globalColors.reserve( m_numLines * 3 ); } catch ( std::bad_alloc& ) { qDebug() << "***error*** failed to allocate enough memory for vbo"; exit ( 0 ); } for ( int i = 0; i < m_data->size(); ++i ) { QVector<float> fib = m_data->at(i); if ( fib.size() < 6 ) { printf( "fib with size < 2 detected" ); continue; } int numFloats = fib.size(); QVector3D lineStart( fib[0], fib[1], fib[2] ); QVector3D lineEnd( fib[numFloats-3], fib[numFloats-2], fib[numFloats-1] ); QVector3D gc( fabs( lineStart.x() - lineEnd.x() ), fabs( lineStart.y() - lineEnd.y() ), fabs( lineStart.z() - lineEnd.z() ) ); gc.normalize(); m_globalColors.push_back( gc ); // push back the first vertex, done seperately because of nomal calculation verts.push_back( fib[0] ); verts.push_back( fib[1] ); verts.push_back( fib[2] ); QVector3D localColor( fabs( fib[0] - fib[3] ), fabs( fib[1] - fib[4] ), fabs( fib[2] - fib[5] ) ); localColor.normalize(); verts.push_back( localColor.x() ); verts.push_back( localColor.y() ); verts.push_back( localColor.z() ); for ( int k = 1; k < fib.size() / 3 - 1; ++k ) { verts.push_back( fib[k*3] ); verts.push_back( fib[k*3+1] ); verts.push_back( fib[k*3+2] ); QVector3D localColor( fabs( fib[k*3-3] - fib[k*3+3] ), fabs( fib[k*3-2] - fib[k*3+4] ), fabs( fib[k*3-1] - fib[k*3+5] ) ); localColor.normalize(); verts.push_back( localColor.x() ); verts.push_back( localColor.y() ); verts.push_back( localColor.z() ); } // push back the last vertex, done seperately because of nomal calculation verts.push_back( fib[numFloats-3] ); verts.push_back( fib[numFloats-2] ); verts.push_back( fib[numFloats-1] ); QVector3D localColor2( fabs( fib[numFloats-6] - fib[numFloats-3] ), fabs( fib[numFloats-5] - fib[numFloats-2] ), fabs( fib[numFloats-4] - fib[numFloats-1] ) ); localColor.normalize(); verts.push_back( localColor2.x() ); verts.push_back( localColor2.y() ); verts.push_back( localColor2.z() ); } glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); verts.clear(); //verts.squeeze(); m_pointsPerLine.resize( m_data->size() ); m_startIndexes.resize( m_data->size() ); int currentStart = 0; for ( int i = 0; i < m_data->size(); ++i ) { m_pointsPerLine[i] = m_data->at( i ).size() / 3; m_startIndexes[i] = currentStart; currentStart += m_pointsPerLine[i]; } updateExtraData( m_extraData ); qDebug() << "create fiber vbo's done"; m_numPoints = verts.size() / 6; m_isInitialized = true; } void FiberRenderer::colorChanged( QVariant color ) { QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_numLines; ++i ) { if ( selected->at( i ) ) { m_colorField.replace( i, color.value<QColor>() ); } } } void FiberRenderer::updateExtraData( QVector< QVector< float > >* extraData ) { m_extraData = extraData; QVector<float>data; QVector<float>indexes; for ( int i = 0; i < extraData->size(); ++i ) { QVector<float>fib = extraData->at(i); for ( int k = 0; k < fib.size(); ++k ) { data.push_back( fib[k] ); indexes.push_back( k ); } } glDeleteBuffers( 1, &dataVbo ); glGenBuffers( 1, &dataVbo ); glDeleteBuffers( 1, &indexVbo ); glGenBuffers( 1, &indexVbo ); glBindBuffer( GL_ARRAY_BUFFER, dataVbo ); glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, indexVbo ); glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } <commit_msg>added include for mac compile<commit_after>/* * fiberrenderer.cpp * * Created on: 28.12.2012 * @author Ralph Schurade */ #include "fiberrenderer.h" #include "fiberrendererthread.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/models.h" #include "../../data/datasets/fiberselector.h" #include "../../data/properties/propertygroup.h" #include <QtOpenGL/QGLShaderProgram> #include <QDebug> #include "math.h" FiberRenderer::FiberRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData, int numPoints ) : ObjectRenderer(), m_selector( selector ), vbo( 0 ), dataVbo( 0 ), m_data( data ), m_extraData( extraData ), m_numLines( data->size() ), m_numPoints( numPoints ), m_isInitialized( false ) { m_colorField.resize( m_numLines ); } FiberRenderer::~FiberRenderer() { glDeleteBuffers( 1, &vbo ); glDeleteBuffers( 1, &dataVbo ); glDeleteBuffers( 1, &indexVbo ); } void FiberRenderer::init() { glGenBuffers( 1, &vbo ); glGenBuffers( 1, &dataVbo ); glGenBuffers( 1, &indexVbo ); } void FiberRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props ) { float alpha = props->get( Fn::Property::D_ALPHA ).toFloat(); if ( renderMode == 0 ) // picking { return; } else if ( renderMode == 1 ) // we are drawing opaque objects { if ( alpha < 1.0 ) { // obviously not opaque return; } } else // we are drawing tranparent objects { if ( !(alpha < 1.0 ) ) { // not transparent return; } } QGLShaderProgram* program = GLFunctions::getShader( "fiber" ); program->bind(); GLFunctions::setupTextures(); GLFunctions::setTextureUniforms( GLFunctions::getShader( "fiber" ), "maingl" ); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() ); initGeometry(); glBindBuffer( GL_ARRAY_BUFFER, vbo ); setShaderVars( props ); glBindBuffer( GL_ARRAY_BUFFER, dataVbo ); int extraLocation = program->attributeLocation( "a_extra" ); program->enableAttributeArray( extraLocation ); glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); glBindBuffer( GL_ARRAY_BUFFER, indexVbo ); int indexLocation = program->attributeLocation( "a_indexes" ); program->enableAttributeArray( indexLocation ); glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); program->setUniformValue( "C5", 13 ); program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() ); program->setUniformValue( "u_lighting", props->get( Fn::Property::D_LIGHT_SWITCH ).toBool() ); program->setUniformValue( "u_lightAmbient", props->get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() ); program->setUniformValue( "u_lightDiffuse", props->get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() ); program->setUniformValue( "u_materialAmbient", props->get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() ); program->setUniformValue( "u_materialDiffuse", props->get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() ); program->setUniformValue( "u_materialSpecular", props->get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() ); program->setUniformValue( "u_materialShininess", props->get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() ); glLineWidth( props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() ); QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_data->size(); ++i ) { if ( selected->at( i ) ) { program->setUniformValue( "u_color", m_colorField[i].redF(), m_colorField[i].greenF(), m_colorField[i].blueF(), 1.0 ); program->setUniformValue( "u_globalColor", m_globalColors[i].x(), m_globalColors[i].y(), m_globalColors[i].z(), 1.0 ); glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] ); } } glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void FiberRenderer::setupTextures() { } void FiberRenderer::setShaderVars( PropertyGroup* props ) { QGLShaderProgram* program = GLFunctions::getShader( "fiber" ); program->bind(); intptr_t offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int numFloats = 6; int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int normalLocation = program->attributeLocation( "a_normal" ); program->enableAttributeArray( normalLocation ); glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() ); program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() ); program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 ); program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() ); program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() ); program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_dx", props->get( Fn::Property::D_DX ).toFloat() ); program->setUniformValue( "u_dy", props->get( Fn::Property::D_DY ).toFloat() ); program->setUniformValue( "u_dz", props->get( Fn::Property::D_DZ ).toFloat() ); program->setUniformValue( "u_x", props->get( Fn::Property::D_NX ).toFloat() / 10.f ); program->setUniformValue( "u_y", props->get( Fn::Property::D_NY ).toFloat() / 10.f ); program->setUniformValue( "u_z", props->get( Fn::Property::D_NZ ).toFloat() / 10.f ); } void FiberRenderer::initGeometry() { if ( m_isInitialized ) { return; } qDebug() << "create fiber vbo's..."; std::vector<float>verts; try { verts.reserve( m_numPoints * 6 ); m_globalColors.reserve( m_numLines * 3 ); } catch ( std::bad_alloc& ) { qDebug() << "***error*** failed to allocate enough memory for vbo"; exit ( 0 ); } for ( int i = 0; i < m_data->size(); ++i ) { QVector<float> fib = m_data->at(i); if ( fib.size() < 6 ) { printf( "fib with size < 2 detected" ); continue; } int numFloats = fib.size(); QVector3D lineStart( fib[0], fib[1], fib[2] ); QVector3D lineEnd( fib[numFloats-3], fib[numFloats-2], fib[numFloats-1] ); QVector3D gc( fabs( lineStart.x() - lineEnd.x() ), fabs( lineStart.y() - lineEnd.y() ), fabs( lineStart.z() - lineEnd.z() ) ); gc.normalize(); m_globalColors.push_back( gc ); // push back the first vertex, done seperately because of nomal calculation verts.push_back( fib[0] ); verts.push_back( fib[1] ); verts.push_back( fib[2] ); QVector3D localColor( fabs( fib[0] - fib[3] ), fabs( fib[1] - fib[4] ), fabs( fib[2] - fib[5] ) ); localColor.normalize(); verts.push_back( localColor.x() ); verts.push_back( localColor.y() ); verts.push_back( localColor.z() ); for ( int k = 1; k < fib.size() / 3 - 1; ++k ) { verts.push_back( fib[k*3] ); verts.push_back( fib[k*3+1] ); verts.push_back( fib[k*3+2] ); QVector3D localColor( fabs( fib[k*3-3] - fib[k*3+3] ), fabs( fib[k*3-2] - fib[k*3+4] ), fabs( fib[k*3-1] - fib[k*3+5] ) ); localColor.normalize(); verts.push_back( localColor.x() ); verts.push_back( localColor.y() ); verts.push_back( localColor.z() ); } // push back the last vertex, done seperately because of nomal calculation verts.push_back( fib[numFloats-3] ); verts.push_back( fib[numFloats-2] ); verts.push_back( fib[numFloats-1] ); QVector3D localColor2( fabs( fib[numFloats-6] - fib[numFloats-3] ), fabs( fib[numFloats-5] - fib[numFloats-2] ), fabs( fib[numFloats-4] - fib[numFloats-1] ) ); localColor.normalize(); verts.push_back( localColor2.x() ); verts.push_back( localColor2.y() ); verts.push_back( localColor2.z() ); } glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); verts.clear(); //verts.squeeze(); m_pointsPerLine.resize( m_data->size() ); m_startIndexes.resize( m_data->size() ); int currentStart = 0; for ( int i = 0; i < m_data->size(); ++i ) { m_pointsPerLine[i] = m_data->at( i ).size() / 3; m_startIndexes[i] = currentStart; currentStart += m_pointsPerLine[i]; } updateExtraData( m_extraData ); qDebug() << "create fiber vbo's done"; m_numPoints = verts.size() / 6; m_isInitialized = true; } void FiberRenderer::colorChanged( QVariant color ) { QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_numLines; ++i ) { if ( selected->at( i ) ) { m_colorField.replace( i, color.value<QColor>() ); } } } void FiberRenderer::updateExtraData( QVector< QVector< float > >* extraData ) { m_extraData = extraData; QVector<float>data; QVector<float>indexes; for ( int i = 0; i < extraData->size(); ++i ) { QVector<float>fib = extraData->at(i); for ( int k = 0; k < fib.size(); ++k ) { data.push_back( fib[k] ); indexes.push_back( k ); } } glDeleteBuffers( 1, &dataVbo ); glGenBuffers( 1, &dataVbo ); glDeleteBuffers( 1, &indexVbo ); glGenBuffers( 1, &indexVbo ); glBindBuffer( GL_ARRAY_BUFFER, dataVbo ); glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, indexVbo ); glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-25 21:27:40 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int Q; char c; ll a, b; ll A = 0; ll B = 0; ll cnt_l = 0; ll cnt_r = 0; ll lower = -1000000000000LL; priority_queue<ll> L; priority_queue<ll, vector<ll>, greater<ll>> R; void merge() { ll x = L.top(); ll y = R.top(); if (a <= x) { L.push(a); } else if (a >= y) { R.push(a); } else { L.push(a); } while (L.size() > R.size()) { ll t = L.top(); L.pop(); R.push(t); } while (L.size() < R.size()) { ll t = R.top(); R.pop(); L.push(t); } B += b; if (a < 0) { cnt_l++; A += abs(a); } else { cnt_r++; A += abs(a); } } void flush() { ll val = L.top(); ll ans = A + B; ll dist = abs(val); ll c = (abs(cnt_l - cnt_r) + 1) / 2; ans -= dist * c; cout << val << " " << ans << endl; } int main() { cin >> Q; L.push(-1000000000000LL); R.push(1000000000000LL); for (auto i = 0; i < Q; i++) { cin >> c; if (c == '1') { cin >> a >> b; merge(); } else { flush(); } } }<commit_msg>submit F.cpp to 'F - Absolute Minima' (abc127) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-25 21:27:40 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int Q; char c; ll a, b; ll A = 0; ll B = 0; ll cnt_l = 0; ll cnt_r = 0; ll lower = -1000000000000LL; priority_queue<ll> L; priority_queue<ll, vector<ll>, greater<ll>> R; void merge() { ll x = L.top(); ll y = R.top(); if (a <= x) { L.push(a); } else if (a >= y) { R.push(a); } else { L.push(a); } while (L.size() > R.size()) { ll t = L.top(); L.pop(); R.push(t); } while (L.size() < R.size()) { ll t = R.top(); R.pop(); L.push(t); } B += b; if (a < 0) { cnt_l++; A += abs(a); } else { cnt_r++; A += abs(a); } } void flush() { ll val = L.top(); ll ans = A + B; ll dist = abs(val); ll c = abs(cnt_l - cnt_r); ans -= dist * c; cout << val << " " << ans << endl; } int main() { cin >> Q; L.push(-1000000000000LL); R.push(1000000000000LL); for (auto i = 0; i < Q; i++) { cin >> c; if (c == '1') { cin >> a >> b; merge(); } else { flush(); } } }<|endoftext|>
<commit_before>#include <convert.hpp> #include <errors.hpp> #include <debug.hpp> #include <ingridientWindow.hpp> #include "ui_ingridientWindow.h" IngridientWindow::IngridientWindow(QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()} { setupMeasureList(); ui->lineEdit_2->setDisabled(true); PRINT_OBJ("IngridientWindow created"); } IngridientWindow::IngridientWindow(Item* item, QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()}, editMode {true}, editedItem {item} { setupMeasureList(); applyItemStats(item); this->setWindowTitle("Edit item"); PRINT_OBJ("Existed item edit window created"); } IngridientWindow::IngridientWindow(Food* food, QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()}, editMode {true}, editedItem {food} { setupMeasureList(); applyFoodStats(food); this->setWindowTitle("Edit food"); PRINT_OBJ("Existed food edit window created"); } IngridientWindow::~IngridientWindow() { delete ui; PRINT_OBJ("IngridientWindow destroyed"); } void IngridientWindow::on_buttonBox_1_accepted() { if ( editMode ) { if ( ui->radioButton_1->isChecked() ) { editFood(dynamic_cast<Food*>(editedItem)); } else if ( ui->radioButton_2->isChecked() ) { editItem(editedItem); } } else { if ( ui->radioButton_1->isChecked() ) { emit foodObjectReady(createNewFood()); } else if ( ui->radioButton_2->isChecked() ) { emit itemObjectReady(createNewItem()); } } this->hide(); PRINT_DEBUG("New item/food accepted"); } void IngridientWindow::on_buttonBox_1_rejected() { this->hide(); PRINT_DEBUG("New item/food rejected"); } void IngridientWindow::setupMeasureList(void) { const std::string* names = Item::getItemMeasureTypeNamesList(); ui->setupUi(this); for ( int i = 0; !names[i].empty(); i++ ) { measureList.append(QString::fromStdString(names[i])); } ui->comboBox_1->addItems(measureList); } void IngridientWindow::applyItemStats(Item* item) { ui->lineEdit_1->setText(QString::fromStdString(item->getName())); ui->lineEdit_1->setDisabled(true); ui->comboBox_1->setCurrentIndex(static_cast<int>(item->getUnitType())); if ( item->getUnitType() != Item::KGRAM ) { ui->lineEdit_2->setText(massToQString(item->getMass())); } else { ui->lineEdit_2->setDisabled(true); } ui->lineEdit_4->setText(priceToQString(item->getPrice())); on_radioButton_2_clicked(); ui->radioButton_2->setChecked(true); ui->radioButton_1->setDisabled(true); PRINT_DEBUG("All items stats are applied"); } void IngridientWindow::applyFoodStats(Food* food) { ui->lineEdit_1->setText(QString::fromStdString(food->getName())); ui->lineEdit_1->setDisabled(true); ui->comboBox_1->setCurrentIndex(static_cast<int>(food->getUnitType())); if ( food->getUnitType() != Item::KGRAM ) { ui->lineEdit_2->setText(massToQString(food->getMass())); } else { ui->lineEdit_2->setDisabled(true); } ui->lineEdit_4->setText(priceToQString(food->getPrice())); ui->lineEdit_3->setText(fatsToQString(food->getFats())); ui->lineEdit_5->setText(proteinsToQString(food->getProteins())); ui->lineEdit_6->setText(carbohydratesToQString(food->getCarbohydrates())); ui->lineEdit_7->setText(caloriesToQString(food->getCalories())); ui->radioButton_1->setChecked(true); ui->radioButton_2->setDisabled(true); PRINT_DEBUG("All food stats are applied"); } Item* IngridientWindow::createNewItem(void) { PRINT_DEBUG("Creating new item"); QString name = ui->lineEdit_1->text(); QString mass = ui->lineEdit_2->text(); QString price = ui->lineEdit_4->text(); if ( name.isEmpty() ) { PRINT_ERR("Ingridient name could not be empty"); throw EmptyIngridientNameException(); } if ( mass.isEmpty() ) { PRINT_ERR("Ingridient mass could not be empty"); throw EmptyIngridientMassException(); } if ( price.isEmpty() ) { PRINT_ERR("Ingridient price could not be empty"); throw EmptyIngridientPriceException(); } return new Item(name.toStdString(), (!ui->comboBox_1->currentText().toStdString().compare("kg") ? 1 : QStringToMass(mass)), QStringToPrice(price), static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex())); } Food* IngridientWindow::createNewFood(void) { bool isKg = !ui->comboBox_1->currentText().toStdString().compare("kg"); PRINT_DEBUG("Creating new food"); QString name = ui->lineEdit_1->text(); QString mass = ui->lineEdit_2->text(); QString price = ui->lineEdit_4->text(); QString fats = ui->lineEdit_3->text(); QString proteins = ui->lineEdit_5->text(); QString carbohydrates = ui->lineEdit_6->text(); QString calories = ui->lineEdit_7->text(); if ( name.isEmpty() ) { PRINT_ERR("Food name could not be empty"); throw EmptyIngridientNameException(); } if ( mass.isEmpty() && !isKg ) { PRINT_ERR("Food mass could not be empty"); throw EmptyIngridientMassException(); } if ( price.isEmpty() ) { PRINT_ERR("Food price could not be empty"); throw EmptyIngridientPriceException(); } if ( fats.isEmpty() ) { PRINT_ERR("Food fats could not be empty"); throw EmptyIngridientFatsException(); } if ( proteins.isEmpty() ) { PRINT_ERR("Food proteins could not be empty"); throw EmptyIngridientProteinsException(); } if ( carbohydrates.isEmpty() ) { PRINT_ERR("Food carbohydrates could not be empty"); throw EmptyIngridientCarbohydratesException(); } if ( calories.isEmpty() ) { PRINT_ERR("Food calories could not be empty"); throw EmptyIngridientCaloriesException(); } return new Food(name.toStdString(), isKg ? 1 : QStringToMass(mass), QStringToPrice(price), static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex()), QStringToFats(fats), QStringToProteins(proteins), QStringToCarbohydrates(carbohydrates), QStringToCalories(calories)); } void IngridientWindow::editItem(Item* item) { PRINT_DEBUG("Editing item"); if ( !ui->comboBox_1->currentText().toStdString().compare("kg") ) { item->setItemMass(1); } else { item->setItemMass(ui->lineEdit_2->text().toLong()); } item->setItemPrice(ui->lineEdit_4->text().toLong()); item->setItemUnitType(static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex())); } void IngridientWindow::editFood(Food* food) { PRINT_DEBUG("Editing food"); editItem(food); food->setItemFats(ui->lineEdit_3->text().toLong()); food->setItemProteins(ui->lineEdit_5->text().toLong()); food->setItemCarbohydrates(ui->lineEdit_6->text().toLong()); food->setItemCalories(ui->lineEdit_7->text().toLong()); } void IngridientWindow::on_radioButton_1_clicked() { ui->lineEdit_3->setDisabled(false); ui->lineEdit_5->setDisabled(false); ui->lineEdit_6->setDisabled(false); ui->lineEdit_7->setDisabled(false); } void IngridientWindow::on_radioButton_2_clicked() { ui->lineEdit_3->setDisabled(true); ui->lineEdit_5->setDisabled(true); ui->lineEdit_6->setDisabled(true); ui->lineEdit_7->setDisabled(true); } void IngridientWindow::on_comboBox_1_currentIndexChanged(const QString& arg1) { if ( !arg1.toStdString().compare("kg") ) { ui->lineEdit_2->setDisabled(true); } else { ui->lineEdit_2->setDisabled(false); } PRINT_DEBUG(arg1.toStdString() << " selected"); } <commit_msg>ingridientWindow: Use convert functions for values<commit_after>#include <convert.hpp> #include <errors.hpp> #include <debug.hpp> #include <ingridientWindow.hpp> #include "ui_ingridientWindow.h" IngridientWindow::IngridientWindow(QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()} { setupMeasureList(); ui->lineEdit_2->setDisabled(true); PRINT_OBJ("IngridientWindow created"); } IngridientWindow::IngridientWindow(Item* item, QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()}, editMode {true}, editedItem {item} { setupMeasureList(); applyItemStats(item); this->setWindowTitle("Edit item"); PRINT_OBJ("Existed item edit window created"); } IngridientWindow::IngridientWindow(Food* food, QWidget* parent) : QDialog {parent}, ui {new Ui::IngridientWindow}, measureList {QStringList()}, editMode {true}, editedItem {food} { setupMeasureList(); applyFoodStats(food); this->setWindowTitle("Edit food"); PRINT_OBJ("Existed food edit window created"); } IngridientWindow::~IngridientWindow() { delete ui; PRINT_OBJ("IngridientWindow destroyed"); } void IngridientWindow::on_buttonBox_1_accepted() { if ( editMode ) { if ( ui->radioButton_1->isChecked() ) { editFood(dynamic_cast<Food*>(editedItem)); } else if ( ui->radioButton_2->isChecked() ) { editItem(editedItem); } } else { if ( ui->radioButton_1->isChecked() ) { emit foodObjectReady(createNewFood()); } else if ( ui->radioButton_2->isChecked() ) { emit itemObjectReady(createNewItem()); } } this->hide(); PRINT_DEBUG("New item/food accepted"); } void IngridientWindow::on_buttonBox_1_rejected() { this->hide(); PRINT_DEBUG("New item/food rejected"); } void IngridientWindow::setupMeasureList(void) { const std::string* names = Item::getItemMeasureTypeNamesList(); ui->setupUi(this); for ( int i = 0; !names[i].empty(); i++ ) { measureList.append(QString::fromStdString(names[i])); } ui->comboBox_1->addItems(measureList); } void IngridientWindow::applyItemStats(Item* item) { ui->lineEdit_1->setText(QString::fromStdString(item->getName())); ui->lineEdit_1->setDisabled(true); ui->comboBox_1->setCurrentIndex(static_cast<int>(item->getUnitType())); if ( item->getUnitType() != Item::KGRAM ) { ui->lineEdit_2->setText(massToQString(item->getMass())); } else { ui->lineEdit_2->setDisabled(true); } ui->lineEdit_4->setText(priceToQString(item->getPrice())); on_radioButton_2_clicked(); ui->radioButton_2->setChecked(true); ui->radioButton_1->setDisabled(true); PRINT_DEBUG("All items stats are applied"); } void IngridientWindow::applyFoodStats(Food* food) { ui->lineEdit_1->setText(QString::fromStdString(food->getName())); ui->lineEdit_1->setDisabled(true); ui->comboBox_1->setCurrentIndex(static_cast<int>(food->getUnitType())); if ( food->getUnitType() != Item::KGRAM ) { ui->lineEdit_2->setText(massToQString(food->getMass())); } else { ui->lineEdit_2->setDisabled(true); } ui->lineEdit_4->setText(priceToQString(food->getPrice())); ui->lineEdit_3->setText(fatsToQString(food->getFats())); ui->lineEdit_5->setText(proteinsToQString(food->getProteins())); ui->lineEdit_6->setText(carbohydratesToQString(food->getCarbohydrates())); ui->lineEdit_7->setText(caloriesToQString(food->getCalories())); ui->radioButton_1->setChecked(true); ui->radioButton_2->setDisabled(true); PRINT_DEBUG("All food stats are applied"); } Item* IngridientWindow::createNewItem(void) { PRINT_DEBUG("Creating new item"); QString name = ui->lineEdit_1->text(); QString mass = ui->lineEdit_2->text(); QString price = ui->lineEdit_4->text(); if ( name.isEmpty() ) { PRINT_ERR("Ingridient name could not be empty"); throw EmptyIngridientNameException(); } if ( mass.isEmpty() ) { PRINT_ERR("Ingridient mass could not be empty"); throw EmptyIngridientMassException(); } if ( price.isEmpty() ) { PRINT_ERR("Ingridient price could not be empty"); throw EmptyIngridientPriceException(); } return new Item(name.toStdString(), (!ui->comboBox_1->currentText().toStdString().compare("kg") ? 1 : QStringToMass(mass)), QStringToPrice(price), static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex())); } Food* IngridientWindow::createNewFood(void) { bool isKg = !ui->comboBox_1->currentText().toStdString().compare("kg"); PRINT_DEBUG("Creating new food"); QString name = ui->lineEdit_1->text(); QString mass = ui->lineEdit_2->text(); QString price = ui->lineEdit_4->text(); QString fats = ui->lineEdit_3->text(); QString proteins = ui->lineEdit_5->text(); QString carbohydrates = ui->lineEdit_6->text(); QString calories = ui->lineEdit_7->text(); if ( name.isEmpty() ) { PRINT_ERR("Food name could not be empty"); throw EmptyIngridientNameException(); } if ( mass.isEmpty() && !isKg ) { PRINT_ERR("Food mass could not be empty"); throw EmptyIngridientMassException(); } if ( price.isEmpty() ) { PRINT_ERR("Food price could not be empty"); throw EmptyIngridientPriceException(); } if ( fats.isEmpty() ) { PRINT_ERR("Food fats could not be empty"); throw EmptyIngridientFatsException(); } if ( proteins.isEmpty() ) { PRINT_ERR("Food proteins could not be empty"); throw EmptyIngridientProteinsException(); } if ( carbohydrates.isEmpty() ) { PRINT_ERR("Food carbohydrates could not be empty"); throw EmptyIngridientCarbohydratesException(); } if ( calories.isEmpty() ) { PRINT_ERR("Food calories could not be empty"); throw EmptyIngridientCaloriesException(); } return new Food(name.toStdString(), isKg ? 1 : QStringToMass(mass), QStringToPrice(price), static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex()), QStringToFats(fats), QStringToProteins(proteins), QStringToCarbohydrates(carbohydrates), QStringToCalories(calories)); } void IngridientWindow::editItem(Item* item) { PRINT_DEBUG("Editing item"); if ( !ui->comboBox_1->currentText().toStdString().compare("kg") ) { item->setItemMass(1); } else { item->setItemMass(QStringToMass(ui->lineEdit_2->text())); } item->setItemPrice(QStringToPrice(ui->lineEdit_4->text())); item->setItemUnitType(static_cast<Item::MeasureType>(ui->comboBox_1->currentIndex())); } void IngridientWindow::editFood(Food* food) { PRINT_DEBUG("Editing food"); editItem(food); food->setItemFats(QStringToFats(ui->lineEdit_3->text())); food->setItemProteins(QStringToProteins(ui->lineEdit_5->text())); food->setItemCarbohydrates(QStringToCarbohydrates(ui->lineEdit_6->text())); food->setItemCalories(QStringToCalories(ui->lineEdit_7->text())); } void IngridientWindow::on_radioButton_1_clicked() { ui->lineEdit_3->setDisabled(false); ui->lineEdit_5->setDisabled(false); ui->lineEdit_6->setDisabled(false); ui->lineEdit_7->setDisabled(false); } void IngridientWindow::on_radioButton_2_clicked() { ui->lineEdit_3->setDisabled(true); ui->lineEdit_5->setDisabled(true); ui->lineEdit_6->setDisabled(true); ui->lineEdit_7->setDisabled(true); } void IngridientWindow::on_comboBox_1_currentIndexChanged(const QString& arg1) { if ( !arg1.toStdString().compare("kg") ) { ui->lineEdit_2->setDisabled(true); } else { ui->lineEdit_2->setDisabled(false); } PRINT_DEBUG(arg1.toStdString() << " selected"); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019-5-26 21:31:42 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, Q; ll S[200010], T[200010], X[200010]; ll D[200010]; int ans[200010]; typedef tuple<ll, ll, ll, int> K; vector<K> KK; typedef tuple<ll, int, int> info; priority_queue<info, vector<info>, greater<info>> P; int main() { cin >> N >> Q; for (auto i = 0; i < N; i++) { cin >> S[i] >> T[i] >> X[i]; KK.push_back(K(X[i], S[i], T[i], i)); } sort(KK.begin(), KK.end()); for (auto i = 0; i < Q; i++) { cin >> D[i]; } for (auto i = 0; i < N; i++) { ll x = get<0>(KK[i]); ll s = get<1>(KK[i]); ll t = get<2>(KK[i]); int ind = get<3>(KK[i]); P.push(info(s - x, ind, 0)); P.push(info(t - x, ind, 1)); } int ind = 0; set<int> S; fill(ans, ans + Q, -1); while (!P.empty()) { info x = P.top(); P.pop(); ll next_t = get<0>(x); int point = get<1>(x); bool start = (get<2>(x) == 0); if (next_t <= D[ind]) { if (start) { S.insert(point); } else { S.erase(S.find(point)); } continue; } else { while (next_t > D[ind]) { int a = -1; if (S.empty()) { a = -1; } else { a = *S.begin(); } ans[ind] = a; ind++; if (ind == Q) { goto EXIT; } } if (start) { S.insert(point); } else { S.erase(S.find(point)); } } } EXIT: for (auto i = 0; i < Q; i++) { if (ans[i] == -1) { cout << -1 << endl; } else { cout << X[ans[i]] << endl; } } }<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2019-5-26 21:31:42 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, Q; ll S[200010], T[200010], X[200010]; ll D[200010]; int ans[200010]; typedef tuple<ll, ll, ll, int> K; vector<K> KK; typedef tuple<ll, int, int> info; priority_queue<info, vector<info>, greater<info>> P; int main() { cin >> N >> Q; for (auto i = 0; i < N; i++) { cin >> S[i] >> T[i] >> X[i]; KK.push_back(K(X[i], S[i], T[i], i)); } sort(KK.begin(), KK.end()); for (auto i = 0; i < Q; i++) { cin >> D[i]; } for (auto i = 0; i < N; i++) { ll x = get<0>(KK[i]); ll s = get<1>(KK[i]); ll t = get<2>(KK[i]); int ind = get<3>(KK[i]); P.push(info(s - x, ind, 0)); P.push(info(t - x, ind, 1)); } int ind = 0; set<int> S; fill(ans, ans + Q, -1); while (!P.empty()) { info x = P.top(); P.pop(); ll next_t = get<0>(x); int point = get<1>(x); bool start = (get<2>(x) == 0); while (next_t > D[ind]) { int a = -1; if (S.empty()) { a = -1; } else { a = *S.begin(); } ans[ind] = a; ind++; if (ind == Q) { goto EXIT; } } if (start) { S.insert(point); } else { S.erase(S.find(point)); } } EXIT: for (auto i = 0; i < Q; i++) { if (ans[i] == -1) { cout << -1 << endl; } else { cout << X[ans[i]] << endl; } } }<|endoftext|>