hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ccef907f0b16ea546b61a842b2c637ee439a8238
330
hpp
C++
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
#include "utilities.hpp" #include "Food.hpp" class Order { public: std::vector<Product> products; int orderDay; int orderMonth; int orderYear; int totalProducts; double totalPrice; Order(int orderDay, int orderMonth, int orderYear); Order(); void computeBill(); void printOrders(); };
18.333333
55
0.657576
Xhiel23
cceff5123fabb181d9c79012b5fa5807b59a5277
32,087
cpp
C++
src/reco/wordrec/common/LTKRecognitionContext.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
src/reco/wordrec/common/LTKRecognitionContext.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
src/reco/wordrec/common/LTKRecognitionContext.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
/***************************************************************************************** * Copyright (c) 2006 Hewlett-Packard Development Company, L.P. * 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. *****************************************************************************************/ /************************************************************************ * SVN MACROS * * $LastChangedDate$ * $Revision$ * $Author$ * ************************************************************************/ /************************************************************************ * FILE DESCR: Implementation of LTKRecognitionContext that holds the context * for recognition * * CONTENTS: * addTrace * addTraceGroup * beginRecoUnit * endRecoUnit * getAllInk * getConfidThreshold * getDeviceContext * getFlag * getLanguageModel * getNextBestResults * getNumResults * getScreenContext * getTopResult * setConfidThreshold * setDeviceContext * setFlag * setLanguageModel * setNumResults * setScreenContext * addRecognitionResult * recognize * reset * * AUTHOR: Deepu V. * * DATE: February 22, 2005 * CHANGE HISTORY: * Author Date Description of change * Thanigai 3-AUG-2005 Added default constructor and setWordRecoEngine * methods. * * Deepu 30-AUG-2005 Replaced LTKWordRecoEngine with LTKWordRecognizer * Changed the representation of m_recognitionFlags * since there was a problem with dlls ************************************************************************/ #include "LTKRecognitionContext.h" #include "LTKMacros.h" #include "LTKErrors.h" #include "LTKTrace.h" #include "LTKErrorsList.h" #include "LTKTraceGroup.h" #include "LTKWordRecoResult.h" #include "LTKWordRecognizer.h" #include "LTKLoggerUtil.h" #include "LTKException.h" /********************************************************************************** * AUTHOR : Thanigai * DATE : 3-AUG-2005 * NAME : LTKRecognitionContext * DESCRIPTION : Default constructor * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ LTKRecognitionContext::LTKRecognitionContext() :m_confidThreshold(0), m_numResults(0), m_nextBestResultIndex(0), m_wordRecPtr(NULL) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::LTKRecognitionContext()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::LTKRecognitionContext()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 22-FEB-2005 * NAME : LTKRecognitionContext * DESCRIPTION : Initialization constructor * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer *wordRecPtr ) :m_wordRecPtr(wordRecPtr), m_confidThreshold(0), m_numResults(0), m_nextBestResultIndex(0) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" << endl; if(m_wordRecPtr == NULL) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER) <<" LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" <<endl; throw LTKException(ENULL_POINTER); } m_recognitionFlags.clear(); m_wordRecPtr = wordRecPtr; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" << endl; } /********************************************************************************** * AUTHOR : Thanigai * DATE : 3-AUG-2005 * NAME : setWordRecoEngine * DESCRIPTION : Accepts the handle to word recognition engine and store it locally * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::setWordRecoEngine(LTKWordRecognizer *wordRecPtr) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setWordRecoEngine()" << endl; if(wordRecPtr == NULL) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER) <<" LTKRecognitionContext::setWordRecoEngine()" <<endl; LTKReturnError(ENULL_POINTER); } m_wordRecPtr = wordRecPtr; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setWordRecoEngine()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 22-FEB-2005 * NAME : addTrace * DESCRIPTION : This function adds a trace to the recognition context for * recognition * ARGUMENTS : trace - the trace to be added * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::addTrace (const LTKTrace& trace) { int recMode; //strokes temporary string for getFlag string tempStr; // the recognition mode LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::addTrace()" << endl; m_fieldInk.push_back(trace); //pushing incoming trace to local buffer //if the recognition mode is set to streaming mode //the recognizer is called at this point tempStr = REC_MODE; int errorCode; if((errorCode = getFlag(tempStr,recMode))!=SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: LTKRecognitionContext::addTrace()"<<endl; LTKReturnError(errorCode); } if(recMode == REC_MODE_STREAMING) { m_wordRecPtr->processInk(*this); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::addTrace()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 22-FEB-2005 * NAME : addTraceGroup * DESCRIPTION : Adds a vector of tracegroup for recognition in the recognition context * ARGUMENTS : fieldInk - the ink to be added. * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::addTraceGroups (const LTKTraceGroupVector& fieldInk) { int numTraceGroups = fieldInk.size(); //number of trace groups int numTraces =0; //number of traces in each trace group string tempStr; //strokes temporary string for getFlag int recMode =0; // the recognition mode LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::addTraceGroups()" << endl; for(int i =0; i<numTraceGroups; ++i) { //accessing each trace group const LTKTraceGroup& traceGp = fieldInk[i]; //get all traces from tracegp //const LTKTraceVector& allTraces = traceGp.getAllTraces(); const LTKTraceVector& allTraces = traceGp.getAllTraces(); //push each trace to local buffer numTraces = allTraces.size(); for(int j = 0; j<numTraces; ++j) { m_fieldInk.push_back(allTraces[j]); } LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Pushed Trace Group:"<<i<<endl; } //if the recognition mode is set to streaming mode //the recognizer is called at this point tempStr = REC_MODE; int errorCode; if((errorCode = getFlag(tempStr,recMode))!=SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: LTKRecognitionContext::addTraceGroups()"<<endl; LTKReturnError(errorCode); } if(recMode == REC_MODE_STREAMING) { m_wordRecPtr->processInk(*this); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::addTraceGroups()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : beginRecoUnit * DESCRIPTION : This function marks the beginning of a recognition unit of Ink. * ARGUMENTS : none * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void LTKRecognitionContext::beginRecoUnit ( ) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::beginRecoUnit()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::beginRecoUnit()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 11-MAR-2005 * NAME : clearRecognitionResult * DESCRIPTION : clears all the recognition results * ARGUMENTS : none * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::clearRecognitionResult ( ) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::clearRecognitionResult()" << endl; //clearing the results m_results.clear(); //reset the index of next best result m_nextBestResultIndex = 0; m_fieldInk.clear(); int errorCode; if((errorCode=m_wordRecPtr->reset())!=SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: LTKRecognitionContext::clearRecognitionResult()"<<endl; LTKReturnError(errorCode); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::clearRecognitionResult()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : endRecoUnit * DESCRIPTION : This function marks the ending of a recognition unit of Ink. * ARGUMENTS : none * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void LTKRecognitionContext::endRecoUnit ( ) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::endRecoUnit()" << endl; //pushing a "marker" into the stream m_fieldInk.push_back(LTKTrace()); //calling the marker of the recognizer m_wordRecPtr->endRecoUnit(); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::endRecoUnit()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getAllInk * DESCRIPTION : Access function for the internal Ink data. * ARGUMENTS : none * RETURNS : reference to internal Ink data * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ const LTKTraceVector& LTKRecognitionContext::getAllInk () const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getAllInk()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getAllInk()" << endl; return m_fieldInk; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getConfidThreshold * DESCRIPTION : Access function for internal confidence threshold * ARGUMENTS : none * RETURNS : confidence threshold * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ float LTKRecognitionContext::getConfidThreshold () const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getConfidThreshold()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getConfidThreshold()" << endl; return m_confidThreshold; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getDeviceContext * DESCRIPTION : Access function for device context * ARGUMENTS : none * RETURNS : reference to LTKCapture device * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ const LTKCaptureDevice& LTKRecognitionContext::getDeviceContext ( ) const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getDeviceContext()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getDeviceContext()" << endl; return m_deviceContext; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getFlag * DESCRIPTION : Returns the value of the flag * ARGUMENTS : key - index of map * RETURNS : value of queried flag (int) * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::getFlag (const string& key,int& outValue) const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getFlag()" << endl; if(key=="") { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING) <<" LTKRecognitionContext::getFlag()" <<endl; LTKReturnError(EEMPTY_STRING); } vector<pair<string,int> >::const_iterator iter,iterEnd; iterEnd = m_recognitionFlags.end(); //Iterating through the vector to find the key for(iter = m_recognitionFlags.begin(); iter != iterEnd; ++iter) { if( (*iter).first == key ) { outValue = (*iter).second; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getFlag()" << endl; return SUCCESS; } } LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EKEY_NOT_FOUND <<":"<< getErrorMessage(EKEY_NOT_FOUND) <<" LTKRecognitionContext::getFlag()" <<endl; LTKReturnError(EKEY_NOT_FOUND); } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getLanguageModel * DESCRIPTION : returns the current language model indexed by the key * ARGUMENTS : key - index of map * RETURNS : value of the queried language model (string) * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::getLanguageModel (const string& key, string& outValue) const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getLanguageModel()" << endl; if(key=="") { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING) <<" LTKRecognitionContext::getLanguageModel()" <<endl; LTKReturnError(EEMPTY_STRING); } stringStringMap::const_iterator iterMap; iterMap = this->m_languageModels.find(key); if(iterMap != m_languageModels.end() ) { outValue = iterMap->second; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getLanguageModel()" << endl; return SUCCESS; } LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EKEY_NOT_FOUND <<":"<< getErrorMessage(EKEY_NOT_FOUND) <<" LTKRecognitionContext::getLanguageModel()" <<endl; LTKReturnError(EKEY_NOT_FOUND); } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getNextBestResults * DESCRIPTION : returns the next N best results * ARGUMENTS : numResults - number of results required * : results - This will be populated with results * RETURNS : SUCCESS/FAILURE * NOTES : Maximum number of results added is limited by number of results * : available. * : vector is not cleared inside the function * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::getNextBestResults (int numResults, LTKWordRecoResultVector& outWordRecResults) { //int lastIndex = 0;//Last index LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getNextBestResults()" << endl; if(numResults<=0) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM) <<" LTKRecognitionContext::getNextBestResults()" <<endl; LTKReturnError(ENON_POSITIVE_NUM); } vector<LTKWordRecoResult>::const_iterator resultBegin, resultEnd, resultIter; //Finding index of requested results resultBegin = m_results.begin() + m_nextBestResultIndex; //Finding index of requested results resultEnd = m_results.begin() + m_nextBestResultIndex + numResults; if(resultBegin > resultEnd ) { LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting LTKRecognitionContext::getNextBestResults" <<endl; return SUCCESS; } //limiting the end to the limits of available results if(resultEnd > m_results.end() ) resultEnd = m_results.end(); //pushing back the results for(resultIter = resultBegin; resultIter< resultEnd; ++resultIter) { outWordRecResults.push_back(*resultIter); } //updating next best result index m_nextBestResultIndex += numResults; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getNextBestResults()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getNumResults * DESCRIPTION : parameter number of results * ARGUMENTS : none * RETURNS : number of results (int) * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::getNumResults () const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getNumResults()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getNumResults()" << endl; return m_numResults; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getScreenContext * DESCRIPTION : access function for the screen context * ARGUMENTS : none * RETURNS : reference to screencontext object * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ const LTKScreenContext& LTKRecognitionContext::getScreenContext ( ) const { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getScreenContext()" << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getScreenContext()" << endl; return m_screenContext; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : getTopResult * DESCRIPTION : get the top result from the recognition context * ARGUMENTS : result - will be assigned to the top recognition result * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::getTopResult (LTKWordRecoResult& outTopResult) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::getTopResult()" << endl; if(m_results.size() == 0) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EEMPTY_WORDREC_RESULTS <<":"<< getErrorMessage(EEMPTY_WORDREC_RESULTS) <<" LTKRecognitionContext::getTopResult()" <<endl; LTKReturnError(EEMPTY_WORDREC_RESULTS); } m_nextBestResultIndex = 1; //assigning the value to output outTopResult = m_results[0]; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::getTopResult()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setConfidThreshold * DESCRIPTION : set the confidence threshold * ARGUMENTS : thresh - the threshold value to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::setConfidThreshold (float thresh) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setConfidThreshold()" << endl; if(thresh < 0) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENEGATIVE_NUM <<":" << getErrorMessage(ENEGATIVE_NUM) <<" LTKRecognitionContext::setConfidThreshold()" <<endl; LTKReturnError(ENEGATIVE_NUM); } m_confidThreshold = thresh; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setConfidThreshold()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setDeviceContext * DESCRIPTION : set the device context * ARGUMENTS : dc - reference to device context object to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void LTKRecognitionContext::setDeviceContext (const LTKCaptureDevice& dc) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setDeviceContext()" << endl; m_deviceContext = dc; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setDeviceContext()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setFlag * DESCRIPTION : sets the flag * ARGUMENTS : key - index of the flag to be set * : value - value of the flag to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::setFlag (const string& key, int value) { vector<pair<string,int> >::iterator iter,iterEnd;//iterators for iterating through all flags LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setFlag()" << endl; if(key=="") { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING) <<" LTKRecognitionContext::setFlag()" <<endl; LTKReturnError(EEMPTY_STRING); } iterEnd = m_recognitionFlags.end(); //looping through the map to check whether the flag exists for(iter = m_recognitionFlags.begin(); iter != iterEnd; ++iter) { if((*iter).first == key) { (*iter).second = value; break; } } //if the flag is not there in the map add a new flag if((iter == iterEnd)||(m_recognitionFlags.empty()) ) { m_recognitionFlags.push_back(pair<string,int>(key,value)); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setFlag()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setLanguageModel * DESCRIPTION : sets the language model * ARGUMENTS : property - name of ppty to be set (DICTIONARY, GRAMMAR) * : value - value to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::setLanguageModel (const string& property, const string& value) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setLanguageModel()" << endl; if(property=="" || value=="") { LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< "Either property or value is empty"<<endl; LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING) <<" LTKRecognitionContext::setLanguageModel()" <<endl; LTKReturnError(EEMPTY_STRING); } m_languageModels [property] = value; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setLanguageModel()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setNumResults * DESCRIPTION : sets parameter number of results to be buffered from recognizer * ARGUMENTS : numResults - the value to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::setNumResults (int numResults) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setNumResults()" << endl; if(numResults <= 0) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENON_POSITIVE_NUM <<":" << getErrorMessage(ENON_POSITIVE_NUM) <<" LTKRecognitionContext::setNumResults()" <<endl; LTKReturnError(ENON_POSITIVE_NUM); } m_numResults = numResults; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setNumResults()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : setScreenContext * DESCRIPTION : sc - reference to the screencontext object to be set * ARGUMENTS : numResults - the value to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void LTKRecognitionContext::setScreenContext (const LTKScreenContext& sc) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::setScreenContext()" << endl; m_screenContext = sc; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::setScreenContext()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 11-MAR-2005 * NAME : addRecognitionResult * DESCRIPTION : used by the recognizer to set the results back in the recognition context * ARGUMENTS : result - the value to be added * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void LTKRecognitionContext::addRecognitionResult (const LTKWordRecoResult& result) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::addRecognitionResult()" << endl; //adding the result to the internal data structure m_results.push_back(result); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::addRecognitionResult()" << endl; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 11-MAR-2005 * NAME : recognize * DESCRIPTION : the recognize call from the application. * : calls the recognize emthod of the recognizer * ARGUMENTS : numResults - the value to be set * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int LTKRecognitionContext::recognize () { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::recognize()" << endl; int errorCode; //calling recognize method of the recognizer if(m_wordRecPtr!=NULL) { if( (errorCode = m_wordRecPtr->recognize(*this)) != SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: LTKRecognitionContext::recognize()"<<endl; LTKReturnError(errorCode); } } else { LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Recognizer is not initialized" <<endl; LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER) <<" LTKRecognitionContext::recognize()" <<endl; LTKReturnError(ENULL_POINTER); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::recognize()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 28-FEB-2005 * NAME : reset * DESCRIPTION : Reset various parameters. * ARGUMENTS : resetParam - specifies data to be rest * RETURNS : SUCCESS/FAILURE * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ /** * This function is used to reset the different components of recognition context * @param resetParam : parameter that identifies the component to be reset * @return SUCCESS/FAILURE */ int LTKRecognitionContext::reset (int resetParam) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Entering: LTKRecognitionContext::reset()" << endl; if(resetParam & LTK_RST_INK) { m_fieldInk.clear(); } if(resetParam & LTK_RST_RECOGNIZER) { int errorCode=0; if((errorCode=m_wordRecPtr->reset(resetParam))!=SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: LTKRecognitionContext::reset()"<<endl; LTKReturnError(errorCode); } } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << " Exiting: LTKRecognitionContext::reset()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Deepu V. * DATE : 22-FEB-2005 * NAME : LTKRecognitionContext * DESCRIPTION : Destructor * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ LTKRecognitionContext::~LTKRecognitionContext() { }
30.100375
128
0.585066
bhardwajhp
ccf1217613402246c262ac1036dbac0d9c1bb5d9
4,019
cpp
C++
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
20
2016-03-28T08:00:28.000Z
2019-07-01T04:23:48.000Z
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
null
null
null
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
4
2017-03-28T16:11:06.000Z
2019-02-20T17:27:59.000Z
// // Hands.cpp // PokerGame // #include "Hands.hpp" USING_NS_CC; Hands::Hands() {} Hands::~Hands() { for(auto card : this->cards) { CC_SAFE_RELEASE_NULL(card.second->card); CC_SAFE_RELEASE_NULL(card.second); } } bool Hands::init() { return true; } // 手札のn番目にカードをセット void Hands::setCard(int n, Card* card) { CardState* cardState { CardState::create(card, false) }; this->cards.insert(n, cardState); } // 手札のn番目のカードを取得 Card* Hands::getCard(int n) const { return this->cards.at(n)->card; } // HOLD状態を切り替える bool Hands::toggleHold(int n) { bool hold { false }; this->cards.at(n)->hold?hold = false:hold = true; return this->cards.at(n)->hold = hold; } // HOLD状態を取得 bool Hands::isHold(int n) const { return this->cards.at(n)->hold; } // 役の判定 void Hands::dicisionHand() { // フラッシュ bool isFlush = false; Suit firstSuit { this->getCard(0)->getSuit() }; if (firstSuit == this->getCard(1)->getSuit() && firstSuit == this->getCard(2)->getSuit() && firstSuit == this->getCard(3)->getSuit() && firstSuit == this->getCard(4)->getSuit()) { isFlush = true; } // カードの数字を変数にいれる std::vector<int> numbers {}; for (int i { 0 }; i < HANDS_MAX; i++) { numbers.push_back(this->getCard(i)->getNumber()); } // ソート std::sort(numbers.begin(), numbers.end()); // ロイヤル・ストレート bool isRoyal = false; if (numbers.at(0) == 1 && numbers.at(1) == 10 && numbers.at(2) == 11 && numbers.at(3) == 12 && numbers.at(4) == 13) { isRoyal = true; } // ストレート bool isStraight = false; int firstNumber { numbers.at(0) }; if (numbers.at(1) == (firstNumber + 1) && numbers.at(2) == (firstNumber + 2) && numbers.at(3) == (firstNumber + 3) && numbers.at(4) == (firstNumber + 4)) { isStraight = true; } // ペア系の判定 // ペアの数のカウント用 int pearCount = 0; // ジャックス・オア・ベター bool isJacks = false; // スリーカード bool is3card = false; // フォーカード bool is4card = false; // トランプの数字についてそれぞれ調査する for(int no { 1 }; no <= 13; no++){ // 手札に数字が何枚含まれているかを数える int count = 0; for(int i { 0 }; i < HANDS_MAX; i++){ // 調査対象の数字ならカウント if(numbers.at(i) == no){ count++; } } // 枚数に応じて、ペアのカウントを計算 switch(count) { case 2: { // ペアの場合はカウント pearCount++; if(no > 10 || no == 1){ // J Q K A の場合は、ジャックス・オア・ベター isJacks = true; } break; } case 3: { // スリーカード is3card = true; break; } case 4: { // フォーカード is4card = true; break; } } } // ツーペア bool is2pear = false; if(pearCount == 2){ is2pear = true; } // 判定 this->hand = Hand::NOTHING; if(isRoyal && isFlush) { this->hand = Hand::ROYAL_STRAIGHT_FLUSH; } else if(isStraight && isFlush) { this->hand = Hand::STRAIGHT_FLUSH; } else if(is4card) { this->hand = Hand::FOUR_OF_A_KIND; } else if(is3card && pearCount > 0) { this->hand = Hand::FULL_HOUSE; } else if(isFlush) { this->hand = Hand::FLUSH; } else if(isRoyal || isStraight) { this->hand = Hand::STRAIGHT; } else if(is3card) { this->hand = Hand::THREE_OF_A_KIND; } else if(pearCount == 2) { this->hand = Hand::TWOPAIR; } else if(isJacks) { this->hand = Hand::JACKS_OR_BETTER; } } // 役の取得 Hand Hands::getHand() const { return this->hand; } // 配当の取得 int Hands::getRate() const { return Rate.at(this->hand); }
19.509709
60
0.485195
mettoboshi
ccf40d824395a01575342a23d6a985a49c672275
24,565
cpp
C++
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
1
2016-07-20T18:43:34.000Z
2016-07-20T18:43:34.000Z
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
4
2016-08-30T05:29:18.000Z
2016-11-07T04:02:15.000Z
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
1
2017-10-20T22:31:17.000Z
2017-10-20T22:31:17.000Z
// Copyright Glen Knowles 2019 - 2021. // Distributed under the Boost Software License, Version 1.0. // // winres.cpp - dim windows platform #include "pch.h" #pragma hdrstop using namespace std; using namespace Dim; /**************************************************************************** * * Declarations * ***/ namespace Dim { class ExecProgram : public ListLink<> , public ITimerNotify { public: class ExecPipe : public IPipeNotify { public: // Inherited via IPipeNotify bool onPipeAccept() override; bool onPipeRead(size_t * bytesUsed, string_view data) override; void onPipeDisconnect() override; void onPipeBufferChanged(const PipeBufferInfo & info) override; ExecProgram * m_notify = {}; StdStream m_strm = {}; RunMode m_mode = kRunStopped; HANDLE m_child = {}; }; public: static void write(IExecNotify * notify, std::string_view data); static void dequeue(); public: ExecProgram( IExecNotify * notify, string_view cmdline, const ExecOptions & opts ); ~ExecProgram(); void exec(); TaskQueueHandle queue() const { return m_hq; } void terminate(); void postJobExit(); bool onAccept(StdStream strm); bool onRead(size_t * bytesUsed, StdStream strm, string_view data); void onDisconnect(StdStream strm); void onBufferChanged(StdStream strm, const PipeBufferInfo & info); void onJobExit(); // Inherited via ITimerNotify Duration onTimer(TimePoint now) override; private: bool createPipe( HANDLE * hchild, StdStream strm, string_view name, Pipe::OpenMode oflags ); bool completeIfDone_LK(); TaskQueueHandle m_hq; HANDLE m_job = NULL; HANDLE m_process = NULL; HANDLE m_thread = NULL; string m_cmdline; ExecOptions m_opts; //----------------------------------------------------------------------- mutex m_mut; IExecNotify * m_notify{}; ExecPipe m_pipes[3]; unsigned m_connected{}; RunMode m_mode{kRunStopped}; bool m_canceled = true; int m_exitCode = -1; }; } // namespace /**************************************************************************** * * Variables * ***/ static auto & s_perfTotal = uperf("exec.programs"); static auto & s_perfIncomplete = uperf("exec.programs (incomplete)"); static auto & s_perfWaiting = uperf("exec.programs (waiting)"); static mutex s_mut; static HANDLE s_iocp; static List<ExecProgram> s_programs; /**************************************************************************** * * IOCP completion thread * ***/ //=========================================================================== static void jobObjectIocpThread() { const int kMaxEntries = 8; OVERLAPPED_ENTRY entries[kMaxEntries]; ULONG found; for (;;) { if (!GetQueuedCompletionStatusEx( s_iocp, entries, (ULONG) size(entries), &found, INFINITE, // timeout false // alertable )) { WinError err; if (err == ERROR_ABANDONED_WAIT_0) { // Completion port closed while inside get status. break; } else if (err == ERROR_INVALID_HANDLE) { // Completion port closed before call to get status. break; } else { logMsgFatal() << "GetQueuedCompletionStatusEx(JobPort): " << err; } } for (unsigned i = 0; i < found; ++i) { auto exe = reinterpret_cast<ExecProgram *>( entries[i].lpCompletionKey ); DWORD msg = entries[i].dwNumberOfBytesTransferred; [[maybe_unused]] DWORD procId = (DWORD) (uintptr_t) entries[i].lpOverlapped; if (msg == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO) { // The process, and any child processes it may have launched, // have exited. taskPush(exe->queue(), [=](){ exe->onJobExit(); }); } } } scoped_lock lk{s_mut}; s_iocp = 0; } //=========================================================================== static HANDLE iocpHandle() { scoped_lock lk(s_mut); if (s_iocp) return s_iocp; s_iocp = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, // existing port NULL, // completion key 0 // concurrent threads, 0 for default ); if (!s_iocp) logMsgFatal() << "CreateIoCompletionPort(null): " << WinError{}; // Start IOCP dispatch task taskPushOnce("JobObject Dispatch", jobObjectIocpThread); return s_iocp; } /**************************************************************************** * * ExecProgram::ExecPipe * ***/ //=========================================================================== bool ExecProgram::ExecPipe::onPipeAccept() { return m_notify->onAccept(m_strm); } //=========================================================================== bool ExecProgram::ExecPipe::onPipeRead( size_t * bytesUsed, std::string_view data ) { return m_notify->onRead(bytesUsed, m_strm, data); } //=========================================================================== void ExecProgram::ExecPipe::onPipeDisconnect() { m_notify->onDisconnect(m_strm); } //=========================================================================== void ExecProgram::ExecPipe::onPipeBufferChanged(const PipeBufferInfo & info) { m_notify->onBufferChanged(m_strm, info); } /**************************************************************************** * * ExecProgram * ***/ //=========================================================================== // static void ExecProgram::write(IExecNotify * notify, string_view data) { if (notify->m_exec) pipeWrite(&notify->m_exec->m_pipes[kStdIn], data); } //=========================================================================== // static void ExecProgram::dequeue() { List<ExecProgram> progs; { scoped_lock lk{s_mut}; while (auto prog = s_programs.front()) { if (prog->m_opts.concurrency <= s_perfIncomplete) break; s_perfWaiting -= 1; s_perfIncomplete += 1; progs.link(prog); } } while (auto prog = progs.front()) { prog->unlink(); prog->exec(); } } //=========================================================================== ExecProgram::ExecProgram( IExecNotify * notify, string_view cmdline, const ExecOptions & opts ) : m_notify(notify) , m_cmdline(cmdline) , m_opts(opts) { s_perfTotal += 1; s_perfWaiting += 1; m_notify->m_exec = this; if (m_opts.concurrency == 0) m_opts.concurrency = envProcessors(); for (auto && e : { kStdIn, kStdOut, kStdErr }) { m_pipes[e].m_strm = e; m_pipes[e].m_notify = this; } scoped_lock lk{s_mut}; s_programs.link(this); } //=========================================================================== ExecProgram::~ExecProgram() { assert(!m_notify); for ([[maybe_unused]] auto && pi : m_pipes) assert(pi.m_mode == kRunStopped); if (linked()) { s_perfWaiting -= 1; } else { s_perfIncomplete -= 1; } } //=========================================================================== void ExecProgram::terminate() { unique_lock lk(m_mut); if (m_mode == kRunStopped || !m_process) return; if (!TerminateProcess(m_process, (UINT) -1)) { logMsgError() << "TerminateProcess(" << m_cmdline << "): " << WinError{}; } CloseHandle(m_process); // Set to null handle so the process will be recognized as canceled. m_process = {}; } //=========================================================================== void ExecProgram::postJobExit() { // Exit events are posted to the job queue so the onExecComplete event gets // routed to the task queue selected by the application. if (!PostQueuedCompletionStatus( s_iocp, JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO, (uintptr_t) this, (OVERLAPPED *) (uintptr_t) GetProcessId(m_process) )) { logMsgFatal() << "PostQueuedCompletionStatus: " << WinError{}; } } //=========================================================================== void ExecProgram::exec() { // Now that we're committed to getting an onJobExit() call, change mode // so that we'll wait for it. m_mode = kRunStarting; m_hq = m_opts.hq; // Create pipes char rawname[100]; snprintf( rawname, sizeof rawname, "//./pipe/local/%u_%p", envProcessId(), this ); string name = rawname; struct { StdStream strm; string name; Pipe::OpenMode oflags; } pipes[] = { { kStdIn, name + ".in", Pipe::fReadWrite }, { kStdOut, name + ".out", Pipe::fReadOnly }, { kStdErr, name + ".err", Pipe::fReadOnly }, }; // First set all pipes to kRunStarting (not kRunStopped), so that the // following transition to stopped can be unambiguously detected. for (auto&& p : pipes) m_pipes[p.strm].m_mode = kRunStarting; for (auto && p : pipes) { auto & child = m_pipes[p.strm].m_child; if (!createPipe(&child, p.strm, p.name, p.oflags)) { postJobExit(); return; } } } //=========================================================================== bool ExecProgram::onAccept(StdStream strm) { unique_lock lk(m_mut); assert(m_mode == kRunStarting); assert(m_pipes[strm].m_mode == kRunStarting); m_pipes[strm].m_mode = kRunRunning; if (m_pipes[kStdIn].m_mode == kRunStarting || m_pipes[kStdOut].m_mode == kRunStarting || m_pipes[kStdErr].m_mode == kRunStarting ) { // If it wasn't the last pipe to finish starting, continue waiting for // the last one. return true; } // Now that all pipes have started, check to make sure all are running, and // stop the whole exec if they aren't. if (m_pipes[kStdIn].m_mode != kRunRunning || m_pipes[kStdOut].m_mode != kRunRunning || m_pipes[kStdErr].m_mode != kRunRunning ) { lk.unlock(); postJobExit(); return true; } bool success = false; for (;;) { m_job = CreateJobObject(NULL, NULL); if (!m_job) { logMsgError() << "CreateJobObjectW()" << WinError{}; break; } JOBOBJECT_EXTENDED_LIMIT_INFORMATION ei = {}; auto & bi = ei.BasicLimitInformation; bi.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject( m_job, JobObjectExtendedLimitInformation, &ei, sizeof ei )) { logMsgError() << "SetInformationJobObject(KILL_ON_JOB_CLOSE): " << WinError{}; break; } JOBOBJECT_ASSOCIATE_COMPLETION_PORT ap = {}; ap.CompletionKey = this; ap.CompletionPort = iocpHandle(); if (!SetInformationJobObject( m_job, JobObjectAssociateCompletionPortInformation, &ap, sizeof ap )) { logMsgError() << "SetInformationJobObject(ASSOC_IOCP): " << WinError{}; break; } success = true; break; } if (!success) { lk.unlock(); postJobExit(); return true; } char * envBlk = nullptr; string envBuf; if (!m_opts.envVars.empty()) { auto env = envGetVars(); for (auto&& [name, value] : m_opts.envVars) { if (value.empty()) { env.erase(name); } else { env[name] = value; } } for (auto&& [name, value] : env) { envBuf += name; envBuf += '='; envBuf += value; envBuf += '\0'; } envBuf += '\0'; envBlk = envBuf.data(); } auto wcmdline = toWstring(m_cmdline); auto wworkDir = toWstring(m_opts.workingDir); STARTUPINFOW si = { sizeof si }; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = m_pipes[kStdIn].m_child; si.hStdOutput = m_pipes[kStdOut].m_child; si.hStdError = m_pipes[kStdErr].m_child; PROCESS_INFORMATION pi = {}; bool running = CreateProcessW( NULL, // explicit application name (no search path) wcmdline.data(), NULL, // process attrs NULL, // thread attrs true, // inherit handles, true to inherit the pipe handles CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDED, envBlk, wworkDir.empty() ? NULL : wworkDir.c_str(), // current dir &si, &pi ); WinError err; // Close parents reference to child side of pipes. for (auto && pipe : m_pipes) { CloseHandle(pipe.m_child); pipe.m_child = {}; } if (!running) { logMsgError() << "CreateProcessW(" << m_cmdline << "): " << err; lk.unlock(); postJobExit(); return true; } m_process = pi.hProcess; m_thread = pi.hThread; if (!AssignProcessToJobObject(m_job, m_process)) { logMsgError() << "AssignProcessToJobObject(" << m_cmdline << "): " << WinError{}; lk.unlock(); terminate(); postJobExit(); return true; } // Now that the process has been assigned to the job it can be resumed. // If it had launched a process before joining the job that child would // be untracked. m_mode = kRunRunning; ResumeThread(m_thread); CloseHandle(m_thread); // Start the allowed execution time countdown. timerUpdate(this, m_opts.timeout); auto pipe = &m_pipes[kStdIn]; if (!m_opts.stdinData.empty()) { // if !enableExecWrite the pipe will be closed when this write // completes. pipeWrite(pipe, m_opts.stdinData); } else if (!m_opts.enableExecWrite) { pipeClose(pipe); } return true; } //=========================================================================== bool ExecProgram::onRead( size_t * bytesUsed, StdStream strm, string_view data ) { return m_notify->onExecRead(bytesUsed, strm, data); } //=========================================================================== void ExecProgram::onDisconnect(StdStream strm) { unique_lock lk(m_mut); auto & pi = m_pipes[strm]; pi.m_mode = kRunStopped; if (completeIfDone_LK()) lk.release(); } //=========================================================================== void ExecProgram::onBufferChanged( StdStream strm, const PipeBufferInfo & info ) { if (strm == kStdIn && !m_opts.enableExecWrite && !info.incomplete) pipeClose(&m_pipes[strm]); } //=========================================================================== Duration ExecProgram::onTimer(TimePoint now) { terminate(); return kTimerInfinite; } //=========================================================================== void ExecProgram::onJobExit() { assert(m_mode != kRunStopped); unique_lock lk(m_mut); for (auto && pi : m_pipes) { pipeClose(&pi); if (pi.m_child) { CloseHandle(pi.m_child); pi.m_child = {}; } } m_mode = kRunStopped; DWORD rc; if (GetExitCodeProcess(m_process, &rc)) { m_canceled = false; m_exitCode = rc; } else { WinError err; m_canceled = true; m_exitCode = -1; } CloseHandle(m_process); CloseHandle(m_job); if (completeIfDone_LK()) lk.release(); } //=========================================================================== bool ExecProgram::completeIfDone_LK() { if (m_pipes[kStdIn].m_mode != kRunStopped || m_pipes[kStdOut].m_mode != kRunStopped || m_pipes[kStdErr].m_mode != kRunStopped || m_mode != kRunStopped ) { return false; } if (m_notify) { m_notify->m_exec = nullptr; m_notify->onExecComplete(m_canceled, m_exitCode); m_notify = nullptr; } m_mut.unlock(); delete this; dequeue(); return true; } //=========================================================================== bool ExecProgram::createPipe( HANDLE * child, StdStream strm, string_view name, Pipe::OpenMode oflags ) { assert(m_pipes[strm].m_mode == kRunStarting); pipeListen(&m_pipes[strm], name, oflags, queue()); if (child) { unsigned flags = SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION; // Child side has read & write reversed from listening parent if (oflags & Pipe::fReadOnly) flags |= GENERIC_WRITE; if (oflags & Pipe::fWriteOnly) flags |= GENERIC_READ; if (oflags & Pipe::fReadWrite) flags |= GENERIC_READ | GENERIC_WRITE; auto wname = toWstring(name); SECURITY_ATTRIBUTES sa = {}; sa.bInheritHandle = true; auto cp = CreateFileW( wname.c_str(), flags, 0, // share &sa, OPEN_EXISTING, 0, // attributes and flags NULL // template file ); if (cp == INVALID_HANDLE_VALUE) { logMsgError() << "CreateFile(pipe): " << WinError{}; return false; } *child = cp; } return true; } /**************************************************************************** * * IExecNotify * ***/ //=========================================================================== bool IExecNotify::onExecRead( size_t * bytesUsed, StdStream strm, string_view data ) { switch (strm) { case kStdIn: break; case kStdOut: m_out.append(data); break; case kStdErr: m_err.append(data); break; } *bytesUsed = data.size(); return true; } /**************************************************************************** * * Execute child program * ***/ //=========================================================================== void Dim::execProgram( IExecNotify * notify, const std::string & cmdline, const ExecOptions & rawOpts ) { assert(notify); auto opts = rawOpts; if (!opts.hq) opts.hq = taskEventQueue(); new ExecProgram(notify, cmdline, opts); ExecProgram::dequeue(); } //=========================================================================== void Dim::execProgram( IExecNotify * notify, const std::vector<std::string> & args, const ExecOptions & opts ) { execProgram(notify, Cli::toCmdline(args), opts); } //=========================================================================== void Dim::execWrite(IExecNotify * notify, std::string_view data) { ExecProgram::write(notify, data); } /**************************************************************************** * * Simple execute child program * ***/ namespace { struct SimpleExecNotify : public IExecNotify { function<void(ExecResult && res)> m_fn; ExecResult m_res; void onExecComplete(bool canceled, int exitCode) override; }; } // namespace //=========================================================================== void SimpleExecNotify::onExecComplete(bool canceled, int exitCode) { m_res.exitCode = exitCode; m_res.out = move(m_out); m_res.err = move(m_err); m_fn(move(m_res)); delete this; } //=========================================================================== void Dim::execProgram( function<void(ExecResult && res)> fn, const string & cmdline, const ExecOptions & opts ) { auto notify = new SimpleExecNotify; notify->m_fn = fn; notify->m_res.cmdline = cmdline; execProgram(notify, cmdline, opts); } //=========================================================================== void Dim::execProgram( function<void(ExecResult && res)> fn, const vector<string> & args, const ExecOptions & opts ) { execProgram(fn, Cli::toCmdline(args), opts); } /**************************************************************************** * * Execute child program and wait * ***/ //=========================================================================== bool Dim::execProgramWait( ExecResult * out, const string & cmdline, const ExecOptions & rawOpts ) { auto opts = rawOpts; if (!opts.hq) opts.hq = taskInEventThread() ? taskComputeQueue() : taskEventQueue(); mutex mut; condition_variable cv; out->cmdline = cmdline; bool complete = false; execProgram( [&](ExecResult && res) { { scoped_lock lk{mut}; *out = move(res); complete = true; } cv.notify_one(); }, cmdline, opts ); unique_lock lk{mut}; while (!complete) cv.wait(lk); return out->exitCode != -1; } //=========================================================================== bool Dim::execProgramWait( ExecResult * res, const vector<string> & args, const ExecOptions & opts ) { return execProgramWait(res, Cli::toCmdline(args), opts); } /**************************************************************************** * * Elevated * ***/ //=========================================================================== bool Dim::execElevatedWait( int * exitCode, const string & cmdline, const string & workingDir ) { SHELLEXECUTEINFOW ei = { sizeof ei }; ei.lpVerb = L"RunAs"; auto args = Cli::toArgv(string(cmdline)); auto wexe = toWstring(args.empty() ? "" : args[0]); ei.lpFile = wexe.c_str(); auto wargs = toWstring(cmdline); ei.lpParameters = wargs.c_str(); auto wdir = toWstring(workingDir); if (wdir.size()) ei.lpDirectory = wdir.c_str(); ei.fMask = SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI ; ei.nShow = SW_HIDE; if (!ShellExecuteExW(&ei)) { WinError err; if (err == ERROR_CANCELLED) { logMsgError() << "Operation canceled."; } else { logMsgError() << "ShellExecuteExW: " << WinError(); } *exitCode = -1; return false; } if (!ei.hProcess) { *exitCode = EX_OK; } else { DWORD rc = EX_OSERR; if (WAIT_OBJECT_0 == WaitForSingleObject(ei.hProcess, INFINITE)) GetExitCodeProcess(ei.hProcess, &rc); *exitCode = rc; CloseHandle(ei.hProcess); } return true; } /**************************************************************************** * * External * ***/ //=========================================================================== void Dim::execCancelWaiting() { List<ExecProgram> progs; { scoped_lock lk{s_mut}; progs.link(move(s_programs)); } while (auto prog = progs.front()) { s_programs.unlink(prog); prog->onJobExit(); } } /**************************************************************************** * * Shutdown monitor * ***/ namespace { class ShutdownNotify : public IShutdownNotify { void onShutdownServer(bool firstTry) override; void onShutdownConsole(bool firstTry) override; }; } // namespace static ShutdownNotify s_cleanup; //=========================================================================== void ShutdownNotify::onShutdownServer(bool firstTry) { if (s_perfIncomplete || s_perfWaiting) return shutdownIncomplete(); } //=========================================================================== void ShutdownNotify::onShutdownConsole(bool firstTry) { scoped_lock lk(s_mut); if (firstTry && s_iocp) { auto h = s_iocp; s_iocp = INVALID_HANDLE_VALUE; if (!CloseHandle(h)) logMsgError() << "CloseHandle(IOCP): " << WinError{}; Sleep(0); } if (s_iocp) shutdownIncomplete(); } /**************************************************************************** * * Internal API * ***/ //=========================================================================== void Dim::winExecInitialize() { shutdownMonitor(&s_cleanup); }
26.876368
79
0.495095
gknowles
6901773a79e7819829a285391bbdc7d7c0feaf79
2,546
cc
C++
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "kernels/funcs/npu_funcs.h" #include "kernels/funcs/npu_op_runner.h" #include "paddle/phi/core/tensor_meta.h" namespace custom_kernel { template <typename T, typename Context> void CastKernel(const Context& dev_ctx, const phi::DenseTensor& x, phi::DenseTensorMeta::DataType dtype, phi::DenseTensor* out) { if (x.dtype() == dtype) { dev_ctx.template Alloc<T>(out); TensorCopy(dev_ctx, x, false, out); return; } int aclDtype = ConvertToNpuDtype(dtype); if (dtype == phi::DenseTensorMeta::DataType::FLOAT32) { dev_ctx.template Alloc<float>(out); } else if (dtype == phi::DenseTensorMeta::DataType::FLOAT64) { dev_ctx.template Alloc<double>(out); } else if (dtype == phi::DenseTensorMeta::DataType::FLOAT16) { dev_ctx.template Alloc<phi::dtype::float16>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT16) { dev_ctx.template Alloc<int16_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT32) { dev_ctx.template Alloc<int32_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT64) { dev_ctx.template Alloc<int64_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::BOOL) { dev_ctx.template Alloc<bool>(out); } aclrtStream stream = static_cast<aclrtStream>(dev_ctx.stream()); const auto& runner = NpuOpRunner( "Cast", {x}, {*out}, {{"dst_type", static_cast<int32_t>(aclDtype)}}); runner.Run(stream); } } // namespace custom_kernel PD_REGISTER_PLUGIN_KERNEL(cast, ascend, ALL_LAYOUT, custom_kernel::CastKernel, phi::dtype::float16, float, double, int16_t, int32_t, int64_t, bool) {}
35.859155
75
0.628437
Aganlengzi
6902fa66817a82195c3b78aac8867e849e1a6533
227
cpp
C++
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#define PROBLEM "https://judge.yosupo.jp/problem/zalgorithm" // #include "../../template/template.hpp" // #include "../../string/z-algorithm.hpp" using namespace Nyaan; void Nyaan::solve() { ins(s); out(z_algorithm(s)); }
18.916667
60
0.669604
NachiaVivias
6904d91a526b6a87879cb54d2dc836bb8fa35704
9,863
hxx
C++
main/comphelper/inc/comphelper/stl_types.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/comphelper/inc/comphelper/stl_types.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/comphelper/inc/comphelper/stl_types.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ #ifndef _COMPHELPER_STLTYPES_HXX_ #define _COMPHELPER_STLTYPES_HXX_ #if !defined(__SGI_STL_VECTOR_H) || !defined(__SGI_STL_MAP_H) || !defined(__SGI_STL_MULTIMAP_H) #include <vector> #include <map> #include <stack> #include <set> #ifdef _MSC_VER # ifndef _USE_MATH_DEFINES # define _USE_MATH_DEFINES // needed by Visual C++ for math constants # endif #endif #include <math.h> // prevent conflict between exception and std::exception #include <functional> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/beans/PropertyValue.hpp> //... namespace comphelper ................................................ namespace comphelper { //......................................................................... //======================================================================== // comparison functors //------------------------------------------------------------------------ struct UStringLess : public ::std::binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { return x < y ? true : false;} // construct prevents a MSVC6 warning }; //------------------------------------------------------------------------ struct UStringMixLess : public ::std::binary_function< ::rtl::OUString, ::rtl::OUString, bool> { bool m_bCaseSensitive; public: UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){} bool operator() (const ::rtl::OUString& x, const ::rtl::OUString& y) const { if (m_bCaseSensitive) return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false; else return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false; } bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ struct UStringEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equals( rhs );} }; //------------------------------------------------------------------------ struct UStringIEqual { sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );} }; //------------------------------------------------------------------------ struct UStringHash { size_t operator() (const ::rtl::OUString& rStr) const {return rStr.hashCode();} }; //------------------------------------------------------------------------ class UStringMixEqual { sal_Bool m_bCaseSensitive; public: UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} sal_Bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ class TStringMixEqualFunctor : public ::std::binary_function< ::rtl::OUString,::rtl::OUString,bool> { sal_Bool m_bCaseSensitive; public: TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True) :m_bCaseSensitive(bCaseSensitive) {} bool operator() (const ::rtl::OUString& lhs, const ::rtl::OUString& rhs) const { return !!(m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs )); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //------------------------------------------------------------------------ class TPropertyValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::PropertyValue,::rtl::OUString,bool> { public: TPropertyValueEqualFunctor() {} bool operator() (const ::com::sun::star::beans::PropertyValue& lhs, const ::rtl::OUString& rhs) const { return !!(lhs.Name == rhs); } }; //------------------------------------------------------------------------ class UStringMixHash { sal_Bool m_bCaseSensitive; public: UStringMixHash(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){} size_t operator() (const ::rtl::OUString& rStr) const { return m_bCaseSensitive ? rStr.hashCode() : rStr.toAsciiUpperCase().hashCode(); } sal_Bool isCaseSensitive() const {return m_bCaseSensitive;} }; //===================================================================== //= OInterfaceCompare //===================================================================== /** is stl-compliant structure for comparing Reference&lt; &lt;iface&gt; &gt; instances */ template < class IAFCE > struct OInterfaceCompare :public ::std::binary_function < ::com::sun::star::uno::Reference< IAFCE > , ::com::sun::star::uno::Reference< IAFCE > , bool > { bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const { return lhs.get() < rhs.get(); // this does not make any sense if you see the semantics of the pointer returned by get: // It's a pointer to a point in memory where an interface implementation lies. // But for our purpose (provide a reliable less-operator which can be used with the STL), this is // sufficient .... } }; template <class _Tp, class _Arg> class mem_fun1_t : public ::std::binary_function<_Tp*,_Arg,void> { typedef void (_Tp::*_fun_type)(_Arg); public: explicit mem_fun1_t(_fun_type __pf) : _M_f(__pf) {} void operator()(_Tp* __p, _Arg __x) const { (__p->*_M_f)(__x); } private: _fun_type _M_f; }; template <class _Tp, class _Arg> inline mem_fun1_t<_Tp,_Arg> mem_fun(void (_Tp::*__f)(_Arg)) { return mem_fun1_t<_Tp,_Arg>(__f); } //......................................................................... /** output iterator that appends OUStrings into an OUStringBuffer. */ class OUStringBufferAppender : public ::std::iterator< ::std::output_iterator_tag, void, void, void, void> { public: typedef OUStringBufferAppender Self; typedef ::std::output_iterator_tag iterator_category; typedef void value_type; typedef void reference; typedef void pointer; typedef size_t difference_type; OUStringBufferAppender(::rtl::OUStringBuffer & i_rBuffer) : m_rBuffer(i_rBuffer) { } Self & operator=(::rtl::OUString const & i_rStr) { m_rBuffer.append( i_rStr ); return *this; } Self & operator*() { return *this; } // so operator= works Self & operator++() { return *this; } Self & operator++(int) { return *this; } private: ::rtl::OUStringBuffer & m_rBuffer; }; //......................................................................... /** algorithm similar to std::copy, but inserts a separator between elements. */ template< typename ForwardIter, typename OutputIter, typename T > OutputIter intersperse( ForwardIter start, ForwardIter end, OutputIter out, T const & separator) { if (start != end) { *out = *start; ++start; ++out; } while (start != end) { *out = separator; ++out; *out = *start; ++start; ++out; } return out; } //......................................................................... } //... namespace comphelper ................................................ //================================================================== // consistently defining stl-types //================================================================== #define DECLARE_STL_ITERATORS(classname) \ typedef classname::iterator classname##Iterator; \ typedef classname::const_iterator Const##classname##Iterator \ #define DECLARE_STL_MAP(keytype, valuetype, comparefct, classname) \ typedef std::map< keytype, valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_STDKEY_MAP(keytype, valuetype, classname) \ DECLARE_STL_MAP(keytype, valuetype, std::less< keytype >, classname) \ #define DECLARE_STL_VECTOR(valuetyp, classname) \ typedef std::vector< valuetyp > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_USTRINGACCESS_MAP(valuetype, classname) \ DECLARE_STL_MAP(::rtl::OUString, valuetype, ::comphelper::UStringLess, classname) \ #define DECLARE_STL_STDKEY_SET(valuetype, classname) \ typedef ::std::set< valuetype > classname; \ DECLARE_STL_ITERATORS(classname) \ #define DECLARE_STL_SET(valuetype, comparefct, classname) \ typedef ::std::set< valuetype, comparefct > classname; \ DECLARE_STL_ITERATORS(classname) \ #endif #endif // _COMPHELPER_STLTYPES_HXX_
35.351254
153
0.573963
Grosskopf
690ab434cbe96c481358662fbc419dc351a1d613
36,549
cpp
C++
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
6
2015-06-29T16:59:17.000Z
2017-12-14T13:50:36.000Z
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
null
null
null
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
3
2015-03-26T15:08:52.000Z
2020-01-07T06:11:29.000Z
/****************************************************************************** * @file hgpucl_devices.cpp * @author Vadim Demchik <vadimdi@yahoo.com> * @version 1.0.2 * * @brief [HGPU library] * Interface for OpenCL AMD APP & nVidia SDK environment * devices submodule * * * @section LICENSE * * Copyright (c) 2013-2015 Vadim Demchik * 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 HOLDER 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 "hgpucl_devices.h" // new OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_new(unsigned int number_of_devices){ if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); if (number_of_devices>HGPU_GPU_MAX_DEVICES) HGPU_GPU_error_message(HGPU_ERROR_NO_MEMORY,"exceed maximal number of descriptions for devices"); HGPU_GPU_devices* result = (HGPU_GPU_devices*) calloc(1,sizeof(HGPU_GPU_devices)); result->devices = (cl_device_id*) calloc(number_of_devices,sizeof(cl_device_id)); result->number_of_devices = number_of_devices; return result; } // new OpenCL devices empty devices HGPU_GPU_devices* HGPU_GPU_devices_new_empty(void){ HGPU_GPU_devices* result = (HGPU_GPU_devices*) calloc(1,sizeof(HGPU_GPU_devices)); result->devices = NULL; result->number_of_devices = 0; return result; } // delete OpenCL devices void HGPU_GPU_devices_delete(HGPU_GPU_devices** devices){ if (!(*devices)) return; free((*devices)->devices); free(*devices); (*devices) = NULL; } // clone OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_clone(HGPU_GPU_devices* devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); size_t bytes = number_of_devices * sizeof(cl_device_id); memcpy_s(result->devices,bytes,devices->devices,bytes); return result; } // copy OpenCL devices void HGPU_GPU_devices_copy(HGPU_GPU_devices** devices_destination,HGPU_GPU_devices* devices_source){ HGPU_GPU_devices_delete(devices_destination); (*devices_destination) = HGPU_GPU_devices_clone(devices_source); } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get(void){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_platforms_delete(&platforms); return result; } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get_on_platforms(HGPU_GPU_platforms* platforms){ unsigned int number_of_devices = HGPU_GPU_devices_get_number_on_platforms(platforms); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); unsigned int device_index = 0; for (unsigned int i=0; i<HGPU_GPU_platforms_get_number(platforms); i++){ unsigned int number_of_devices_on_platform = HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); if (number_of_devices_on_platform){ HGPU_GPU_devices* devices_on_platform = HGPU_GPU_devices_get_on_platform(platforms->platforms[device_index]); for (unsigned int j=0; j<number_of_devices_on_platform; j++) result->devices[device_index++] = devices_on_platform->devices[j]; HGPU_GPU_devices_delete(&devices_on_platform); } } return result; } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get_on_platform(cl_platform_id platform){ cl_uint number_of_devices = HGPU_GPU_devices_get_number_on_platform(platform); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); HGPU_GPU_error_message(clGetDeviceIDs(platform,CL_DEVICE_TYPE_ALL,number_of_devices, result->devices, &result->number_of_devices),"clGetDeviceIDs failed"); if(!result->number_of_devices) HGPU_GPU_error_message(HGPU_ERROR_NO_PLATFORM,"there are no any available OpenCL devices"); return result; } // get OpenCL devices by vendor HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor(HGPU_GPU_vendor vendor){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } // get OpenCL devices by vendor on platform HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor_on_platform(cl_platform_id platform,HGPU_GPU_vendor vendor){ HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platform(platform); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } // get OpenCL devices by vendor on platforms HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor_on_platforms(HGPU_GPU_platforms* platforms,HGPU_GPU_vendor vendor){ HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } //get max OpenCL version of devices on platforms HGPU_GPU_version HGPU_GPU_devices_get_version_max(HGPU_GPU_devices* devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); HGPU_GPU_version version = HGPU_GPU_device_get_version(devices->devices[0]); for (unsigned int i=1; i<number_of_devices; i++) version = HGPU_GPU_version_max(version,HGPU_GPU_device_get_version(devices->devices[i])); return version; } // get number of OpenCL devices unsigned int HGPU_GPU_devices_get_number(HGPU_GPU_devices* devices){ if (!devices) return 0; return devices->number_of_devices; } // get total number of OpenCL devices unsigned int HGPU_GPU_devices_get_total_number(void){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); unsigned int result = 0; for (unsigned int i=0;i<HGPU_GPU_platforms_get_number(platforms);i++) result += HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); HGPU_GPU_platforms_delete(&platforms); return result; } // get number of OpenCL devices unsigned int HGPU_GPU_devices_get_number_on_platform(cl_platform_id platform){ cl_uint number_of_devices = 0; cl_int get_number_of_devices_result = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, NULL, &number_of_devices); if (get_number_of_devices_result!=CL_DEVICE_NOT_FOUND) HGPU_GPU_error_message(get_number_of_devices_result, "clGetDeviceIDs failed"); return number_of_devices; } // get number of OpenCL devices on platforms unsigned int HGPU_GPU_devices_get_number_on_platforms(HGPU_GPU_platforms* platforms){ unsigned int result = 0; for (unsigned int i=0;i<HGPU_GPU_platforms_get_number(platforms);i++) result += HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); return result; } // select section_________________________________________________________________________________________________ // select OpenCL devices by vendor void HGPU_GPU_devices_select_by_vendor(HGPU_GPU_devices** devices,HGPU_GPU_vendor vendor){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); char infobuf[HGPU_MAX_STR_INFO_LENGHT]; cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id GPU_device = (*devices)->devices[i]; HGPU_GPU_error_message(clGetDeviceInfo(GPU_device,CL_DEVICE_VENDOR,sizeof(infobuf),infobuf,NULL),"clGetDeviceInfo failed"); if ((HGPU_convert_vendor_from_str(infobuf)==vendor) || (vendor==HGPU_GPU_vendor_any)) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int j=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id GPU_device = (*devices)->devices[i]; HGPU_GPU_error_message(clGetDeviceInfo(GPU_device,CL_DEVICE_VENDOR,sizeof(infobuf),infobuf,NULL),"clGetDeviceInfo failed"); if ((HGPU_convert_vendor_from_str(infobuf)==vendor) || (vendor==HGPU_GPU_vendor_any)) result->devices[j++] = GPU_device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by OpenCL version void HGPU_GPU_devices_select_by_version(HGPU_GPU_devices** devices,HGPU_GPU_version version){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; HGPU_GPU_version version_gpu = HGPU_GPU_device_get_version(device); if (HGPU_GPU_version_check(version_gpu,version)) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; HGPU_GPU_version version_gpu = HGPU_GPU_device_get_version(device); if (HGPU_GPU_version_check(version_gpu,version)) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by type void HGPU_GPU_devices_select_by_type(HGPU_GPU_devices** devices,cl_device_type device_type){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_device_type dev_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(dev_type),&dev_type,NULL),"clGetDeviceInfo failed"); if (dev_type & device_type) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_device_type dev_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(dev_type),&dev_type,NULL),"clGetDeviceInfo failed"); if (dev_type & device_type) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by device available void HGPU_GPU_devices_select_by_device_and_compiler_available(HGPU_GPU_devices** devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_bool device_available; cl_bool compiler_available; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_AVAILABLE,sizeof(device_available),&device_available,NULL),"clGetDeviceInfo failed"); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_COMPILER_AVAILABLE,sizeof(device_available),&compiler_available,NULL),"clGetDeviceInfo failed"); if (device_available & compiler_available) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_bool device_available; cl_bool compiler_available; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_AVAILABLE,sizeof(device_available),&device_available,NULL),"clGetDeviceInfo failed"); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_COMPILER_AVAILABLE,sizeof(device_available),&compiler_available,NULL),"clGetDeviceInfo failed"); if (device_available & compiler_available) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by global memory size void HGPU_GPU_devices_select_by_global_mem_size(HGPU_GPU_devices** devices,unsigned long int memory_size_in_bytes){ HGPU_GPU_devices* result = (*devices); HGPU_GPU_devices_select_by_parameter_uint(&result,CL_DEVICE_GLOBAL_MEM_SIZE,memory_size_in_bytes); (*devices) = result; } // select OpenCL devices by max allocable memory size void HGPU_GPU_devices_select_by_max_alloc_mem(HGPU_GPU_devices** devices,unsigned long int memory_size_in_bytes){ HGPU_GPU_devices* result = (*devices); HGPU_GPU_devices_select_by_parameter_uint(&result,CL_DEVICE_MAX_MEM_ALLOC_SIZE,memory_size_in_bytes); (*devices) = result; } // select OpenCL devices by uint parameter void HGPU_GPU_devices_select_by_parameter_uint(HGPU_GPU_devices** devices,cl_device_info parameter,unsigned long int min_value){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_ulong device_output; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(device_output),&device_output,NULL),"clGetDeviceInfo failed"); if (device_output>=min_value) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_ulong device_output; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(device_output),&device_output,NULL),"clGetDeviceInfo failed"); if (device_output>=min_value) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices, supporting double precision void HGPU_GPU_devices_select_by_double_precision(HGPU_GPU_devices** devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++) if (HGPU_GPU_device_check_double_precision((*devices)->devices[i])) desired_devices++; HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++) if (HGPU_GPU_device_check_double_precision((*devices)->devices[i])) result->devices[device_index++] = (*devices)->devices[i]; } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } void HGPU_GPU_devices_select_by_highest_version(HGPU_GPU_devices** devices){ HGPU_GPU_version version = HGPU_GPU_devices_get_version_max(*devices); HGPU_GPU_devices_select_by_version(devices,version); } void HGPU_GPU_devices_exclude_device(HGPU_GPU_devices** devices,cl_device_id device){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices){ HGPU_GPU_devices_delete(devices); return; } unsigned int number_of_devices_result = 0; for (unsigned int i=0; i<number_of_devices; i++) if ((*devices)->devices[i]!=device) number_of_devices_result++; if (!number_of_devices_result){ HGPU_GPU_devices_delete(devices); return; } HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices_result); unsigned int j = 0; for (unsigned int i=0; i<number_of_devices; i++) if (((*devices)->devices[i]) && ((*devices)->devices[i]!=device)) result->devices[j++]=(*devices)->devices[i]; HGPU_GPU_devices_delete(devices); (*devices) = result; } // print names of OpenCL devices void HGPU_GPU_devices_print(HGPU_GPU_devices* devices){ if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); for (unsigned int i=0; i<number_of_devices; i++){ char* device_name = HGPU_GPU_device_get_name(devices->devices[i]); printf("Device [%u]: %s\n",i,device_name); free(device_name); } } // print names of platforms of OpenCL devices void HGPU_GPU_devices_print_platforms(HGPU_GPU_devices* devices){ if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); for (unsigned int i=0; i<number_of_devices; i++){ char* platform_name = HGPU_GPU_platform_get_name(HGPU_GPU_device_get_platform(devices->devices[i])); printf("Platform [%u]: %s\n",i,platform_name); free(platform_name); } } // single device___________________________________________________________________________________________________ // get index of OpenCL device by device unsigned int HGPU_GPU_device_get_index_of(cl_device_id device){ unsigned int result = 0; HGPU_GPU_devices* devices = HGPU_GPU_devices_get(); bool flag = true; while ((result<HGPU_GPU_devices_get_number(devices))&&(flag)){ if (devices->devices[result]==device) flag = false; else result++; } HGPU_GPU_devices_delete(&devices); if (flag) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return result; } // get index of OpenCL device by device on platform unsigned int HGPU_GPU_device_get_index_of_on_platform(cl_device_id device){ unsigned int result = 0; cl_platform_id platform = HGPU_GPU_device_get_platform(device); HGPU_GPU_devices* devices = HGPU_GPU_devices_get_on_platform(platform); bool flag = true; while ((result<HGPU_GPU_devices_get_number(devices))&&(flag)){ if (devices->devices[result]==device) flag = false; else result++; } HGPU_GPU_devices_delete(&devices); if (flag) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return result; } // get platform of OpenCL device cl_platform_id HGPU_GPU_device_get_platform(cl_device_id device){ cl_platform_id platform; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_PLATFORM,sizeof(platform),&platform,NULL),"clGetDeviceInfo (get platform) failed"); return platform; } // get index of platform for OpenCL device unsigned int HGPU_GPU_device_get_platform_index_of(cl_device_id device){ unsigned int platform_index = HGPU_GPU_platform_get_index_of(HGPU_GPU_device_get_platform(device)); return platform_index; } // get OpenCL device by index cl_device_id HGPU_GPU_device_get_by_index(unsigned int device_index){ cl_device_id result; HGPU_GPU_devices* devices = HGPU_GPU_devices_get(); if (HGPU_GPU_devices_get_number(devices)<=device_index) { HGPU_GPU_devices_delete(&devices); HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); } result = devices->devices[device_index]; HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device by index cl_device_id HGPU_GPU_device_get_by_index_on_platform(cl_platform_id platform,unsigned int device_index){ cl_device_id result; HGPU_GPU_devices* devices = HGPU_GPU_devices_get_on_platform(platform); if (HGPU_GPU_devices_get_number(devices)<=device_index) { HGPU_GPU_devices_delete(&devices); HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); } result = devices->devices[device_index]; HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device info char* HGPU_GPU_device_get_info_str(cl_device_id device,cl_device_info parameter){ size_t parameter_length; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,0,NULL,&parameter_length),"clGetDeviceInfo failed"); char* result_str = (char*) calloc(parameter_length,sizeof(char)); HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,(parameter_length),result_str,NULL),"clGetDeviceInfo failed"); return result_str; } // get OpenCL device info (unsigned long int) unsigned long int HGPU_GPU_device_get_info_uint(cl_device_id device,cl_device_info parameter){ cl_ulong result = 0; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(result),&result,NULL),"clGetDeviceInfo failed"); return (unsigned long int) result; } char* HGPU_GPU_device_get_name(cl_device_id device){ char* device_name = HGPU_GPU_device_get_info_str(device,CL_DEVICE_NAME); HGPU_string_trim(device_name); return device_name; } // get short info on OpenCL device char* HGPU_GPU_device_get_info_short(cl_device_id device){ char* result = (char*) calloc(HGPU_MAX_STR_INFO_LENGHT,sizeof(char)); char* name = HGPU_GPU_device_get_name(device); char* vendor = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VENDOR); char* profile = HGPU_GPU_device_get_info_str(device,CL_DEVICE_PROFILE); char* version = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VERSION); char* extensions = HGPU_GPU_device_get_info_str(device,CL_DEVICE_EXTENSIONS); unsigned int j = 0; j = sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," Device: %s\n",name); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j,"device's vendor: %s\n",vendor); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," profile: %s\n",profile); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," version: %s\n",version); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," extensions: %s\n",extensions); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j,"max alloc. size: %lu\n",HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_MEM_ALLOC_SIZE)); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," index: [%u] [%u]\n",HGPU_GPU_device_get_index_of(device),HGPU_GPU_device_get_index_of_on_platform(device)); free(extensions); free(version); free(profile); free(vendor); free(name); return result; } // get device's OpenCL version (min of DEVICE and DRIVER version) HGPU_GPU_version HGPU_GPU_device_get_version(cl_device_id device){ HGPU_GPU_version version, version2; char* version_str = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VERSION); version = HGPU_GPU_version_get(version_str); if (version.minor>=1) { char* version_str2 = HGPU_GPU_device_get_info_str(device,CL_DEVICE_OPENCL_C_VERSION); // CL_DEVICE_OPENCL_C_VERSION option only in OpenCL 1.1 version2 = HGPU_GPU_version_get(version_str2); version = HGPU_GPU_version_min(version,version2); free(version_str2); } free(version_str); return version; } // get vendor of OpenCL device HGPU_GPU_vendor HGPU_GPU_device_get_vendor(cl_device_id device){ size_t parameter_length; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_VENDOR,0,NULL,&parameter_length),"clGetDeviceInfo failed"); char* result_str = (char*) calloc(parameter_length+1,sizeof(char)); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_VENDOR,(parameter_length+1),result_str,NULL),"clGetDeviceInfo failed"); HGPU_GPU_vendor vendor = HGPU_convert_vendor_from_str(result_str); free(result_str); return vendor; } // get first available device cl_device_id HGPU_GPU_device_get_first(HGPU_GPU_devices* devices){ if ((!devices) || (!HGPU_GPU_devices_get_number(devices))) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return devices->devices[0]; } // get best available device cl_device_id HGPU_GPU_device_get_best(HGPU_GPU_devices* devices){ if ((!devices) || (!HGPU_GPU_devices_get_number(devices))) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); HGPU_GPU_devices* devs = HGPU_GPU_devices_clone(devices); HGPU_GPU_devices_sort(&devs); cl_device_id result = devs->devices[0]; return result; } // get next available device cl_device_id HGPU_GPU_device_get_next(HGPU_GPU_devices* devices,cl_device_id device){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); unsigned int device_last_index = number_of_devices; for (unsigned int i=0;i<number_of_devices;i++){ if (devices->devices[i]==device){ device_last_index = i; i = number_of_devices; } } if (device_last_index>=(number_of_devices-1)) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return devices->devices[device_last_index+1]; } // check if OpenCL supports double precision bool HGPU_GPU_device_check_double_precision(cl_device_id device){ bool result = false; char device_output[HGPU_MAX_STR_INFO_LENGHT]; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_EXTENSIONS,HGPU_MAX_STR_INFO_LENGHT,&device_output,NULL),"clGetDeviceInfo failed"); HGPU_string_to_lowercase(device_output); if (strstr(device_output,"cl_khr_fp64")) result = true; return result; } // automatically select OpenCL devices according to (HGPU_parameter) parameters HGPU_GPU_devices* HGPU_GPU_devices_select_auto(HGPU_parameter** parameters){ HGPU_GPU_platforms* platforms = NULL; HGPU_GPU_devices* devices = NULL; HGPU_parameter* parameter_device = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_DEVICE); HGPU_parameter* parameter_device_type = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_DEVICE_TYPE); HGPU_parameter* parameter_platform = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_PLATFORM); if (parameter_platform) { unsigned int platform_id = parameter_platform->value_integer; if ((!platform_id) && (strlen(parameter_platform->value_text)>1)){ // get platforms by vendor platforms = HGPU_GPU_platforms_get(); HGPU_GPU_vendor platform_vendor = HGPU_convert_vendor_from_str(parameter_platform->value_text); HGPU_GPU_platforms_select_by_vendor(&platforms,platform_vendor); } else { platforms = HGPU_GPU_platforms_new(1); platforms[0].platforms[0] = HGPU_GPU_platform_get_by_index(platform_id); } devices = HGPU_GPU_devices_get_on_platforms(platforms); } if (parameter_device) { unsigned int device_id = parameter_device->value_integer; if ((!device_id) && (strlen(parameter_device->value_text)>1)){ HGPU_GPU_vendor device_vendor = HGPU_convert_vendor_from_str(parameter_device->value_text); // get devices by vendor if (parameter_platform) HGPU_GPU_devices_select_by_vendor(&devices,device_vendor); else devices = HGPU_GPU_devices_get_by_vendor(device_vendor); } else { devices = HGPU_GPU_devices_new(1); if (parameter_platform) devices[0].devices[0] = HGPU_GPU_device_get_by_index_on_platform(platforms[0].platforms[0],device_id); else devices[0].devices[0] = HGPU_GPU_device_get_by_index(device_id); } } if ((!parameter_platform) && (!parameter_device)) devices = HGPU_GPU_devices_get(); if (parameter_device_type) { if (!strcmp(parameter_device_type->value_text,"GPU")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_GPU); if (!strcmp(parameter_device_type->value_text,"CPU")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_CPU); if (!strcmp(parameter_device_type->value_text,"ACCELERATOR")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_ACCELERATOR); } HGPU_GPU_devices_sort(&devices); return devices; } // get rating of OpenCL device unsigned int HGPU_GPU_device_get_rating(cl_device_id device){ //+++ GPU - 1000 points //+++ Double precision - 100 points //+++ OpenCL major version - 10 points //+++ OpenCL minor version - 1 point unsigned int result = 0; if (device){ cl_device_type device_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(device_type),&device_type,NULL),"clGetDeviceInfo failed"); if (device_type==CL_DEVICE_TYPE_GPU) result += 1000; if (HGPU_GPU_device_check_double_precision(device)) result += 100; HGPU_GPU_version version = HGPU_GPU_device_get_version(device); result += version.major * 10; result += version.minor; } return result; } // sort OpenCL devices by characteristics void HGPU_GPU_devices_sort(HGPU_GPU_devices** devices){ // 1. GPU which supports double precision with highest version of OpenCL // 2. GPU with highest version of OpenCL // 3. device which supports double precision with highest version of OpenCL // 4. any other OpenCL device if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (number_of_devices>0){ unsigned int* rating = (unsigned int*) calloc(number_of_devices,sizeof(unsigned int)); for (unsigned int i=0;i<number_of_devices;i++) rating[i]=HGPU_GPU_device_get_rating((*devices)->devices[i]); // sort by result for (unsigned int i=0;i<(number_of_devices-1);i++){ unsigned int max_rating = rating[i]; unsigned int max_index = i; for (unsigned int j=(i+1);j<number_of_devices;j++){ if (rating[j]>max_rating) { max_index = j; max_rating = rating[j]; } } if (max_index>i) { unsigned int temp_rating = rating[i]; cl_device_id temp_device = (*devices)->devices[i]; (*devices)->devices[i] = (*devices)->devices[max_index]; rating[i] = rating[max_index]; (*devices)->devices[max_index] = temp_device; rating[max_index] = temp_rating; } } } } // automatically select OpenCL device cl_device_id HGPU_GPU_device_select_auto(void){ return HGPU_GPU_device_select_auto_with_parameters(NULL); } // automatically select OpenCL device from devices cl_device_id HGPU_GPU_device_select_auto_from_devices(HGPU_GPU_devices* devices){ return HGPU_GPU_device_get_best(devices); } // automatically select next OpenCL device from devices cl_device_id HGPU_GPU_device_select_auto_from_devices_next(HGPU_GPU_devices* devices,cl_device_id device){ HGPU_GPU_devices* results = HGPU_GPU_devices_clone(devices); HGPU_GPU_devices_sort(&results); cl_device_id result = NULL; bool device_found = false; cl_device_id temp_device; while ((results) && (HGPU_GPU_devices_get_number(results)) && (!device_found)) { temp_device = HGPU_GPU_device_get_first(results); if (temp_device==device) device_found = true; HGPU_GPU_devices_exclude_device(&results,temp_device); } if ((results) && (HGPU_GPU_devices_get_number(results))) result = HGPU_GPU_device_get_first(results); HGPU_GPU_devices_delete(&results); return result; } // automatically select next OpenCL device cl_device_id HGPU_GPU_device_select_auto_next(cl_device_id device){ return HGPU_GPU_device_select_auto_with_parameters_next(device,NULL); } // automatically select OpenCL device with parameters cl_device_id HGPU_GPU_device_select_auto_with_parameters(HGPU_parameter** parameters){ return HGPU_GPU_device_select_auto_with_parameters_next(NULL,parameters); } // automatically select next OpenCL device with parameters cl_device_id HGPU_GPU_device_select_auto_with_parameters_next(cl_device_id device,HGPU_parameter** parameters){ HGPU_GPU_devices* devices = HGPU_GPU_devices_select_auto(parameters); cl_device_id result; if (!device) result = HGPU_GPU_device_get_best(devices); else result = HGPU_GPU_device_select_auto_from_devices_next(devices,device); HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device info HGPU_GPU_device_info HGPU_GPU_device_get_info(cl_device_id device){ HGPU_GPU_device_info result; result.platform_vendor = HGPU_GPU_platform_get_vendor(HGPU_GPU_device_get_platform(device)); result.device_vendor = HGPU_GPU_device_get_vendor(device); result.global_memory_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_GLOBAL_MEM_SIZE); result.local_memory_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_LOCAL_MEM_SIZE); result.max_compute_units = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_COMPUTE_UNITS); result.max_constant_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE); result.max_memory_height = (size_t) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_HEIGHT); result.max_memory_width = (size_t) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_WIDTH); result.max_workgroup_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_WORK_GROUP_SIZE); result.memory_align_factor= HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_WORK_GROUP_SIZE); if (result.max_memory_width) result.max_memory_width = HGPU_GPU_MAX_MEMORY_WIDTH; if (result.max_memory_height) result.max_memory_height = HGPU_GPU_MAX_MEMORY_HEIGHT; #if defined(HGPU_GPU_MAX_INTEL_WORKGROUP_SIZE) if (result.device_vendor == HGPU_GPU_vendor_intel) result.max_workgroup_size = HGPU_GPU_MAX_INTEL_WORKGROUP_SIZE; #endif return result; } // print short info on OpenCL device void HGPU_GPU_device_print_info(cl_device_id device){ char* device_info = HGPU_GPU_device_get_info_short(device); printf("%s",device_info); free(device_info); } // print OpenCL device's name void HGPU_GPU_device_print_name(cl_device_id device){ char* device_name = HGPU_GPU_device_get_name(device); printf("%s",device_name); free(device_name); } // get max memory width unsigned int HGPU_GPU_device_get_max_memory_width(cl_device_id device){ unsigned int result = (unsigned int) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_WIDTH); if (!result) result = 8192; return result; } // get max allocation memory unsigned long int HGPU_GPU_device_get_max_allocation_memory(cl_device_id device){ unsigned long int result = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_MEM_ALLOC_SIZE); return result; }
42.847597
173
0.744015
vadimdi
691113bd555bada5d5032b9618441c3c1bc9d8af
4,144
cpp
C++
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Servo.h> //include the servo library const int trigPin = 11; //connects to the trigger pin on the distance sensor const int echoPin = 12; //connects to the echo pin on the distance sensor const int redPin = 3; //pin to control the red LED inside the RGB LED const int greenPin = 5; //pin to control the green LED inside the RGB LED const int bluePin = 6; //pin to control the blue LED inside the RGB LED const int buzzerPin = 10; //pin that will drive the buzzer float distance = 0; //stores the distance measured by the distance sensor Servo myservo; //create a servo object float getDistance(); void setup() { Serial.begin (9600); //set up a serial connection with the computer pinMode(trigPin, OUTPUT); //the trigger pin will output pulses of electricity pinMode(echoPin, INPUT); //the echo pin will measure the duration of pulses coming back from the distance sensor //set the RGB LED pins to output pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(buzzerPin, OUTPUT); //set the buzzer pin to output myservo.attach(9); //use pin 9 to control the servo } void loop() { distance = getDistance(); //variable to store the distance measured by the sensor Serial.print(distance); //print the distance that was measured Serial.println(" in"); //print units after the distance #ifdef _EXPERIMENT_1_ if (distance < 24) { //if the object is close #else if (distance <= 10) { //if the object is close #endif //make the RGB LED red analogWrite(redPin, 255); analogWrite(greenPin, 0); analogWrite(bluePin, 0); //this code wiggles the servo and beeps the buzzer tone(buzzerPin, 272); //buzz the buzzer pin #ifdef _EXPERIMENT_2_ myservo.write(10); //move the servo to 45 degrees delay(300); //wait 100 milliseconds noTone(buzzerPin); //turn the buzzer off myservo.write(160); //move the servo to 135 degrees delay(300); tone(buzzerPin, 272); //buzz the buzzer pin myservo.write(45); delay(150); noTone(buzzerPin); myservo.write(65); delay(150); #else myservo.write(10); //move the servo to 45 degrees delay(100); //wait 100 milliseconds noTone(buzzerPin); //turn the buzzer off myservo.write(160); //move the servo to 135 degrees delay(100); //wait 100 milliseconds #endif #ifdef _EXPERIMENT_1_ } else if(distance < 40){ #else } else if (10 < distance && distance < 20) { //if the object is a medium distance #endif //make the RGB LED yellow analogWrite(redPin, 255); analogWrite(greenPin, 50); analogWrite(bluePin, 0); } else { //if the object is far away //make the RGB LED green analogWrite(redPin, 0); analogWrite(greenPin, 255); analogWrite(bluePin, 0); } delay(50); //delay 50ms between each reading } //------------------FUNCTIONS------------------------------- //RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR float getDistance() { float echoTime; //variable to store the time it takes for a ping to bounce off an object float calculatedDistance; //variable to store the distance calculated from the echo time //send out an ultrasonic pulse that's 10ms long digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the //pulse to bounce back to the sensor calculatedDistance = echoTime / 148.0; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound) return calculatedDistance; //send back the distance that was calculated }
34.533333
161
0.624759
padlewski
6911c61370affdff725c6a6f147cc296d2b5dfed
3,489
cpp
C++
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
// system includes #include <stdexcept> // project includes #include <jsonserver/JsonServer.h> #include "JsonClientConnection.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/WebSocket.h" #include "Poco/Net/NetException.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerParams.h" #include "Poco/Delegate.h" class WebSocketRequestHandler: public Poco::Net::HTTPRequestHandler { public: WebSocketRequestHandler(Hyperion *hyperion) : _hyperion(hyperion) { } void handleRequest(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response) { try { Poco::Net::WebSocket socket(request, response); std::cout << "New json connection from " << request.clientAddress().toString() << std::endl; JsonClientConnection connection(&socket, _hyperion); // connection.setColorsEvent += Poco::delegate(_hyperion, &Hyperion::setColorsD); // connection.clearEvent += Poco::delegate(_hyperion, &Hyperion::clearD); // connection.clearAllEvent += Poco::delegate(_hyperion, &Hyperion::clearAllD); int result; do { result = connection.processRequest(); } while (result == 0); std::cout << "Connection to " << request.clientAddress().toString() << " closed" << std::endl; // connection.setColorsEvent -= Poco::delegate(_hyperion, &Hyperion::setColorsD); // connection.clearEvent -= Poco::delegate(_hyperion, &Hyperion::clearD); // connection.clearAllEvent -= Poco::delegate(_hyperion, &Hyperion::clearAllD); } catch (Poco::Net::WebSocketException & exc) { std::cout << exc.what() << std::endl; switch (exc.code()) { case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION: response.set("Sec-WebSocket-Version", Poco::Net::WebSocket::WEBSOCKET_VERSION); // fallthrough case Poco::Net::WebSocket::WS_ERR_NO_HANDSHAKE: case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_VERSION: case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_KEY: response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response.setContentLength(0); response.send(); break; } } catch (const std::exception& e) { std::cerr << "[ERROR] handleRequest: " << e.what() << std::endl; } } private: Hyperion * _hyperion; }; class WebSocketRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory { public: WebSocketRequestHandlerFactory(Hyperion *hyperion) : _hyperion(hyperion) { } Poco::Net::HTTPRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) { return new WebSocketRequestHandler(_hyperion); } private: Hyperion * _hyperion; }; JsonServer::JsonServer(Hyperion *hyperion, uint16_t port) : _hyperion(hyperion) { Poco::Net::ServerSocket serverSocket(port); _server = new Poco::Net::HTTPServer(new WebSocketRequestHandlerFactory(_hyperion), serverSocket, new Poco::Net::HTTPServerParams); _server->start(); } JsonServer::~JsonServer() { _server->stop(); delete _server; } uint16_t JsonServer::getPort() const { return _server->port(); }
32.305556
134
0.651476
juanesf
6914aa29492fe85b7864021a19b19a2aade8818e
2,145
hpp
C++
Support/Modules/GSRoot/Point.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/GSRoot/Point.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/GSRoot/Point.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
// ***************************************************************************** // // Point class // // Module: AC // Namespace: - // Contact person: AZS // // SG compatible // // ***************************************************************************** #ifndef POINT_HPP #define POINT_HPP #pragma once // --- Includes ---------------------------------------------------------------- // --- Declarations ------------------------------------------------------------ namespace GS { // --- Class declarations ------------------------------------------------------ // --- Point ------------------------------------------------------------------- template<class TYPE> class Point { private: TYPE x; TYPE y; public: Point (); Point (const TYPE& newX, const TYPE& newY); void Set (const TYPE& newX, const TYPE& newY); TYPE GetX (void) const; TYPE GetY (void) const; void SetX (const TYPE& newX); void SetY (const TYPE& newY); void Offset (const TYPE& deltaX, const TYPE& deltaY); bool operator== (const Point<TYPE>&) const; bool operator!= (const Point<TYPE>&) const; }; // --- Public methods ---------------------------------------------------------- template <class TYPE> Point<TYPE>::Point (): x (0), y (0) { } template <class TYPE> Point<TYPE>::Point (const TYPE& newX, const TYPE& newY): x (newX), y (newY) { } template <class TYPE> void Point<TYPE>::Set (const TYPE& newX, const TYPE& newY) { x = newX; y = newY; } template <class TYPE> TYPE Point<TYPE>::GetX (void) const { return x; } template <class TYPE> TYPE Point<TYPE>::GetY (void) const { return y; } template <class TYPE> void Point<TYPE>::SetX (const TYPE& newX) { x = newX; } template <class TYPE> void Point<TYPE>::SetY (const TYPE& newY) { y = newY; } template <class TYPE> void Point<TYPE>::Offset (const TYPE& deltaX, const TYPE& deltaY) { x += deltaX; y += deltaY; } template <class TYPE> bool Point<TYPE>::operator== (const Point<TYPE>& p) const { return x == p.x && y == p.y; } template <class TYPE> bool Point<TYPE>::operator!= (const Point<TYPE>& p) const { return x != p.x || y != p.y; } } #endif
16.374046
80
0.49324
graphisoft-python
69158c9c357a594c3e78806e318ed2bba85b49da
4,810
cxx
C++
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
4
2020-04-23T12:28:41.000Z
2021-06-07T05:54:16.000Z
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
null
null
null
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
1
2017-06-05T18:00:21.000Z
2017-06-05T18:00:21.000Z
#include "dbdet_curvelet.h" #include <vcl_iostream.h> #include <vcl_fstream.h> #include <vcl_cassert.h> #include <vcl_deque.h> #include <vcl_algorithm.h> //: copy constructor dbdet_curvelet::dbdet_curvelet(const dbdet_curvelet& other) { //the edgels have to copied as links because curvelets are just groupings of the edgels ref_edgel = other.ref_edgel; edgel_chain = other.edgel_chain; //but the curve model has to be deep copied switch(other.curve_model->type) { case dbdet_curve_model::LINEAR: curve_model = new dbdet_linear_curve_model(*(dbdet_linear_curve_model*)other.curve_model); break; case dbdet_curve_model::CC: curve_model = new dbdet_CC_curve_model(*(dbdet_CC_curve_model*)other.curve_model); case dbdet_curve_model::CC2: curve_model = new dbdet_CC_curve_model_new(*(dbdet_CC_curve_model_new*)other.curve_model); case dbdet_curve_model::CC3d: curve_model = new dbdet_CC_curve_model_3d(*(dbdet_CC_curve_model_3d*)other.curve_model); case dbdet_curve_model::ES: curve_model = new dbdet_ES_curve_model(*(dbdet_ES_curve_model*)other.curve_model); default: curve_model=0; //TO DO } forward = other.forward; length = other.length; quality = other.quality; used = other.used; } //: copy constructor with provisions for copying a different curve bundle dbdet_curvelet::dbdet_curvelet(const dbdet_curvelet& other, dbdet_curve_model* cm) { //the edgels have to copied as links because curvelets are just groupings of the edgels ref_edgel = other.ref_edgel; edgel_chain = other.edgel_chain; //do not copy the CB, just assign the ne passed to it curve_model = cm; forward = other.forward; length = other.length; quality = other.quality; used = other.used; } //: destructor dbdet_curvelet::~dbdet_curvelet() { //delete the curve model if (curve_model) delete curve_model; edgel_chain.clear(); } // weighting constants for the heuristic #define alpha3 1.0 #define alpha4 1.0 //: compute properties of this curvelet once formed void dbdet_curvelet::compute_properties(double R, double token_len) { //find out the # of edgels before and after the reference edgel //also find out the length before and after the reference edgel int num_before=0, num_after=0; double Lm=0, Lp=0; bool before_ref = true; for (unsigned i=0; i<edgel_chain.size()-1; i++){ if (before_ref) { Lm += vgl_distance(edgel_chain[i]->pt, edgel_chain[i+1]->pt); num_before++; } else { Lp += vgl_distance(edgel_chain[i]->pt, edgel_chain[i+1]->pt); num_after++; } if (edgel_chain[i+1]==ref_edgel) before_ref = false; } //compute the length of the curvelet (extrinsic length) length = Lm+Lp; //also compute the LG ratio and store as quality //quality = (num_before+num_after)*token_len/length; //new quality measure (1/cost of the compatibility heauristic) quality = 2/(alpha3*R/length + alpha4*length/token_len/edgel_chain.size()); } //: print info to file void dbdet_curvelet::print(vcl_ostream& os) { //first output the edgel chain os << "["; for (unsigned i=0; i< edgel_chain.size(); i++){ os << edgel_chain[i]->id << " "; } os << "] "; //forward/backward tag os << "("; if (forward) os << "F"; else os << "B"; os << ") "; //next output the curve model curve_model->print(os); //then output the other properties os << " " << length << " " << quality << vcl_endl; } //: read info from file void dbdet_curvelet::read(vcl_istream& /*is*/) { //this is not possible without access to the edgemap } vcl_list<dbdet_edgel*> dbdet_curvelet::child_chain() { bool flag=false; vcl_list<dbdet_edgel*> return_chain; for(unsigned i=0;i<edgel_chain.size();i++) { if(flag) return_chain.push_back(edgel_chain[i]); if(edgel_chain[i]->id==ref_edgel->id) flag=true; } return return_chain; } vcl_list<dbdet_edgel*> dbdet_curvelet::parent_chain() { bool flag=true; vcl_list<dbdet_edgel*> return_chain; for(unsigned i=0;i<edgel_chain.size();i++) { if(edgel_chain[i]->id==ref_edgel->id) flag=false; if(flag) return_chain.push_front(edgel_chain[i]); } return return_chain; } ////: does a larger grouping exist already? //dbdet_curvelet* dbdet_curvelet::exists(dbdet_curvelet* cv) //{ // curvelet_list_iter c_it = larger_curvelets.begin(); // for (; c_it != larger_curvelets.end(); c_it++){ // dbdet_curvelet* lcv = (*c_it); // // bool found = true; // for (unsigned j=0; j<lcv->edgel_chain.size(); j++){ // if (cv->edgel_chain[j] != lcv->edgel_chain[j]) // found = false; // } // // if (found) // return lcv; // } // //not found // return 0; //}
26.574586
99
0.673805
yuliangguo
69169830c1ce01e00e1d9551f7e899d2e1cadcd4
346
cc
C++
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "../src/s-approximations.h" using ::testing::ElementsAreArray; namespace { TEST(ApproximationsUtilsTest, GetProgressTest) { std::vector<double> y_new {1, 2, 3, 4, 5}; std::vector<double> y_old {0, 1, 2, 3, 3}; EXPECT_DOUBLE_EQ(2.0, getProgress(y_new, y_old)); } }
18.210526
53
0.66474
vined
69192dd65e8e8a19fafdc420ad72dabcb3b60a6d
11,464
hpp
C++
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
/** * Intersects.hpp * * Copyright 2015 Tony Stone * * 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. * * Created by Tony Stone on 10/6/15. */ #ifndef __GeoFeature_Intersects_Other_Operation_HPP_ #define __GeoFeature_Intersects_Other_Operation_HPP_ #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/variant_fwd.hpp> #include <boost/geometry/strategies/strategies.hpp> #include <boost/geometry/algorithms/intersects.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include "GeometryVariant.hpp" namespace geofeatures { namespace operators { namespace detail { /** * intersects implementation class. */ struct intersects { /** * Internal class to convert from GeometryCollection variant * to the GeometryPtrVariant type. */ struct VariantToPtrVariant : public boost::static_visitor<GeometryPtrVariant> { template <typename T> GeometryPtrVariant operator()(const T & v) const { return GeometryPtrVariant(&v); } }; /** * Internal visitor class for variant access. */ class IntersectsSelfVisitor : public boost::static_visitor<bool> { public: /** * Constructor to initialize the visitor members */ IntersectsSelfVisitor() : variantToPtrVariantVisitor() {} /** * Generic intersects that are implemented by boost */ template <typename T> bool operator()(const T * t) const { return boost::geometry::intersects(*t); } /* * Intersects operation methods specific to 1 type */ bool operator()(const Point * v) const { return false; // A point can't intersect itself } bool operator()(const MultiPoint * v) const { return false; // A multipoint can't intersect itself } bool operator()(const Box * v) const { return false; // A box can't intersect itself } // GeometryCollection intersects bool operator()(const GeometryCollection<> * collection) const { for (auto it = collection->begin(); it != collection->end(); ++it ) { geofeatures::GeometryPtrVariant ptrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, ptrVariant)) { return true; } } return false; } private: VariantToPtrVariant variantToPtrVariantVisitor; }; /** * Internal visitor class for variant access. */ class IntersectsOtherVisitor : public boost::static_visitor<bool> { public: /** * Constructor to initialize the visitor members */ IntersectsOtherVisitor() : variantToPtrVariantVisitor() {} /** * Generic intersects that are implemented by boost */ template <typename T1, typename T2> bool operator()(const T1 * t1, const T2 * t2) const { return boost::geometry::intersects(*t1,*t2); } /* * Intersects operation methods specific to 2 types */ /** * Generic template for MultiType to single type intersects */ template<typename MultiType, typename SingleType> inline bool multiIntersects(const MultiType * multiType, const SingleType * singleType) const { // // If any point in the item in the multi intersects the other geometry, // we have an intersection. // for (auto it = multiType->begin(); it != multiType->end(); it++) { if (boost::geometry::intersects(*it,*singleType)) { return true; } } return false; } bool operator()(const MultiPoint * multiPoint, const Ring * ring) const { return multiIntersects(multiPoint,ring); } bool operator()(const Ring * ring, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,ring); } bool operator()(const Polygon * polygon, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,polygon); } bool operator()(const MultiPoint * multiPoint, const Polygon * polygon) const { return multiIntersects(multiPoint,polygon); } bool operator()(const MultiPoint * multiPoint, const MultiPolygon * multiPolygon) const { return multiIntersects(multiPoint,multiPolygon); } bool operator()(const MultiPolygon * multiPolygon, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,multiPolygon); } bool operator()(const GeometryCollection<> * lhs, const GeometryCollection<> * rhs) const { for (auto it = lhs->begin(); it != lhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); geofeatures::GeometryPtrVariant rhsPtrVariant(rhs); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } for (auto it = rhs->begin(); it != rhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant(lhs); geofeatures::GeometryPtrVariant rhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } template <typename T> bool operator()(const GeometryCollection<> * lhs, const T * rhs) const { geofeatures::GeometryPtrVariant rhsPtrVariant(rhs); for (auto it = lhs->begin(); it != lhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } template <typename T> bool operator()(const T * lhs, const GeometryCollection<> * rhs) const { geofeatures::GeometryPtrVariant lhsPtrVariant(lhs); for (auto it = rhs->begin(); it != rhs->end(); ++it ) { geofeatures::GeometryPtrVariant rhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } private: VariantToPtrVariant variantToPtrVariantVisitor; }; /** * Apply the detail implementation to the variant passed. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T)> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const & variant) { return boost::apply_visitor(IntersectsSelfVisitor(), variant); } /** * Apply the detail implementation to the variants passed. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2)> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant1,boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const & variant2) { return boost::apply_visitor(IntersectsOtherVisitor(), variant1, variant2); } }; } /** * intersect self method. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T)> inline bool intersects(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const & variant) { return detail::intersects::apply(variant); } /** * intersect other method. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2)> inline bool intersects(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const & variant2) { return detail::intersects::apply(variant1, variant2); } } // namespace operators } // namespace geofeatures #endif //__GeoFeature_Intersects_Other_Operation_HPP_
43.097744
167
0.491626
xarvey
691dc3230f62e0fb18cb4241f8918f8e447cb4cf
7,144
hpp
C++
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
6
2021-03-08T15:29:20.000Z
2021-07-04T06:39:23.000Z
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
1
2021-03-25T03:36:57.000Z
2021-03-25T03:36:57.000Z
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
3
2021-03-18T07:32:00.000Z
2021-08-11T09:53:40.000Z
/// \author Jian Wen /// \date 2021/02/02 #pragma once #include "types.hpp" #include <cstddef> /// \brief Assign the pending trips to the vehicles using Insertion Heuristics. /// \param pending_trip_ids A vector holding indices to the pending trips. /// \param trips A vector of all trips. /// \param vehicles A vector of all vehicles. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void assign_trips_through_insertion_heuristics(const std::vector<size_t> &pending_trip_ids, std::vector<Trip> &trips, std::vector<Vehicle> &vehicles, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Assign one single trip to the vehicles using using Insertion Heuristics. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicles A vector of all vehicles. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void assign_trip_through_insertion_heuristics(Trip &trip, const std::vector<Trip> &trips, std::vector<Vehicle> &vehicles, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Compute the cost (time in millisecond) of serving the current waypoints. /// \details The cost of serving all waypoints is defined as the total time taken to drop off each /// of the trips based on the current ordering. uint64_t get_cost_of_waypoints(const std::vector<Waypoint> &waypoints); /// \brief Validate waypoints by checking all constraints. Returns true if valid. bool validate_waypoints(const std::vector<Waypoint> &waypoints, const std::vector<Trip> &trips, const Vehicle &vehicle, uint64_t system_time_ms); /// \brief Compute the time that the trip is picked up knowing pickup index. /// \param pos The current vehicle pose. /// \param waypoints The waypoints that are orignially planned. /// \param pickup_pos The pose for the pickup. /// \param pickup_index The index in the waypoint list where we pick up. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. /// \return A pair. True if the trip can be inserted, together with the pick up time. False /// otherwise. template <typename RouterFunc> std::pair<bool, uint64_t> get_pickup_time(Pos pos, const std::vector<Waypoint> &waypoints, Pos pickup_pos, size_t pickup_index, uint64_t system_time_ms, RouterFunc &router_func); /// \brief The return type of the following function. /// \details If the trip could not be inserted based on the current vehicle status, result is false. /// Otherwise, result is true. The cost_ms is the additional cost in milliseconds required to serve /// this trip, The following indices point to where to insert the pickup and dropoff. struct InsertionResult { bool success = false; size_t vehicle_id; uint64_t cost_ms = std::numeric_limits<uint64_t>::max(); size_t pickup_index; size_t dropoff_index; }; /// \brief Compute the additional cost (time in millisecond) if a vehicle is to serve a trip. /// \see get_cost_of_waypoints has the detialed definition of cost. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicle The vehicle that serves the trip. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> InsertionResult compute_cost_of_inserting_trip_to_vehicle(const Trip &trip, const std::vector<Trip> &trips, const Vehicle &vehicle, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Compute the additional cost knowing pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. /// \return A pair. True if the trip can be inserted, together with the additional cost in seconds. /// False otherwise. template <typename RouterFunc> std::pair<bool, uint64_t> compute_cost_of_inserting_trip_to_vehicle_given_pickup_and_dropoff_indices( const Trip &trip, const std::vector<Trip> &trips, const Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Insert the trip to the vehicle given known pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void insert_trip_to_vehicle(Trip &trip, Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, RouterFunc &router_func); /// \brief Generate a vector of waypoints given known pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \param routing_type The type of the route. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> std::vector<Waypoint> generate_waypoints(const Trip &trip, const Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, RoutingType routing_type, RouterFunc &router_func); // Implementation is put in a separate file for clarity and maintainability. #include "dispatch_impl.hpp"
51.028571
100
0.638438
wenjian0202
691e38ca93768071e24cbf69f255584a2bdbd21d
1,630
cpp
C++
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
#include "BBTranslateFeedbackObject.h" #include "BBVertexBufferObject.h" BBTranslateFeedbackObject::BBTranslateFeedbackObject(int nVertexCount, GLenum hint, GLenum eDrawPrimitiveType) : BBBufferObject() { m_nVertexCount = nVertexCount; m_eDrawPrimitiveType = eDrawPrimitiveType; createTFO(); } void BBTranslateFeedbackObject::bind() { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); // all data of TFO will be written into the buffer glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_Name); glBeginTransformFeedback(m_eDrawPrimitiveType); } void BBTranslateFeedbackObject::unbind() { glEndTransformFeedback(); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); } void BBTranslateFeedbackObject::debug() { BBBufferObject::bind(); // extract from gpu BBVertex *pVertexes = new BBVertex[m_nVertexCount]; glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, sizeof(BBVertex) * m_nVertexCount, pVertexes); if (pVertexes) { for (int i = 0; i < m_nVertexCount; i++) { qDebug() << pVertexes[i].m_fPosition[0] << pVertexes[i].m_fPosition[1] << pVertexes[i].m_fPosition[2]; } } else { qDebug() << "error"; } glUnmapBuffer(m_BufferType); BBBufferObject::unbind(); } GLuint BBTranslateFeedbackObject::createTFO() { glGenTransformFeedbacks(1, &m_TFO); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); m_Name = createBufferObject(m_BufferType, sizeof(BBVertex) * m_nVertexCount, GL_STATIC_DRAW, nullptr); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); return m_TFO; }
29.107143
114
0.725153
xiaoxianrouzhiyou
69244678a6c097ed04b869e4f77fd7482b68c4c2
6,618
cxx
C++
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "teca_index_executive.h" #include "teca_config.h" #include "teca_common.h" #include <string> #include <sstream> #include <iostream> #include <utility> using std::cerr; using std::endl; // -------------------------------------------------------------------------- teca_index_executive::teca_index_executive() : start_index(0), end_index(-1), stride(1) { } // -------------------------------------------------------------------------- void teca_index_executive::set_index(long s) { this->start_index = std::max(0l, s); this->end_index = s; } // -------------------------------------------------------------------------- void teca_index_executive::set_start_index(long s) { this->start_index = std::max(0l, s); } // -------------------------------------------------------------------------- void teca_index_executive::set_end_index(long s) { this->end_index = s; } // -------------------------------------------------------------------------- void teca_index_executive::set_stride(long s) { this->stride = std::max(0l, s); } // -------------------------------------------------------------------------- void teca_index_executive::set_extent(unsigned long *ext) { this->set_extent({ext[0], ext[1], ext[2], ext[3], ext[4], ext[4]}); } // -------------------------------------------------------------------------- void teca_index_executive::set_extent(const std::vector<unsigned long> &ext) { this->extent = ext; } // -------------------------------------------------------------------------- void teca_index_executive::set_bounds(double *bds) { this->set_bounds({bds[0], bds[1], bds[2], bds[3], bds[4], bds[5]}); } // -------------------------------------------------------------------------- void teca_index_executive::set_bounds(const std::vector<double> &bds) { this->bounds = bds; } // -------------------------------------------------------------------------- void teca_index_executive::set_arrays(const std::vector<std::string> &v) { this->arrays = v; } // -------------------------------------------------------------------------- int teca_index_executive::initialize(MPI_Comm comm, const teca_metadata &md) { #if !defined(TECA_HAS_MPI) (void)comm; #endif this->requests.clear(); // locate the keys that enable us to know how many // requests we need to make and what key to use if (md.get("index_initializer_key", this->index_initializer_key)) { TECA_ERROR("No index initializer key has been specified") return -1; } if (md.get("index_request_key", this->index_request_key)) { TECA_ERROR("No index request key has been specified") return -1; } // locate available indices long n_indices = 0; if (md.get(this->index_initializer_key, n_indices)) { TECA_ERROR("metadata is missing the initializer key \"" << this->index_initializer_key << "\"") return -1; } // apply restriction long last = this->end_index >= 0 ? this->end_index : n_indices - 1; long first = ((this->start_index >= 0) && (this->start_index <= last)) ? this->start_index : 0; n_indices = last - first + 1; // partition indices across MPI ranks. each rank // will end up with a unique block of indices // to process. size_t rank = 0; size_t n_ranks = 1; #if defined(TECA_HAS_MPI) int is_init = 0; MPI_Initialized(&is_init); if (is_init) { int tmp = 0; MPI_Comm_size(comm, &tmp); n_ranks = tmp; MPI_Comm_rank(comm, &tmp); rank = tmp; } #endif size_t n_big_blocks = n_indices%n_ranks; size_t block_size = 1; size_t block_start = 0; if (rank < n_big_blocks) { block_size = n_indices/n_ranks + 1; block_start = block_size*rank; } else { block_size = n_indices/n_ranks; block_start = block_size*rank + n_big_blocks; } // consrtuct base request teca_metadata base_req; if (this->bounds.empty()) { if (this->extent.empty()) { std::vector<unsigned long> whole_extent(6, 0l); md.get("whole_extent", whole_extent); base_req.set("extent", whole_extent); } else base_req.set("extent", this->extent); } else base_req.set("bounds", this->bounds); base_req.set("arrays", this->arrays); // apply the base request to local indices. for (size_t i = 0; i < block_size; ++i) { size_t index = i + block_start + first; if ((index % this->stride) == 0) { this->requests.push_back(base_req); this->requests.back().set(this->index_request_key, index); } } // print some info about the set of requests if (this->get_verbose()) cerr << teca_parallel_id() << " teca_index_executive::initialize index_initializer_key=" << this->index_initializer_key << " index_request_key=" << this->index_request_key << " first=" << this->start_index << " last=" << this->end_index << " stride=" << this->stride << endl; return 0; } // -------------------------------------------------------------------------- teca_metadata teca_index_executive::get_next_request() { teca_metadata req; if (!this->requests.empty()) { req = this->requests.back(); this->requests.pop_back(); // print the details of the current request. this is a execution // progress indicator of where the run is at if (this->get_verbose()) { std::vector<unsigned long> ext; req.get("extent", ext); std::vector<double> bds; req.get("bounds", bds); unsigned long index; req.get(this->index_request_key, index); std::ostringstream oss; oss << teca_parallel_id() << " teca_index_executive::get_next_request " << this->index_request_key << "=" << index; if (bds.empty()) { if (!ext.empty()) oss << " extent=" << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5]; } else { oss << " bounds=" << bds[0] << ", " << bds[1] << ", " << bds[2] << ", " << bds[3] << ", " << bds[4] << ", " << bds[5]; } cerr << oss.str() << endl; } } return req; }
28.649351
88
0.487307
Data-Scientist-Wannabe
69264d19724dd12efc8db02ec69470c5bec653b6
19,055
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/utils/funcexp/func_bitwise.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/utils/funcexp/func_bitwise.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/utils/funcexp/func_bitwise.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2014 InfiniDB, Inc. 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** * $Id: func_bitwise.cpp 3616 2013-03-04 14:56:29Z rdempsey $ * * ****************************************************************************/ #include <string> using namespace std; #include "functor_int.h" #include "funchelpers.h" #include "functioncolumn.h" #include "predicateoperator.h" using namespace execplan; #include "rowgroup.h" using namespace rowgroup; #include "errorcodes.h" #include "idberrorinfo.h" #include "errorids.h" using namespace logging; #include "mcs_int64.h" #include "mcs_decimal.h" #include "dataconvert.h" #include "numericliteral.h" using namespace dataconvert; namespace { using namespace funcexp; bool validateBitOperandTypeOrError(execplan::FunctionColumn &col, const Func & func, uint argno) { auto & type = col.functionParms()[argno]->data()->resultType(); if (type.canReturnXInt64()) return false; func.raiseIllegalParameterDataTypeError(type); return true; } template<typename T> datatypes::TUInt64Null ConvertToBitOperand(const T &val) { if (val > static_cast<T>(UINT64_MAX)) return datatypes::TUInt64Null(UINT64_MAX); if (val >= 0) return datatypes::TUInt64Null(static_cast<uint64_t>(val)); if (val < static_cast<T>(INT64_MIN)) return datatypes::TUInt64Null(static_cast<uint64_t>(INT64_MAX)+1); return datatypes::TUInt64Null((uint64_t) (int64_t) val); } static datatypes::TUInt64Null DecimalToBitOperand(Row& row, const execplan::SPTP& parm, const funcexp::Func& thisFunc) { bool tmpIsNull = false; datatypes::Decimal d = parm->data()->getDecimalVal(row, tmpIsNull); if (tmpIsNull) return datatypes::TUInt64Null(); if (parm->data()->resultType().colWidth == datatypes::MAXDECIMALWIDTH) { int128_t val = d.getPosNegRoundedIntegralPart(0).getValue(); return ConvertToBitOperand<int128_t>(val); } return datatypes::TUInt64Null((uint64_t) d.decimal64ToSInt64Round()); } // Functions TypeHolderStd::canReturnXInt64() and GenericToBitOperand() // should be splitted eventually to virtual methods in TypeHandler. // // However, TypeHandler::getBitOperand() would seem to be too specific. // It would be nice to have a more generic functionality in TypeHandler. // // Let's consider having something similar to MariaDB Longlong_hybrid, // which holds a signed/unsigned 64bit value together with a sign flag. // Having TypeHandler::getXInt64Hybrid() would be more useful: // it can be reused for other purposes, not only for bitwise operations. // @bug 4703 - the actual bug was only in the DATETIME case // part of this statement below, but instead of leaving 5 identical // copies of this code, extracted into a single utility function // here. This same method is potentially useful in other methods // and could be extracted into a utility class with its own header // if that is the case - this is left as future exercise datatypes::TUInt64Null GenericToBitOperand( Row& row, const execplan::SPTP& parm, const funcexp::Func& thisFunc, bool temporalRounding) { switch (parm->data()->resultType().colDataType) { case execplan::CalpontSystemCatalog::BIGINT: case execplan::CalpontSystemCatalog::INT: case execplan::CalpontSystemCatalog::MEDINT: case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::SMALLINT: { datatypes::TSInt64Null tmp= parm->data()->toTSInt64Null(row); return tmp.isNull() ? datatypes::TUInt64Null() : datatypes::TUInt64Null((uint64_t) (int64_t) tmp); } case execplan::CalpontSystemCatalog::DOUBLE: case execplan::CalpontSystemCatalog::FLOAT: case execplan::CalpontSystemCatalog::UDOUBLE: case execplan::CalpontSystemCatalog::UFLOAT: { bool tmpIsNull = false; double val = parm->data()->getDoubleVal(row, tmpIsNull); return tmpIsNull ? datatypes::TUInt64Null() : ConvertToBitOperand<double>(round(val)); } case execplan::CalpontSystemCatalog::UBIGINT: case execplan::CalpontSystemCatalog::UINT: case execplan::CalpontSystemCatalog::UMEDINT: case execplan::CalpontSystemCatalog::UTINYINT: case execplan::CalpontSystemCatalog::USMALLINT: return parm->data()->toTUInt64Null(row); case execplan::CalpontSystemCatalog::VARCHAR: case execplan::CalpontSystemCatalog::CHAR: case execplan::CalpontSystemCatalog::TEXT: { bool tmpIsNull = false; const string& str = parm->data()->getStrVal(row, tmpIsNull); if (tmpIsNull) return datatypes::TUInt64Null(); datatypes::DataCondition cnverr; literal::Converter<literal::SignedNumericLiteral> cnv(str, cnverr); cnv.normalize(); return cnv.negative() ? datatypes::TUInt64Null((uint64_t)cnv.toPackedSDecimal<int64_t>(0, cnverr)) : datatypes::TUInt64Null(cnv.toPackedUDecimal<uint64_t>(0, cnverr)); } case execplan::CalpontSystemCatalog::DECIMAL: case execplan::CalpontSystemCatalog::UDECIMAL: return DecimalToBitOperand(row, parm, thisFunc); case execplan::CalpontSystemCatalog::DATE: { bool tmpIsNull = false; int32_t time = parm->data()->getDateIntVal(row, tmpIsNull); if (tmpIsNull) return datatypes::TUInt64Null(); int64_t value = Date(time).convertToMySQLint(); return datatypes::TUInt64Null((uint64_t) value); } case execplan::CalpontSystemCatalog::DATETIME: { bool tmpIsNull = false; int64_t time = parm->data()->getDatetimeIntVal(row, tmpIsNull); if (tmpIsNull) return datatypes::TUInt64Null(); // @bug 4703 - missing year when convering to int DateTime dt(time); int64_t value = dt.convertToMySQLint(); if (temporalRounding && dt.msecond >= 500000) value++; return datatypes::TUInt64Null((uint64_t) value); } case execplan::CalpontSystemCatalog::TIMESTAMP: { bool tmpIsNull = false; int64_t time = parm->data()->getTimestampIntVal(row, tmpIsNull); if (tmpIsNull) return datatypes::TUInt64Null(); TimeStamp dt(time); int64_t value = dt.convertToMySQLint(thisFunc.timeZone()); if (temporalRounding && dt.msecond >= 500000) value++; return datatypes::TUInt64Null((uint64_t) value); } case execplan::CalpontSystemCatalog::TIME: { bool tmpIsNull = false; int64_t time = parm->data()->getTimeIntVal(row, tmpIsNull); Time dt(time); int64_t value = dt.convertToMySQLint(); if (temporalRounding && dt.msecond >= 500000) value < 0 ? value-- : value++; return datatypes::TUInt64Null((uint64_t) value); } default: idbassert(0); // Not possible: checked during the preparation stage. break; } return datatypes::TUInt64Null(); } } namespace funcexp { class BitOperandGeneric: public datatypes::TUInt64Null { public: BitOperandGeneric() { } BitOperandGeneric(Row& row, const execplan::SPTP& parm, const funcexp::Func& thisFunc) :TUInt64Null(GenericToBitOperand(row, parm, thisFunc, true)) { } }; // The shift amount operand in MariaDB does not round temporal values // when sql_mode=TIME_FRAC_ROUND is not set. class BitOperandGenericShiftAmount: public datatypes::TUInt64Null { public: BitOperandGenericShiftAmount() { } BitOperandGenericShiftAmount(Row& row, const execplan::SPTP& parm, const funcexp::Func& thisFunc) :TUInt64Null(GenericToBitOperand(row, parm, thisFunc, false)) { } }; // A functor to return NULL as a bitwise operation result. // Used when an unexpected argument count // is encounteded during the preparation step. class Func_bitwise_null: public Func_BitOp { public: Func_bitwise_null(): Func_BitOp("bitwise") { } int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { isNull = true; return 0; } }; bool Func_BitOp::validateArgCount(execplan::FunctionColumn &col, uint expected) const { static Func_bitwise_null return_null; if (col.functionParms().size() == expected) return false; col.setFunctor(&return_null); return true; } void Func_BitOp::setFunctorByParm(execplan::FunctionColumn &col, const execplan::SPTP& parm, Func_Int & return_uint64_from_uint64, Func_Int & return_uint64_from_sint64, Func_Int & return_uint64_generic) const { if (parm->data()->resultType().isUnsignedInteger()) col.setFunctor(&return_uint64_from_uint64); else if (parm->data()->resultType().isSignedInteger()) col.setFunctor(&return_uint64_from_sint64); else col.setFunctor(&return_uint64_generic); } bool Func_BitOp::fixForBitShift(execplan::FunctionColumn &col, Func_Int & return_uint64_from_uint64, Func_Int & return_uint64_from_sint64, Func_Int & return_uint64_generic) const { if (validateArgCount(col, 2)) return false; // The functor detection is done using functionParms()[0] only. // This is how MariaDB performs it. setFunctorByParm(col, col.functionParms()[0], return_uint64_from_uint64, return_uint64_from_sint64, return_uint64_generic); return validateBitOperandTypeOrError(col, *this, 0) || validateBitOperandTypeOrError(col, *this, 1); } bool Func_BitOp::fixForBitOp2(execplan::FunctionColumn &col, Func_Int & return_uint64_from_uint64_uint64, Func_Int & return_uint64_from_sint64_sint64, Func_Int & return_uint64_generic) const { if (validateArgCount(col, 2)) return false; if (col.functionParms()[0]->data()->resultType().isUnsignedInteger() && col.functionParms()[1]->data()->resultType().isUnsignedInteger()) { col.setFunctor(&return_uint64_from_uint64_uint64); return false; } if (col.functionParms()[0]->data()->resultType().isSignedInteger() && col.functionParms()[1]->data()->resultType().isSignedInteger()) { col.setFunctor(&return_uint64_from_sint64_sint64); return false; } col.setFunctor(&return_uint64_generic); return validateBitOperandTypeOrError(col, *this, 0) || validateBitOperandTypeOrError(col, *this, 1); } // // BITAND // template<class TA, class TB> class Func_bitand_return_uint64: public Func_bitand { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 2); Arg2Lazy<TA, TB> args(row, parm, *this); return (int64_t) (args.a & args.b).nullSafeValue(isNull); } }; bool Func_bitand::fix(execplan::FunctionColumn &col) const { static Func_bitand_return_uint64<ParmTUInt64, ParmTUInt64> return_uint64_from_uint64_uint64; static Func_bitand_return_uint64<ParmTSInt64, ParmTSInt64> return_uint64_from_sint64_sint64; static Func_bitand_return_uint64<BitOperandGeneric, BitOperandGeneric> return_uint64_generic; return fixForBitOp2(col, return_uint64_from_uint64_uint64, return_uint64_from_sint64_sint64, return_uint64_generic); } // // LEFT SHIFT // template<class TA> class Func_leftshift_return_uint64: public Func_leftshift { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 2); Arg2Eager<TA, BitOperandGenericShiftAmount> args(row, parm, *this); return (int64_t) args.a.MariaDBShiftLeft(args.b).nullSafeValue(isNull); } }; bool Func_leftshift::fix(execplan::FunctionColumn &col) const { static Func_leftshift_return_uint64<ParmTUInt64> return_uint64_from_uint64; static Func_leftshift_return_uint64<ParmTSInt64> return_uint64_from_sint64; static Func_leftshift_return_uint64<BitOperandGeneric> return_uint64_generic; return fixForBitShift(col, return_uint64_from_uint64, return_uint64_from_sint64, return_uint64_generic); } // // RIGHT SHIFT // template<class TA> class Func_rightshift_return_uint64: public Func_rightshift { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 2); Arg2Eager<TA, BitOperandGenericShiftAmount> args(row, parm, *this); return (int64_t) args.a.MariaDBShiftRight(args.b).nullSafeValue(isNull); } }; bool Func_rightshift::fix(execplan::FunctionColumn &col) const { static Func_rightshift_return_uint64<ParmTUInt64> return_uint64_from_uint64; static Func_rightshift_return_uint64<ParmTSInt64> return_uint64_from_sint64; static Func_rightshift_return_uint64<BitOperandGeneric> return_uint64_generic; return fixForBitShift(col, return_uint64_from_uint64, return_uint64_from_sint64, return_uint64_generic); } // // BIT OR // uint64_t Func_bitor::getUintVal(rowgroup::Row& row, FunctionParm& fp, bool& isNull, execplan::CalpontSystemCatalog::ColType& op_ct) { return static_cast<uint64_t>(getIntVal(row, fp, isNull, op_ct)); } template<class TA, class TB> class Func_bitor_return_uint64: public Func_bitor { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 2); Arg2Lazy<TA, TB> args(row, parm, *this); return (int64_t) (args.a | args.b).nullSafeValue(isNull); } }; bool Func_bitor::fix(execplan::FunctionColumn &col) const { static Func_bitor_return_uint64<ParmTUInt64, ParmTUInt64> return_uint64_from_uint64_uint64; static Func_bitor_return_uint64<ParmTSInt64, ParmTSInt64> return_uint64_from_sint64_sint64; static Func_bitor_return_uint64<BitOperandGeneric, BitOperandGeneric> return_uint64_generic; return fixForBitOp2(col, return_uint64_from_uint64_uint64, return_uint64_from_sint64_sint64, return_uint64_generic); } // // BIT XOR // template<class TA, class TB> class Func_bitxor_return_uint64: public Func_bitxor { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 2); Arg2Eager<TA, TB> args(row, parm, *this); return (int64_t) (args.a ^ args.b).nullSafeValue(isNull); } }; bool Func_bitxor::fix(execplan::FunctionColumn &col) const { static Func_bitxor_return_uint64<ParmTUInt64, ParmTUInt64> return_uint64_from_uint64_uint64; static Func_bitxor_return_uint64<ParmTSInt64, ParmTSInt64> return_uint64_from_sint64_sint64; static Func_bitxor_return_uint64<BitOperandGeneric, BitOperandGeneric> return_uint64_generic; return fixForBitOp2(col, return_uint64_from_uint64_uint64, return_uint64_from_sint64_sint64, return_uint64_generic); } // // BIT COUNT // inline int64_t bitCount(uint64_t val) { // Refer to Hacker's Delight Chapter 5 // for the bit counting algo used here val = val - ((val >> 1) & 0x5555555555555555); val = (val & 0x3333333333333333) + ((val >> 2) & 0x3333333333333333); val = (val + (val >> 4)) & 0x0F0F0F0F0F0F0F0F; val = val + (val >> 8); val = val + (val >> 16); val = val + (val >> 32); return (int64_t)(val & 0x000000000000007F); } template<class TA> class Func_bit_count_return_uint64: public Func_bit_count { public: int64_t getIntVal(Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& operationColType) override { idbassert(parm.size() == 1); return bitCount((uint64_t) TA(row, parm[0], *this).nullSafeValue(isNull)); } }; bool Func_bit_count::fix(execplan::FunctionColumn &col) const { static Func_bit_count_return_uint64<ParmTUInt64> return_uint64_from_uint64; static Func_bit_count_return_uint64<ParmTSInt64> return_uint64_from_sint64; static Func_bit_count_return_uint64<BitOperandGeneric> return_uint64_generic; if (validateArgCount(col, 1)) return false; setFunctorByParm(col, col.functionParms()[0], return_uint64_from_uint64, return_uint64_from_sint64, return_uint64_generic); return validateBitOperandTypeOrError(col, *this, 0); } } // namespace funcexp // vim:ts=4 sw=4:
33.312937
97
0.639097
zettadb
6926614fb6b20fda97e724ba86ff8030248cdb92
1,265
cpp
C++
src/core/deck_of_cards.cpp
maxkolotilin/Holding-cards
c4a07f44c468b4e47a0e6e9d9c90ca3a885ddd16
[ "MIT" ]
1
2015-06-07T16:09:45.000Z
2015-06-07T16:09:45.000Z
src/core/deck_of_cards.cpp
maxkolotilin/Holding-cards
c4a07f44c468b4e47a0e6e9d9c90ca3a885ddd16
[ "MIT" ]
null
null
null
src/core/deck_of_cards.cpp
maxkolotilin/Holding-cards
c4a07f44c468b4e47a0e6e9d9c90ca3a885ddd16
[ "MIT" ]
null
null
null
/* * Created on 20.03.2015 by Maxim Kolotilin * e-mail: maxkolmail@gmail.com * * Distributed under the Boost Software License, Version 1.0. * http://www.boost.org/LICENSE_1_0.txt * * It's a part of Texas Hold'em project * * Implementation for DeckOfCards.h * */ #include <cstdlib> #include <ctime> #include "deck_of_cards.h" DeckOfCards::DeckOfCards() { current_deck_size = DECK_SIZE; deck.reserve(DECK_SIZE); for (int i = 0; i < DECK_SIZE; ++i) { deck.push_back(new Card(i / Card::NUMBER_OF_SUITS, i % Card::NUMBER_OF_SUITS)); } srand(time(0)); } DeckOfCards::~DeckOfCards() { for (int i = 0; i < DECK_SIZE; ++i) { delete deck[i]; } } void DeckOfCards::shuffle() { for (int i = 0; i < DECK_SIZE; ++i) { int j = rand() % DECK_SIZE; std::swap(deck[i], deck[j]); } current_deck_size = DECK_SIZE; // std::random_shuffle(deck.begin(), deck.end()); } void DeckOfCards::print_deck() const { for (int i = 0; i < DECK_SIZE; ++i) { output << deck[i]->get_full_name() << (((i + 1) % 2) ? '\t' : '\n'); } // output is defined in poker_defs.h } const Card* DeckOfCards::deal_next_card() { return deck[--current_deck_size]; }
20.737705
76
0.590514
maxkolotilin
6926cb35fce3bcef927d6d73a17cb849b534e390
950
cpp
C++
problems/166.Fraction_to_Recurring_Decimal/yin_simulate_nlogn.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/166.Fraction_to_Recurring_Decimal/yin_simulate_nlogn.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/166.Fraction_to_Recurring_Decimal/yin_simulate_nlogn.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
// Simulate // Time Complexity O(nlogn) // Space Complexity O(n) class Solution { public: string fractionToDecimal(int numerator, int denominator) { long long n = numerator, d = denominator; // prevent overflow string res = ""; // sign of result if ((n < 0 && d > 0) || (n > 0 && d < 0)) res += '-'; n = max(n, -n); d = max(d, -d); // integer part res += to_string(n / d); n = n % d; if (n == 0) return res; // decimal part res += "."; n *= 10; unordered_map<long, long> mp; while (n) { int num = n / d; if (mp.find(n) != mp.end()) { res.insert(mp[n], 1, '('); res += ')'; break; } mp[n] = res.size(); res += to_string(num); n = (n % d) * 10; } return res; } };
25.675676
69
0.392632
subramp-prep
6928e167ced08d070afdc700b552d5dd9c6833de
624
cpp
C++
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n, l; cin >> n >> l; vector<int>lanterns(n); for (int i = 0; i < n; ++i) { cin >> lanterns[i]; } sort(lanterns.begin(), lanterns.end()); int maxx = 2*max(lanterns[0], l-lanterns[n-1]); for (int i = 1; i < n; ++i) { maxx=max(maxx, (lanterns[i]-lanterns[i-1])); } cout << maxx/2.0; }
23.111111
72
0.573718
wdjpng
692bf79c7d220200f498c249b7da064afde48f59
1,906
hpp
C++
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The asps Authors. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Modbus PDU Client. #ifndef ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP #define ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP #include <functional> #include <asps/modbus/frame/adu_service.hpp> #include <asps/modbus/pdu/semantic/constant.hpp> #include <asps/modbus/pdu/semantic/data_model.hpp> #include <asps/modbus/pdu/session/client_session.hpp> namespace asps { namespace modbus { namespace pdu { using namespace std::placeholders; // Modbus PDU Client class pdu_client : public client_session_observer { public: pdu_client(frame::adu_service::pointer_type adu = frame::make_tcp_adu()) : adu_(adu) { session_.register_observer(this); adu_->set_handler(std::bind(&pdu_client::read_handler, this, _1)); } virtual ~pdu_client() {} public: void read_coils(uint16_t starting_address, uint16_t quantity_of_coils); void read_discrete_inputs(uint16_t starting_address, uint16_t quantity_of_inputs); public: virtual void on_read_coils(const coils& status) {} virtual void on_read_discrete_inputs(const discrete_inputs& status) {} virtual void on_exception(function_code fc, exception_code ec) {} private: virtual void update_send(const buffer_type& pdu) override; virtual void update_datas(const request::pointer_type& req, const mb_datas& datas) override; virtual void update_exception(const request::pointer_type& req, exception_code ec) override; private: void read_handler(const buffer_type& pdu); protected: frame::adu_service::pointer_type adu_; client_session session_; }; } // pdu } // modbus } // asps #endif // ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP
28.878788
77
0.732424
activesys
692edafe41c3a64de468fbbbc2a38ba867907740
2,086
cpp
C++
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
1
2021-01-14T06:01:02.000Z
2021-01-14T06:01:02.000Z
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
8
2018-03-27T11:47:19.000Z
2018-11-12T06:02:12.000Z
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
2
2020-04-30T09:47:01.000Z
2020-12-03T09:34:08.000Z
/* * [950] X of a Kind in a Deck of Cards * * https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ * * algorithms * Easy (33.02%) * Total Accepted: 7.7K * Total Submissions: 23.2K * Testcase Example: '[1,2,3,4,4,3,2,1]' * * In a deck of cards, each card has an integer written on it. * * Return true if and only if you can choose X >= 2 such that it is possible to * split the entire deck into 1 or more groups of cards, where: * * * Each group has exactly X cards. * All the cards in each group have the same integer. * * * * * Example 1: * * * Input: [1,2,3,4,4,3,2,1] * Output: true * Explanation: Possible partition [1,1],[2,2],[3,3],[4,4] * * * * Example 2: * * * Input: [1,1,1,2,2,2,3,3] * Output: false * Explanation: No possible partition. * * * * Example 3: * * * Input: [1] * Output: false * Explanation: No possible partition. * * * * Example 4: * * * Input: [1,1] * Output: true * Explanation: Possible partition [1,1] * * * * Example 5: * * * Input: [1,1,2,2,2,2] * Output: true * Explanation: Possible partition [1,1],[2,2],[2,2] * * * * * * * * Note: * * * 1 <= deck.length <= 10000 * 0 <= deck[i] < 10000 * * * * * * * * * * * * */ class Solution { public: bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int, int> count; for (int d : deck) { count[d]++; } unordered_set<int> ocs; int mino = 10000; for (auto& e: count) { mino = min(mino, e.second); ocs.insert(e.second); } if (mino == 1) { return false; } for (int i = 2; i <= mino; i++) { if (all_divide(ocs, i)) { return true; } } return false; } private: bool all_divide(unordered_set<int>& ocs, int i) { for (int o : ocs) { if (o % i != 0) { return false; } } return true; } };
16.555556
79
0.490892
nettee
69327c89e8e8109949bbeecf1eff31b65c76f042
2,114
cpp
C++
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
3
2021-10-10T11:12:03.000Z
2021-11-04T16:46:57.000Z
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
#include <specific/stypes.h> #include "objects.h" #include "lara.h" #include "lot.h" #include "types.h" #define MAX_RAPTORS 5 #define LARA_TOO_CLOSE SQUARE(WALL_L * 4) int16_t RaptorItem[3] = { NO_ITEM, NO_ITEM, NO_ITEM }; void RaptorEmitterControl(int16_t item_num) { auto item = &items[item_num]; if (!(item->active) || item->timer <= 0) return; if (RaptorItem[0] == NO_ITEM) { for (int target_number = 0, i = 0; target_number < level_items; ++target_number) { auto target = &items[target_number]; if (target->object_number == RAPTOR && target->ai_bits == MODIFY) RaptorItem[i++] = target_number; if (i > 2) return; } return; } if (items[RaptorItem[0]].data != nullptr && items[RaptorItem[1]].data != nullptr && items[RaptorItem[2]].data != nullptr) return; int z = lara_item->pos.z_pos - item->pos.z_pos, x = lara_item->pos.x_pos - item->pos.x_pos, distance = (z * z) + (x * x); if (distance < LARA_TOO_CLOSE) return; if (item->item_flags[0] <= 0) { item->item_flags[0] = 255; item->timer -= 30; } else { --item->item_flags[0]; return; } int raptor_num = 0; for (int i = 0; i < 3; ++i, ++raptor_num) if (!items[RaptorItem[i]].data) break; auto raptor = &items[RaptorItem[raptor_num]]; raptor->pos = item->pos; raptor->anim_number = objects[raptor->object_number].anim_index; raptor->frame_number = anims[raptor->anim_number].frame_base; raptor->current_anim_state = raptor->goal_anim_state = anims[raptor->anim_number].current_anim_state; raptor->required_anim_state = 0; raptor->flags &= ~(ONESHOT | KILLED_ITEM | INVISIBLE); raptor->data = 0; raptor->status = ACTIVE; raptor->mesh_bits = 0xffffffff; raptor->hit_points = objects[raptor->object_number].hit_points; raptor->collidable = 1; if (raptor->active) RemoveActiveItem(RaptorItem[raptor_num]); AddActiveItem(RaptorItem[raptor_num]); ItemNewRoom(RaptorItem[raptor_num], item->room_number); EnableBaddieAI(RaptorItem[raptor_num], 1); } void InitialiseRaptorEmitter(int16_t item_number) { items[item_number].item_flags[0] = (item_number & 0x3) * 96; }
24.022727
122
0.685904
Tonyx97
6934c1945f8a1f4015897ef2f9f40e73e5587b80
2,823
cc
C++
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
#include "lrucache_api.h" // posix header #include <arpa/inet.h> #include <sys/socket.h> #include <thread> #include <gtest/gtest.h> using std::thread; using namespace AtsPluginUtils; namespace AtsPluginUtils { constexpr int TEST_TYPE = 42; template<> struct CacheValue<static_cast<CACHE_VALUE_TYPE>(TEST_TYPE)> { int value; CacheValue() = default; }; using testCache = LRUC::ScalableLRUCache<int, CacheValue<static_cast<CACHE_VALUE_TYPE>(TEST_TYPE)>>; } // namespace AtsPluginUtils /** * create_IpAddress is a callable object taking IPv4 address as const char* and returns IpAddress * */ auto create_IpAddress = [](auto ipv4) -> IpAddress { sockaddr_in socket; socket.sin_family = AF_INET; socket.sin_port = 42; if (inet_pton(AF_INET, ipv4, &socket.sin_addr) == 1) { IpAddress ipa{(sockaddr*)& socket}; return ipa; } return IpAddress{}; }; /** * singletonTest tests the cache instances returned from different DSO * point to the same memory address. * Thus, the inserted key/value from one DSO can be retrieved from another DSO. * */ TEST(LRUcacheSingletonTest, singletonTest) { thread t1([] {init_cache1();}); thread t2([] {init_cache2();}); t1.join(); t2.join(); const char* ip1 = "192.168.1.1"; const char* ip2 = "192.168.1.2"; auto key1 = create_IpAddress(ip1); auto key2 = create_IpAddress(ip2); constexpr auto ts1 = 1'629'834'401; constexpr auto ts2 = 1'629'834'402; AtsPluginUtils::CacheValue<AtsPluginUtils::CACHE_VALUE_TYPE::TIME_ENTITY_LOOKUP_INFO> value1; AtsPluginUtils::CacheValue<AtsPluginUtils::CACHE_VALUE_TYPE::TIME_ENTITY_LOOKUP_INFO> value2; value1.expiryTs = ts1; value2.expiryTs = ts2; cache1_insert(key1, value1); auto retrieved_value1 = cache2_find(key1); EXPECT_EQ(retrieved_value1.expiryTs, ts1); cache2_insert(key2, value2); auto retrieved_value2 = cache1_find(key2); EXPECT_EQ(retrieved_value2.expiryTs, ts2); auto& cache_1 = get_cache1(); // retrieve cache from liblrucache1.so auto& cache_2 = get_cache2(); // retrieve cache from liblrucache2.so EXPECT_EQ(cache_1.capacity(), magic_cache_size); EXPECT_EQ(cache_1.capacity(), cache_2.capacity()); ASSERT_EQ(&cache_1, &cache_2); } /** * differentCacheValueTypeTest tests the cache insert key with different value type. * */ TEST(LRUcacheSingletonTest, differentCacheValueTypeTest) { auto cache = AtsPluginUtils::testCache{42, 4}; constexpr auto val = 1'629'834'401; AtsPluginUtils::CacheValue<static_cast<AtsPluginUtils::CACHE_VALUE_TYPE>(AtsPluginUtils::TEST_TYPE)> value; value.value = val; cache.insert(42, value); AtsPluginUtils::testCache::ConstAccessor ca; EXPECT_EQ(cache.find(ca, 42), true); EXPECT_EQ(ca->value, val); ASSERT_EQ(cache.size(), 1); EXPECT_EQ(cache.erase(42), 1); ASSERT_EQ(cache.size(), 0); }
26.885714
109
0.72972
vsdmars
693764b377374707b669ae6cd44e739a77dc6693
4,454
cpp
C++
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file didyoumean.cpp ** \verbatim ** Top contributors (to current version): ** Kshitij Bansal, Tim King, Clark Barrett ** This file is part of the CVC4 project. ** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief did-you-mean style suggestions ** ** ``What do you mean? I don't understand.'' An attempt to be more ** helpful than that. Similar to one in git. ** ** There are no dependencies on CVC4 (except namespace). **/ #include "options/didyoumean.h" #include <iostream> #include <set> #include <sstream> #include <string> #include <vector> namespace CVC4 { std::vector<std::string> DidYouMean::getMatch(std::string input) { /** Magic numbers */ const int similarityThreshold = 7; const unsigned numMatchesThreshold = 10; typedef std::set<std::pair<int, std::string> > ScoreSet; ScoreSet scores; std::vector<std::string> ret; for (Words::const_iterator it = d_words.begin(); it != d_words.end(); ++it) { std::string s = (*it); if (s == input) { // if input matches AS-IS just return that ret.push_back(s); return ret; } int score; if (s.compare(0, input.size(), input) == 0) { score = 0; } else { score = editDistance(input, s) + 1; } scores.insert(make_pair(score, s)); } int min_score = scores.begin()->first; for (ScoreSet::const_iterator i = scores.begin(); i != scores.end(); ++i) { // add if score is overall not too big, and also not much close to // the score of the best suggestion if (i->first < similarityThreshold && i->first <= min_score + 1) { ret.push_back(i->second); #ifdef DIDYOUMEAN_DEBUG cout << i->second << ": " << i->first << std::endl; #endif } } if (ret.size() > numMatchesThreshold) { ret.resize(numMatchesThreshold); } return ret; } int DidYouMean::editDistance(const std::string& a, const std::string& b) { // input string: a // desired string: b const int swapCost = 0; const int substituteCost = 2; const int addCost = 1; const int deleteCost = 3; const int switchCaseCost = 0; int len1 = a.size(); int len2 = b.size(); int* C[3]; int ii; for (ii = 0; ii < 3; ++ii) { C[ii] = new int[len2 + 1]; } // int C[3][len2+1]; // cost for (int j = 0; j <= len2; ++j) { C[0][j] = j * addCost; } for (int i = 1; i <= len1; ++i) { int cur = i % 3; int prv = (i + 2) % 3; int pr2 = (i + 1) % 3; C[cur][0] = i * deleteCost; for (int j = 1; j <= len2; ++j) { C[cur][j] = 100000000; // INF if (a[i - 1] == b[j - 1]) { // match C[cur][j] = std::min(C[cur][j], C[prv][j - 1]); } else if (tolower(a[i - 1]) == tolower(b[j - 1])) { // switch case C[cur][j] = std::min(C[cur][j], C[prv][j - 1] + switchCaseCost); } else { // substitute C[cur][j] = std::min(C[cur][j], C[prv][j - 1] + substituteCost); } // swap if (i >= 2 && j >= 2 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) { C[cur][j] = std::min(C[cur][j], C[pr2][j - 2] + swapCost); } // add C[cur][j] = std::min(C[cur][j], C[cur][j - 1] + addCost); // delete C[cur][j] = std::min(C[cur][j], C[prv][j] + deleteCost); #ifdef DIDYOUMEAN_DEBUG1 std::cout << "C[" << cur << "][" << 0 << "] = " << C[cur][0] << std::endl; #endif } } int result = C[len1 % 3][len2]; for (ii = 0; ii < 3; ++ii) { delete[] C[ii]; } return result; } std::string DidYouMean::getMatchAsString(std::string input, int prefixNewLines, int suffixNewLines) { std::vector<std::string> matches = getMatch(input); std::ostringstream oss; if (matches.size() > 0) { while (prefixNewLines-- > 0) { oss << std::endl; } if (matches.size() == 1) { oss << "Did you mean this?"; } else { oss << "Did you mean any of these?"; } for (unsigned i = 0; i < matches.size(); ++i) { oss << "\n " << matches[i]; } while (suffixNewLines-- > 0) { oss << std::endl; } } return oss.str(); } } /* CVC4 namespace */
27.493827
80
0.540413
FabianWolff
69386a6d2df7d85712ee8d58045a6962d2181bb6
719
cpp
C++
baekjoon/6217/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
4
2020-02-02T08:34:46.000Z
2021-10-01T11:21:17.000Z
baekjoon/6217/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
1
2021-09-04T14:03:50.000Z
2021-09-04T14:03:50.000Z
baekjoon/6217/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(void){ int n, i, h, r; scanf("%d %d %d %d", &n, &i, &h, &r); vector<pair<int, int>> v; vector<pair<int, int>> vq; for(int a=0;a<r;a++){ int q, p; scanf("%d %d", &q, &p); if(q > p) swap(q, p); if(q+1 < p){ vq.emplace_back(q+1, p); } } sort(vq.begin(), vq.end()); vq.erase(unique(vq.begin(), vq.end()), vq.end()); for(auto c : vq){ v.emplace_back(c.first, 0); v.emplace_back(c.second, 1); } sort(v.begin(), v.end()); int cnt = 0; int vp = 0; for(int a=1;a<=n;a++){ for(;vp<(int)v.size()&&a == v[vp].first;vp++){ if(v[vp].second) cnt--; else cnt++; } printf("%d\n", h-cnt); } return 0; }
20.542857
53
0.493741
qilip
693dffeecbf76175ab9b9b0ba17420ca01a97e22
3,044
cpp
C++
clang/test/ClangScanDeps/modules-full.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
158
2016-07-21T10:45:05.000Z
2022-03-25T00:56:20.000Z
clang/test/ClangScanDeps/modules-full.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
35
2016-07-25T01:23:07.000Z
2021-09-27T16:05:50.000Z
clang/test/ClangScanDeps/modules-full.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
62
2016-08-29T17:28:11.000Z
2021-12-29T17:55:58.000Z
// RUN: rm -rf %t.dir // RUN: rm -rf %t.cdb // RUN: rm -rf %t.module-cache // RUN: mkdir -p %t.dir // RUN: cp %s %t.dir/modules_cdb_input.cpp // RUN: cp %s %t.dir/modules_cdb_input2.cpp // RUN: mkdir %t.dir/Inputs // RUN: cp %S/Inputs/header.h %t.dir/Inputs/header.h // RUN: cp %S/Inputs/header2.h %t.dir/Inputs/header2.h // RUN: cp %S/Inputs/module.modulemap %t.dir/Inputs/module.modulemap // RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/modules_cdb.json > %t.cdb // // RUN: echo %t.dir > %t.result // RUN: clang-scan-deps -compilation-database %t.cdb -j 1 \ // RUN: -mode preprocess-minimized-sources -format experimental-full >> %t.result // RUN: cat %t.result | FileCheck --check-prefixes=CHECK %s // FIXME: Backslash issues. // XFAIL: system-windows #include "header.h" // CHECK: [[PREFIX:(.*[/\\])+[a-zA-Z0-9.-]+]] // CHECK-NEXT: { // CHECK-NEXT: "clang-context-hash": "[[CONTEXT_HASH:[A-Z0-9]+]]", // CHECK-NEXT: "clang-module-deps": [ // CHECK-NEXT: "header1" // CHECK-NEXT: ], // CHECK-NEXT: "clang-modules": [ // CHECK-NEXT: { // CHECK-NEXT: "clang-module-deps": [ // CHECK-NEXT: "header2" // CHECK-NEXT: ], // CHECK-NEXT: "clang-modulemap-file": "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap", // CHECK-NEXT: "file-deps": [ // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}header.h", // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap" // CHECK-NEXT: ], // CHECK-NEXT: "name": "header1" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "clang-module-deps": [], // CHECK-NEXT: "clang-modulemap-file": "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap", // CHECK-NEXT: "file-deps": [ // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}header2.h", // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap" // CHECK-NEXT: ], // CHECK-NEXT: "name": "header2" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "file-deps": [ // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}modules_cdb_input2.cpp" // CHECK-NEXT: ], // CHECK-NEXT: "input-file": "[[PREFIX]]{{[/\\]}}modules_cdb_input2.cpp" // CHECK-NEXT:}, // CHECK-NEXT:{ // CHECK-NOT: "clang-context-hash": "[[CONTEXT_HASH]]", // CHECK-NEXT: "clang-context-hash": "{{[A-Z0-9]+}}", // CHECK-NEXT: "clang-module-deps": [ // CHECK-NEXT: "header1" // CHECK-NEXT: ], // CHECK-NEXT: "clang-modules": [ // CHECK-NEXT: { // CHECK-NEXT: "clang-module-deps": [], // CHECK-NEXT: "clang-modulemap-file": "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap", // CHECK-NEXT: "file-deps": [ // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}header.h", // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}Inputs{{[/\\]}}module.modulemap" // CHECK-NEXT: ], // CHECK-NEXT: "name": "header1" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "file-deps": [ // CHECK-NEXT: "[[PREFIX]]{{[/\\]}}modules_cdb_input.cpp" // CHECK-NEXT: ], // CHECK-NEXT: "input-file": "[[PREFIX]]{{[/\\]}}modules_cdb_input.cpp" // CHECK-NEXT:},
39.025641
97
0.554534
dan-zheng
6943a049660ee3277364c015dfb829533683e515
7,691
cc
C++
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
2
2017-02-23T09:55:54.000Z
2017-02-23T10:06:32.000Z
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
null
null
null
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
null
null
null
/** Copyright (c) 2017 Vicente Romero. All rights reserved. Licensed under the MIT License. See LICENSE file in the project root for full license information. */ #include <cstdio> #include <cstring> #include <string> #include "compress.h" #include "constants.h" #include "decompress.h" using namespace std; struct ExecConfig { bool help_opt; bool decompress_opt; bool stdout_opt; bool force_opt; bool keep_opt; bool version_opt; bool license_opt; string in_file_name; string out_file_name; FILE *in_file; FILE *out_file; ExecConfig() { help_opt = false; decompress_opt = false; stdout_opt = false; force_opt = false; keep_opt = false; version_opt = false; license_opt = false; in_file = stdin; out_file = stdout; } ~ExecConfig() { if((in_file != nullptr) && (in_file != stdin)) { fclose(in_file); } if((out_file != nullptr) && (out_file != stdout)) { fclose(out_file); } } }; static const char *kZjumpCompressedExt = ".zjump"; static const char *kZjumpDecompressedExt = ".orig"; static void DisplayVersionNumber() { uint32_t major = kZjumpVersion / 10000; uint32_t minor = (kZjumpVersion / 100) % 100; uint32_t patch = kZjumpVersion % 100; fprintf(stderr, "zjump %u.%u.%u\n", major, minor, patch); } static void DisplayLicense() { fprintf(stderr, "Copyright (c) 2017 Vicente Romero. All rights reserved.\n" "Licensed under the MIT License. See LICENSE file, which is included in the\n" "zjump source distribution, for full license information.\n" ); } static void Usage(const char *name) { fprintf(stderr, "zjump, a data compressor/decompressor\n" "\n" "Usage: %s [OPTIONS] [FILE]\n" "\n" " -c, --stdout Write on standard output\n" " -d, --decompress Decompress FILE\n" " -f, --force Force to overwrite the output file\n" " -h, --help Output this help and exit\n" " -k, --keep Keep the input file (do not delete it)\n" " -L, --license Display software license\n" " -V, --version Display version number\n" "\n" "If no FILE is given, zjump compresses or decompresses\n" "from standard input to standard output." "\n", name); } static void SetOutputFileName(ExecConfig* config) { if(config->stdout_opt || (config->in_file_name.empty())) { return; } if(config->decompress_opt) { size_t last_dot = config->in_file_name.find_last_of('.'); if( (last_dot == string::npos) || (config->in_file_name.compare(last_dot, string::npos, kZjumpCompressedExt) != 0)) { config->out_file_name = config->in_file_name + kZjumpDecompressedExt; } else { config->out_file_name = config->in_file_name.substr(0, last_dot); } } else { config->out_file_name = config->in_file_name + kZjumpCompressedExt; } } static int ParseOptions(int argc, char **argv, ExecConfig* config) { for(int i=1; i<argc; ++i) { if((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "--stdout") == 0)) { config->stdout_opt = true; } else if((strcmp(argv[i], "-d") == 0) || (strcmp(argv[i], "--decompress") == 0)) { config->decompress_opt = true; } else if((strcmp(argv[i], "-f") == 0) || (strcmp(argv[i], "--force") == 0)) { config->force_opt = true; } else if((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0)) { config->help_opt = true; } else if((strcmp(argv[i], "-k") == 0) || (strcmp(argv[i], "--keep") == 0)) { config->keep_opt = true; } else if((strcmp(argv[i], "-L") == 0) || (strcmp(argv[i], "--license") == 0)) { config->license_opt = true; } else if((strcmp(argv[i], "-V") == 0) || (strcmp(argv[i], "--version") == 0)) { config->version_opt = true; } else if(argv[i][0] == '-') { fprintf(stderr, "Unrecognized option: '%s'\n", argv[i]); } else { return i; } } return argc; } static ZjumpErrorCode ValidateOptions(int argc, char **argv, int last_opt, ExecConfig* config) { if(config->help_opt) { return ZJUMP_NO_ERROR; } int last_args = argc - last_opt; if(last_args > 1) { fprintf(stderr, "Incorrect arguments. Use -h to display more information\n"); return ZJUMP_ERROR_ARGUMENT; } else if(last_args == 1) { config->in_file_name = argv[last_opt]; SetOutputFileName(config); } return ZJUMP_NO_ERROR; } static bool FileExists(const char* file_name) { FILE *file = fopen(file_name, "rb"); if(file == nullptr) { return false; } else { fclose(file); return true; } } static ZjumpErrorCode ValidateOutput(const ExecConfig& config) { if(config.force_opt) { return ZJUMP_NO_ERROR; } if(config.out_file_name.empty()) { return ZJUMP_NO_ERROR; } const char *out_file_name = config.out_file_name.c_str(); if(FileExists(out_file_name)) { fprintf(stderr, "Output file %s already exists.\n", out_file_name); return ZJUMP_ERROR_FILE; } return ZJUMP_NO_ERROR; } static ZjumpErrorCode OpenFiles(ExecConfig* config) { if(!config->in_file_name.empty()) { const char *in_file_name = config->in_file_name.c_str(); config->in_file = fopen(in_file_name, "rb"); if(config->in_file == nullptr) { perror(in_file_name); return ZJUMP_ERROR_FILE; } } if(!config->out_file_name.empty()) { const char *out_file_name = config->out_file_name.c_str(); config->out_file = fopen(out_file_name, "wb"); if(config->out_file == nullptr) { perror(out_file_name); return ZJUMP_ERROR_FILE; } } return ZJUMP_NO_ERROR; } static ZjumpErrorCode RemoveInput(const ExecConfig& config) { if(config.keep_opt) { return ZJUMP_NO_ERROR; } if(config.in_file == stdin) { return ZJUMP_NO_ERROR; } const char *in_file_name = config.in_file_name.c_str(); if(remove(in_file_name) != 0) { perror(in_file_name); return ZJUMP_ERROR_FILE; } return ZJUMP_NO_ERROR; } int main(int argc, char **argv) { ExecConfig config; int last_opt = ParseOptions(argc, argv, &config); int ret_code = ValidateOptions(argc, argv, last_opt, &config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } if(config.version_opt || config.license_opt) { DisplayVersionNumber(); DisplayLicense(); return ZJUMP_NO_ERROR; } if(config.help_opt) { Usage(argv[0]); return ZJUMP_NO_ERROR; } ret_code = ValidateOutput(config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } ret_code = OpenFiles(&config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } if(config.decompress_opt) { Decompressor decompressor; ret_code = decompressor.Decompress(config.in_file, config.out_file); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } } else { Compressor compressor; ret_code = compressor.Compress(config.in_file, config.out_file); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } } ret_code = RemoveInput(config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } return ZJUMP_NO_ERROR; }
27.467857
96
0.593421
vteromero
69449ea720c73b0352bf124099774276b9843361
1,410
cpp
C++
engine/conversion/source/ArtifactDumper.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/conversion/source/ArtifactDumper.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/conversion/source/ArtifactDumper.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include <sstream> #include "ArtifactDumper.hpp" #include "Conversion.hpp" #include "ItemDumper.hpp" #include "TextKeys.hpp" using namespace std; ArtifactDumper::ArtifactDumper(const ItemMap& new_item_map, const GenerationValuesMap& new_igv_map, const uint new_num_cols) : item_map(new_item_map), igv_map(new_igv_map), num_cols(new_num_cols) { } // Loop through all the items in the game, and display info for artifacts. string ArtifactDumper::str() const { ostringstream ss; ss << String::centre(StringTable::get(TextKeys::GENERATED_ARTIFACTS), num_cols) << endl << endl; ss << get_artifacts() << endl; ss << endl; return ss.str(); } string ArtifactDumper::get_artifacts() const { ostringstream ss; for (const auto& item_pair : item_map) { ItemPtr item = item_pair.second; if (item != nullptr && item->get_artifact()) { auto igv_it = igv_map.find(item->get_base_id()); // Ensure we only show artifacts that have already been generated. if (igv_it != igv_map.end() && igv_it->second.is_maximum_reached()) { ItemDumper item_dumper(nullptr, item, false); // Ignore blindness checks because we're checking on globally generated // values, not what's in the creature's equipment or inventory. item_dumper.set_ignore_blindness_checks(true); ss << item_dumper.str(); } } } return ss.str(); }
26.111111
124
0.690071
sidav
6944e8a081f3a002f6638a7265f8665b6a7db528
3,368
cpp
C++
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
/* * stream.cpp * * Created on: 9. 1. 2021 * Author: ondra */ #include "stream.h" #include "async_provider.h" namespace userver { std::string_view SocketStream::read() { std::string_view out; if (curbuff.empty()) { if (!eof) { if (rdbuff.empty()) rdbuff.resize(1000); int sz = sock->read(rdbuff.data(), rdbuff.size()); if (sz == 0) { eof = true; } else { if (sz == static_cast<int>(rdbuff.size())) rdbuff.resize(sz*3/2); out = rdbuff; out = out.substr(0, sz); } } } else { std::swap(out, curbuff); } return out; } std::size_t SocketStream::maxWrBufferSize = 65536; void SocketStream::putBack(const std::string_view &pb) { curbuff = pb; } void SocketStream::write(const std::string_view &data) { wrbuff.append(data); if (wrbuff.size() >= wrbufflimit) { flush_lk(); } } bool SocketStream::timeouted() const { return sock->timeouted(); } void SocketStream::closeOutput() { flush_lk(); sock->closeOutput(); } void SocketStream::closeInput() { sock->closeInput(); } void SocketStream::flush() { flush_lk(); } ISocket& SocketStream::getSocket() const { return *sock; } bool SocketStream::writeNB(const std::string_view &data) { wrbuff.append(data); return (wrbuff.size() >= wrbufflimit); } void SocketStream::flushAsync(const std::string_view &data, bool firstCall, CallbackT<void(bool)> &&fn) { if (data.empty()) { getCurrentAsyncProvider().runAsync([fn = std::move(fn)] { fn(true); }); } else { sock->write(data.data(), data.size(), [this, data, firstCall, fn = std::move(fn)](int r) mutable { if (r <= 0) { wrbuff.clear(); fn(false); } else if (static_cast<std::size_t>(r) == data.size()) { wrbufflimit = std::min(wrbufflimit * 3 / 2, maxWrBufferSize); wrbuff.clear(); fn(true); } else { if (!firstCall) wrbufflimit = (r * 2 + 2) / 3 ; flushAsync(data.substr(r), false, std::move(fn)); } }); } } void SocketStream::flushAsync(CallbackT<void(bool)> &&fn) { if (wrbuff.empty()) { getCurrentAsyncProvider().runAsync([fn = std::move(fn)] { fn(true); }); } else { std::string_view s(wrbuff); flushAsync(s, true, std::move(fn)); } } void SocketStream::flush_lk() { std::string_view s(wrbuff); if (!s.empty()) { unsigned int wx = sock->write(s.data(),s.length()); bool rep = wx < s.length(); while (rep) { s = s.substr(wx); wx = sock->write(s.data(),s.length()); rep = wx < s.length(); if (rep && wx < wrbufflimit) { wrbufflimit = (wx * 2+2) / 3; } } wrbufflimit = std::min(wrbufflimit *3/2, maxWrBufferSize); wrbuff.clear(); } } void SocketStream::readAsync(CallbackT<void(const std::string_view &data)> &&fn) { std::string_view out; if (curbuff.empty() && !eof) { if (rdbuff.empty()) rdbuff.resize(1000); sock->read(rdbuff.data(), rdbuff.size(), [this, fn = std::move(fn)](int sz){ std::string_view out; if (sz == 0) { eof = true; } else { if (sz == static_cast<int>(rdbuff.size())) rdbuff.resize(sz*3/2); out = rdbuff; out = out.substr(0, sz); } fn(out); }); } else { std::swap(out,curbuff); getCurrentAsyncProvider().runAsync([fn = std::move(fn), out](){ fn(out); }); } } std::size_t SocketStream::getOutputBufferSize() const { return wrbufflimit; } void SocketStream::clearTimeout() { sock->clearTimeout(); eof = false; } }
20.662577
105
0.615202
ondra-novak
694510257d4c266d8c021b6aa035a78dc1ace904
1,395
cpp
C++
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: House_Robber_198.cpp > Author: zzy > Mail: 942744575@qq.com > Created Time: Fri 22 Feb 2019 07:16:58 PM CST ********************************************************************** */ /* 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。 */ /* * dp: 最后一间房,要么偷,要么不偷 * 公式: f(n) = max(f(n-2) + a[n], f(n-1)) */ #include <vector> #include<gtest/gtest.h> #include <stdio.h> using std::vector; class Solution { public: int rob(vector<int>& nums) { if (nums.empty()) { return 0; } const int n = nums.size(); int money[n+1]; money[0] = 0; money[1] = nums[0]; for (int i = 2; i <= n; ++i) { money[i] = std::max(nums[i-1] + money[i-2], money[i-1]); } return money[n]; } }; TEST(test_rob, dp) { Solution s; std::vector<int> nums_1{1,2,3,1}; std::vector<int> nums_2{2,7,9,3,1}; EXPECT_EQ(s.rob(nums_1), 4); EXPECT_EQ(s.rob(nums_2), 12); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
19.647887
92
0.53405
obviouskkk
6947647fc635cb94d51eca5ba5c1346daba305ab
7,662
cpp
C++
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
4
2021-06-22T20:52:30.000Z
2022-02-04T00:19:44.000Z
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
null
null
null
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
null
null
null
#include "PciBus.h" #include "acpi.h" #include "log.h" #include <driver/DrivermanClient.h> #include <mpack/mpack.h> using namespace acpi; std::string const PciBus::kBusName = "PCI"; std::string const PciBus::kDriverName = "AcpiPciRootBridge"; bool PciBus::gLogInterrupts = false; /** * Extracts the interrupt routing from a given ACPI object. * * @param object Handle to the PCI object (such as "\_SB.PCI0") in the ACPI namespace. */ void PciBus::getIrqRoutes(ACPI_HANDLE object) { ACPI_STATUS status; // set up the buffer ACPI_BUFFER buf; buf.Length = ACPI_ALLOCATE_BUFFER; buf.Pointer = nullptr; // read tables status = AcpiGetIrqRoutingTable(object, &buf); if(status != AE_OK) { Abort("AcpiGetIrqRoutingTable failed: %s", AcpiFormatException(status)); } // iterate over the interrupts std::byte *scan = reinterpret_cast<std::byte *>(buf.Pointer); while(true) { // get table and exit if we've reached the end auto table = reinterpret_cast<const ACPI_PCI_ROUTING_TABLE *>(scan); if(!table->Length) { break; } uint8_t slot = (table->Address >> 16); // static interrupt assignment if(!table->Source[0]) { // TODO: implement static IRQs Trace("gsi %u pin %u (slot %u)", table->SourceIndex, table->Pin, slot); } // the assignment is dynamic else { // get PCI link ACPI_HANDLE linkObject; status = AcpiGetHandle(object, table->Source, &linkObject); if(status != AE_OK) { Abort("failed to get source '%s': %s", table->Source, AcpiFormatException(status)); } // get associated IRQ ACPI_BUFFER resbuf; resbuf.Length = ACPI_ALLOCATE_BUFFER; resbuf.Pointer = NULL; status = AcpiGetCurrentResources(linkObject, &resbuf); if(status != AE_OK) { Abort("AcpiGetCurrentResources failed for '%s': %s", table->Source, AcpiFormatException(status)); } auto rscan = reinterpret_cast<std::byte *>(resbuf.Pointer); resource::Irq devIrq; while(1) { // bail if at end auto res = reinterpret_cast<ACPI_RESOURCE *>(rscan); if(res->Type == ACPI_RESOURCE_TYPE_END_TAG) { break; } // handle interrupt resource types else if(res->Type == ACPI_RESOURCE_TYPE_IRQ) { devIrq = resource::Irq(res->Data.Irq); break; } else if(res->Type == ACPI_RESOURCE_TYPE_EXTENDED_IRQ) { devIrq = resource::Irq(res->Data.ExtendedIrq); break; } // check next resource rscan += res->Length; } // release resource buffer free(resbuf.Pointer); // record the interrupt we got if(devIrq.flags == resource::IrqMode::Invalid) { Abort("failed to derive IRQ for device %d from '%s'", (int)slot, table->Source); } // modify an IRQ map entry given the current state auto yeeter = [&, devIrq](DeviceIrqInfo &map) { switch(table->Pin) { case 0: map.inta = devIrq; break; case 1: map.intb = devIrq; break; case 2: map.intc = devIrq; break; case 3: map.intd = devIrq; break; } }; // have we an existing object? if(this->irqMap.contains(slot)) { auto &map = this->irqMap.at(slot); yeeter(map); } else { DeviceIrqInfo map; yeeter(map); this->irqMap.emplace(slot, std::move(map)); } } // go to next scan += table->Length; } // clean up free(buf.Pointer); // XXX: print for(const auto &[device, map] : this->irqMap) { int a = -1, b = -1, c = -1, d = -1; if(map.inta) { a = (*map.inta).irq; } if(map.intb) { b = (*map.intb).irq; } if(map.intc) { c = (*map.intc).irq; } if(map.intd) { d = (*map.intd).irq; } if(gLogInterrupts) { Trace("Device %2u: INTA %2d INTB %2d INTC %2d INTD %2d", device, a, b, c, d); } } } /** * Loads a driver for this PCI bus. */ void PciBus::loadDriver(const uintptr_t) { std::vector<std::byte> aux; this->serializeAuxData(aux); auto rpc = libdriver::RpcClient::the(); // register driver this->drivermanPath = libdriver::RpcClient::the()->AddDevice(kAcpiBusRoot, kDriverName); Trace("PCI bus registered at %s", this->drivermanPath.c_str()); // set configuration rpc->SetDeviceProperty(this->drivermanPath, kAuxDataKey, aux); rpc->StartDevice(this->drivermanPath); } /** * Serializes the interrupt map to an msgpack object. It's basically identical to the * representation used in memory. Additionally, bus address is added. */ void PciBus::serializeAuxData(std::vector<std::byte> &out) { char *data; size_t size; // set up writer mpack_writer_t writer; mpack_writer_init_growable(&writer, &data, &size); mpack_start_map(&writer, 4); mpack_write_cstr(&writer, "bus"); mpack_write_u8(&writer, this->bus); mpack_write_cstr(&writer, "segment"); mpack_write_u8(&writer, this->segment); mpack_write_cstr(&writer, "address"); mpack_write_u32(&writer, this->address); // serialize mpack_write_cstr(&writer, "irqs"); if(!this->irqMap.empty()) { mpack_start_map(&writer, this->irqMap.size()); for(const auto &[device, info] : this->irqMap) { mpack_write_u8(&writer, device); info.serialize(&writer); } mpack_finish_map(&writer); } else { mpack_write_nil(&writer); } // clean up mpack_finish_map(&writer); auto status = mpack_writer_destroy(&writer); if(status != mpack_ok) { Warn("%s failed: %d", "mpack_writer_destroy", status); return; } // copy to output buffer out.resize(size); out.assign(reinterpret_cast<std::byte *>(data), reinterpret_cast<std::byte *>(data + size)); free(data); } /** * Serializes an interrupt info object. */ void PciBus::DeviceIrqInfo::serialize(mpack_writer_t *writer) const { mpack_start_map(writer, 4); // INTA //mpack_write_cstr(writer, "a"); mpack_write_u8(writer, 0); if(this->inta) { this->inta->serialize(writer); } else { mpack_write_nil(writer); } // INTB //mpack_write_cstr(writer, "b"); mpack_write_u8(writer, 1); if(this->intb) { this->intb->serialize(writer); } else { mpack_write_nil(writer); } // INTC //mpack_write_cstr(writer, "c"); mpack_write_u8(writer, 2); if(this->intc) { this->intc->serialize(writer); } else { mpack_write_nil(writer); } // INTD //mpack_write_cstr(writer, "d"); mpack_write_u8(writer, 3); if(this->intd) { this->intd->serialize(writer); } else { mpack_write_nil(writer); } // clean up mpack_finish_map(writer); }
28.273063
113
0.543461
tristanseifert
6947925b89d6354d11d2ebeb364896efe5c8f025
1,109
cpp
C++
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not. Constraints: 1 ≤ V, E ≤ 10^5 Approach: This is another method based on Union-Find. This method assumes that the graph doesn’t contain any self-loops. We can keep track of the subsets in a 1D array, let’s call it parent[]. Time Complexity: O(V + E) Space Complexity: O(V) */ int findSet(int currentVertex, int parent[]) { if(parent[currentVertex]==-1) { return currentVertex; } findSet(parent[currentVertex], parent); } bool isCycle(int V,vector<int> g[] ) { int parent[V]; for(int i=0;i<V;i++) { parent[i] = -1; } int s1,s2; for(int i=0;i<V;i++) { vector<int>::iterator it; for(it=g[i].begin(); it!=g[i].end(); it++) { s1 = findSet(i, parent); s2 = findSet(*it, parent); if(s1!=s2) { parent[*it] = i; } else { if(parent[i]!=*it) { return true; } } } } return false; }
23.595745
121
0.540126
PrachieNaik
6948c4b730f092e9aa145ba7b471eb6a9749d816
267
cpp
C++
source/framework/partitioned_array/src/array_partition_uint64.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/partitioned_array/src/array_partition_uint64.cpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/partitioned_array/src/array_partition_uint64.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "lue/framework/partitioned_array/array_partition_impl.hpp" namespace lue { template class ArrayPartition<std::uint64_t, 0>; template class ArrayPartition<std::uint64_t, 1>; template class ArrayPartition<std::uint64_t, 2>; } // namespace lue
24.272727
67
0.749064
computationalgeography
694aadddf1dc57e6a0d2e3eb4ff5ac13043a5624
5,188
cpp
C++
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015-2017, Nokia Technologies Ltd. * All rights reserved. * * Licensed under the Nokia High-Efficiency Image File Format (HEIF) License (the "License"). * * You may not use the High-Efficiency Image File Format except in compliance with the License. * The License accompanies the software and can be found in the file "LICENSE.TXT". * * You may also obtain the License at: * https://nokiatech.github.io/heif/license.txt */ #include "auxiliaryimagewriter.hpp" #include "auxiliarytypeproperty.hpp" #include "avcconfigurationbox.hpp" #include "datastore.hpp" #include "hevcconfigurationbox.hpp" #include "imagespatialextentsproperty.hpp" #include "itempropertiesbox.hpp" #include "mediatypedefs.hpp" #include "metabox.hpp" #include "services.hpp" #include "writerconstants.hpp" #include <memory> #define ANDROID_STOI_HACK #define ANDROID_TO_STRING_HACK #include "androidhacks.hpp" AuxiliaryImageWriter::AuxiliaryImageWriter(const IsoMediaFile::Auxiliary& config, const std::uint32_t contextId) : RootMetaImageWriter({""}, contextId), mConfig(config) { } void AuxiliaryImageWriter::write(MetaBox* metaBox) { RootMetaImageWriter::initWrite(); storeValue("uniq_bsid", std::to_string(mConfig.uniq_bsid)); storeValue("capsulation", META_ENCAPSULATION); RootMetaImageWriter::parseInputBitStream(mConfig.file_path, mConfig.code_type); ItemSet itemIds = addItemReferences(metaBox); ilocWrite(metaBox, itemIds); iinfWrite(metaBox, itemIds); iprpWrite(metaBox, itemIds); } void AuxiliaryImageWriter::ilocWrite(MetaBox* metaBox, const ItemSet& itemIds) const { for (const auto& item : mMetaItems) { if (itemIds.count(item.mId)) { metaBox->addIloc(item.mId, item.mOffset, item.mLength, getBaseOffset()); } } } void AuxiliaryImageWriter::iinfWrite(MetaBox* metaBox, const ItemSet& itemIds) const { for (const auto& item : mMetaItems) { if (itemIds.count(item.mId)) { metaBox->addItem(item.mId, item.mType, item.mName, mConfig.hidden); } } } void AuxiliaryImageWriter::iprpWrite(MetaBox* metaBox, const ItemSet& itemIds) const { std::vector<std::uint32_t> itemIdVector; for (const auto id : itemIds) { itemIdVector.push_back(id); } RootMetaImageWriter::iprpWrite(metaBox); // Add 'auxC' property auto auxBox = std::make_shared<AuxiliaryTypeProperty>(); auxBox->setAuxType(mConfig.urn); metaBox->addProperty(auxBox, itemIdVector, true); } AuxiliaryImageWriter::ItemSet AuxiliaryImageWriter::addItemReferences(MetaBox* metaBox) const { ItemId fromId = mMetaItems.at(0).mId; ItemSet itemIds; if (mConfig.idxs_list.size() == 0) { // No idxs_list was given, so assume 1:1 mapping for referenced image items and auxiliary image items, or // map an auxiliary image to every master if there is only one. const std::vector<std::string> masterImageIds = getMasterStoreValue("item_indx"); for (size_t i = 0; i < masterImageIds.size(); ++i) { if (mMetaItems.size() > 1) { fromId = mMetaItems.at(i).mId; } metaBox->addItemReference("auxl", fromId, std::stoi(masterImageIds.at(i))); itemIds.insert(fromId); } } else { // idxs_list was given, so set the first auxiliary image for all images listed. const ReferenceToItemIdMap referenceMap = createReferenceToItemIdMap(); for (size_t i = 0; i < mConfig.refs_list.size(); ++i) { const UniqBsid masterUniqBsid = mConfig.refs_list.at(i); const ItemIdVector& indexList = mConfig.idxs_list.at(i); for (const auto index : indexList) { const ItemId masterImageId = referenceMap.at(masterUniqBsid).at(index - 1); metaBox->addItemReference("auxl", fromId, masterImageId); itemIds.insert(fromId); } } } return itemIds; } /// @todo This is common with derived item writer and should be refactored. AuxiliaryImageWriter::ReferenceToItemIdMap AuxiliaryImageWriter::createReferenceToItemIdMap() const { ReferenceToItemIdMap referenceToItemIdMap; // Add meta master contexts to the map const std::vector<std::uint32_t> storeIds = DataServe::getStoreIds(); for (const auto storeId : storeIds) { const std::shared_ptr<DataStore> dataStore = DataServe::getStore(storeId); if (dataStore->isValueSet("uniq_bsid") && dataStore->isValueSet("capsulation") && dataStore->getValue("capsulation").at(0) == META_ENCAPSULATION) { const UniqBsid uniqBsid = std::stoi(dataStore->getValue("uniq_bsid").at(0)); const std::vector<std::string> itemIdStrings = dataStore->getValue("item_indx"); ItemIdVector itemIds; for (const auto& itemId : itemIdStrings) { itemIds.push_back(std::stoi(itemId)); } referenceToItemIdMap.insert( { uniqBsid, itemIds }); } } return referenceToItemIdMap; }
33.25641
114
0.667887
anzksdk
694e41b62fd18581a35e497b57379741b0f936eb
583
cc
C++
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
/* bind()绑定时参数个数固定,类型需匹配 */ #include <iostream> #include <functional> using namespace std; void func3(int n1, int n2, int n3) { cout << n1 << ' ' << n2 << ' ' << n3 << endl; } void test3_1() { auto f3 = std::bind(func3, placeholders::_1, 101); //f3(11); // 编译错误,因为bind函数中少了一个参数 } void test3_2() { auto f3 = std::bind(func3, placeholders::_1, 101, 102, 103); //f3(11); // 编译错误,因为bind函数中多了一个参数 } void test3_3() { auto f3 = std::bind(func3, placeholders::_1, "test", placeholders::_1); //f3(11); // 编译错误,第二个参数类型不匹配,无法将参数 2 从“const char *”转换为“int” }
23.32
75
0.600343
chanchann
6950341a5a7bdc98c804afb9768f304d09903d1e
4,692
cc
C++
contrib/gnu/gcc/dist/gcc/brig/brigfrontend/brig-seg-inst-handler.cc
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
contrib/gnu/gcc/dist/gcc/brig/brigfrontend/brig-seg-inst-handler.cc
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
null
null
null
contrib/gnu/gcc/dist/gcc/brig/brigfrontend/brig-seg-inst-handler.cc
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
null
null
null
/* brig-seg-inst-handler.cc -- brig segment related instruction handling Copyright (C) 2016-2020 Free Software Foundation, Inc. Contributed by Pekka Jaaskelainen <pekka.jaaskelainen@parmance.com> for General Processor Tech. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include <sstream> #include "brig-code-entry-handler.h" #include "brig-util.h" #include "convert.h" #include "tree-pretty-print.h" #include "errors.h" #include "diagnostic-core.h" brig_seg_inst_handler::brig_seg_inst_handler (brig_to_generic &parent) : brig_code_entry_handler (parent) { } size_t brig_seg_inst_handler::operator () (const BrigBase *base) { const BrigInstBase &inst_base = *(const BrigInstBase *) base; std::vector<tree> operands = build_operands (inst_base); tree expr = NULL_TREE; if (inst_base.opcode == BRIG_OPCODE_STOF) { const BrigInstSegCvt &inst = *(const BrigInstSegCvt *) base; if (inst.segment == BRIG_SEGMENT_GROUP) expr = build2 (PLUS_EXPR, size_type_node, convert_to_integer (size_type_node, m_parent.m_cf->m_group_base_arg), convert_to_integer (size_type_node, operands[1])); else if (inst.segment == BRIG_SEGMENT_PRIVATE || inst.segment == BRIG_SEGMENT_SPILL) expr = build2 (PLUS_EXPR, size_type_node, convert_to_integer (size_type_node, m_parent.m_cf->m_private_base_arg), convert_to_integer (size_type_node, operands[1])); else gcc_unreachable (); if (!(inst.modifier & BRIG_SEG_CVT_NONULL)) { /* Need to convert the null value. -1 is used for 32b segments, and 0 for flat/global. */ tree cmp = build2 (EQ_EXPR, uint32_type_node, build_int_cstu (uint32_type_node, -1), operands[1]); tree null_check = build3 (COND_EXPR, size_type_node, cmp, build_int_cstu (size_type_node, 0), expr); expr = null_check; } } else if (inst_base.opcode == BRIG_OPCODE_FTOS) { const BrigInstSegCvt &inst = *(const BrigInstSegCvt *) base; if (inst.segment == BRIG_SEGMENT_GROUP) expr = build2 (MINUS_EXPR, size_type_node, convert_to_integer (size_type_node, m_parent.m_cf->m_group_base_arg), convert_to_integer (size_type_node, operands[1])); else if (inst.segment == BRIG_SEGMENT_PRIVATE) expr = build2 (MINUS_EXPR, size_type_node, convert_to_integer (size_type_node, m_parent.m_cf->m_private_base_arg), convert_to_integer (size_type_node, operands[1])); else gcc_unreachable (); if (!(inst.modifier & BRIG_SEG_CVT_NONULL)) { /* Need to convert the null value. -1 is used for 32b segments, and 0 for flat/global. */ tree cmp = build2 (EQ_EXPR, size_type_node, build_int_cstu (size_type_node, 0), operands[1]); tree null_check = build3 (COND_EXPR, size_type_node, cmp, build_int_cstu (uint32_type_node, -1), expr); expr = null_check; } } else if (inst_base.opcode == BRIG_OPCODE_NULLPTR) { const BrigInstSeg &inst = *(const BrigInstSeg *) base; if (inst.segment == BRIG_SEGMENT_GLOBAL || inst.segment == BRIG_SEGMENT_FLAT || inst.segment == BRIG_SEGMENT_READONLY) expr = build_int_cstu (uint64_type_node, 0); else expr = build_int_cstu (uint32_type_node, -1); } else if (inst_base.opcode == BRIG_OPCODE_SEGMENTP) { const BrigInstSegCvt &inst = *(const BrigInstSegCvt *) base; tree builtin = NULL_TREE; switch (inst.segment) { case BRIG_SEGMENT_GLOBAL: builtin = builtin_decl_explicit (BUILT_IN_HSAIL_SEGMENTP_GLOBAL); break; case BRIG_SEGMENT_GROUP: builtin = builtin_decl_explicit (BUILT_IN_HSAIL_SEGMENTP_GROUP); break; case BRIG_SEGMENT_PRIVATE: builtin = builtin_decl_explicit (BUILT_IN_HSAIL_SEGMENTP_PRIVATE); break; default: gcc_unreachable (); } expr = call_builtin (builtin, 2, uint32_type_node, uint64_type_node, operands[1], ptr_type_node, m_parent.m_cf->m_context_arg); } else gcc_unreachable (); build_output_assignment (inst_base, operands[0], expr); return base->byteCount; }
31.918367
72
0.708227
TheSledgeHammer
695075a6022cc3460f34c545bcc6ee5984704557
2,104
cpp
C++
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
1
2018-08-13T04:01:11.000Z
2018-08-13T04:01:11.000Z
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
null
null
null
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
1
2018-09-23T03:36:20.000Z
2018-09-23T03:36:20.000Z
#include <bandit_with_gmock/bandit_with_gmock.hpp> #include <ts_processor/ts/data.hpp> #include <ts_processor/ts/psi/pat.hpp> #include <bitfield/iostream.hpp> namespace ts_processor { namespace ts { namespace psi { go_bandit([]{ using namespace bandit; describe("ts::psi::pat", [&]{ ts::data data; auto equals_v = [](pat::pid_type v){ return Equals(v); }; before_each([&]{ ts::packet packet{ #include <fixture/ts/psi/pat/single_packet.cpp> }; data.reset(packet.pid); data.push(packet); }); describe("#sections", [&]{ it("should iterate each fieldset in the section list", [&]{ auto & sections = data->psi.get<pat>()->sections; auto it = sections.begin(); auto end = sections.end(); AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::network)); AssertThat(it->pid, Equals(0x0010)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x0101)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x0102)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x1FC8)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x1FC9)); ++it; AssertThat(it, Equals(end)); }); }); }); }); }}}
33.935484
77
0.475285
mrk21
6950c2cf28f88da37efe9b1e4c84267ceda1962b
7,988
inl
C++
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
5
2015-09-22T02:33:34.000Z
2018-08-29T07:37:54.000Z
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
1
2018-12-12T12:08:28.000Z
2018-12-13T06:14:54.000Z
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
4
2015-03-04T00:09:18.000Z
2020-09-08T02:58:06.000Z
/* Copyright (c) 2013, Fatih Calakli and Daniel Moreno 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 Brown University 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. */ #if defined(_MSC_VER) && (_MSC_VER<1600) // VS2008 defines std::unordered_map as std::tr1::unordered_map namespace std {using namespace std::tr1;}; #endif template <typename Octree> void OctreeCache<Octree>::clear(void) { _cells.clear(); _vertices.clear(); _cellmap.clear(); _vertexmap.clear(); } template <typename Octree> void OctreeCache<Octree>::build(Octree & octree) { static const size_t MORTON_TO_TAUBIN_VERTEX_ORDER[8] = { 0, 4, 2, 6, 1, 5, 3, 7 }; // 0 1 2 3 4 5 6 7 _octree = &octree; size_t cell_count = octree.getNumberOfCells(); size_t vertex_count = octree.getNumberOfVertices(); _cells.clear(); _cells.resize(cell_count); _vertices.clear(); _vertices.resize(vertex_count); _cellmap.clear(); _cellmap.rehash(cell_count); _vertexmap.clear(); _vertexmap.rehash(vertex_count); size_t index = 0; size_t v_index = 0; for (typename Octree::cell_iterator iter=octree.cell_begin(); iter!=octree.cell_end(); ++iter) { //original key typename Octree::CellKey cellA = (*iter).first; //mapped key size_t index_a; typename CellMap::const_iterator map_a = _cellmap.find(cellA); if (map_a==_cellmap.end()) { //not found: create _cellmap[cellA] = index; index_a = index; ++index; } else { //found index_a = map_a->second; } //cache CellCache & cache_a = _cells[index_a]; cache_a.key = cellA; //save user data (first point in partition) //cache_a.data = iter->second->data; cache_a.data = (*iter).second; //save cell coords octree.getCellCoords(cellA, cache_a.cell); //make neighbor edges typename Octree::CellKey neighbor_keys[6]; octree.getFaceNeighborKeys(cellA, neighbor_keys); typename Octree::Cell neighbors[6] = { octree.getCellFirstAncestor(neighbor_keys[0]), octree.getCellFirstAncestor(neighbor_keys[1]), octree.getCellFirstAncestor(neighbor_keys[2]), octree.getCellFirstAncestor(neighbor_keys[3]), octree.getCellFirstAncestor(neighbor_keys[4]), octree.getCellFirstAncestor(neighbor_keys[5])}; std::vector<size_t> & edges_a = cache_a.edges; for (size_t i=0; i<6; ++i) { typename Octree::CellKey cellB = neighbors[i].first; if (cellB==octree.INVALID_CELL_KEY) { continue; } //mapped key size_t index_b; typename CellMap::const_iterator map_b = _cellmap.find(cellB); if (map_b==_cellmap.end()) { //not found: create _cellmap[cellB] = index; index_b = index; ++index; } else { //found index_b = map_b->second; } if (cellB<cellA) { if (std::find(edges_a.begin(), edges_a.end(), index_b)==edges_a.end()) { edges_a.push_back(index_b); } } else { std::vector<size_t> & edges_b = _cells[index_b].edges; if (std::find(edges_b.begin(), edges_b.end(), index_a)==edges_b.end()) { edges_b.push_back(index_a); } } } //get current cell vertices typename Octree::Vertex vertices[8]; octree.getVertices(cellA, vertices); size_t * vertices_a = cache_a.vertices; for (size_t i=0; i<8; ++i) { //original key typename Octree::VertexKey v = vertices[i].first; //mapped key size_t j; typename VertexMap::const_iterator map_v = _vertexmap.find(v); if (map_v==_vertexmap.end()) { //not found: add _vertexmap[v] = v_index; _vertices[v_index] = vertices[i].second; j = v_index; ++v_index; } else { //found j = map_v->second; } //save in the current cell vertices_a[MORTON_TO_TAUBIN_VERTEX_ORDER[i]] = j; } }//for each cell } template <typename Octree> void OctreeCache<Octree>::getFaceNeighborKeys(CellKey key, CellKey neighbors[6]) const { std::vector<size_t> const& edges = _cells[key].edges; std::vector<size_t>::const_iterator iter = edges.begin(); for (size_t i=0; i<6; ++i) { neighbors[i] = (iter==edges.end() ? INVALID_CELL_KEY : *iter++); } } template <typename Octree> void OctreeCache<Octree>::getCellNeighborKeys(CellKey key, const size_t * direction, CellKey * neighbors) const { typename Octree::CellKey original_neighbors[27]; _octree->getCellNeighborKeys(_cells[key].key, direction, original_neighbors); for (size_t i=0; original_neighbors[i]!=MAX_VALUE; ++i) { neighbors[i] = _cellmap.find(original_neighbors[i])->second; } } template <typename Octree> typename OctreeCache<Octree>::Cell OctreeCache<Octree>::getCellFirstAncestor(CellKey key) { //this is just exists, we cannot do better //assert(false); //just a warning abut the incomplete implementation here if (key<_cells.size()) { return Cell(key, _cells[key].data); } //not found return Cell(); } template <typename Octree> void OctreeCache<Octree>::getVertices(CellKey key, Vertex vertices[8]) { if (key<_cells.size()) { const size_t * v = _cells[key].vertices; vertices[0] = Vertex(v[0], _vertices[v[0]]); vertices[1] = Vertex(v[1], _vertices[v[1]]); vertices[2] = Vertex(v[2], _vertices[v[2]]); vertices[3] = Vertex(v[3], _vertices[v[3]]); vertices[4] = Vertex(v[4], _vertices[v[4]]); vertices[5] = Vertex(v[5], _vertices[v[5]]); vertices[6] = Vertex(v[6], _vertices[v[6]]); vertices[7] = Vertex(v[7], _vertices[v[7]]); } //not found }
35.660714
138
0.591888
csiro-workspace
6953de013ac11a355e15d6181dc319853353a522
4,703
cc
C++
third_party/tmb/src/voltdb_procedure_factory.cc
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
31
2016-01-20T05:43:46.000Z
2022-02-07T09:14:06.000Z
third_party/tmb/src/voltdb_procedure_factory.cc
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
221
2016-01-20T18:25:10.000Z
2016-06-26T02:58:12.000Z
third_party/tmb/src/voltdb_procedure_factory.cc
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
17
2016-01-20T04:00:21.000Z
2019-03-12T02:41:25.000Z
// Copyright 2014-2015 Quickstep Technologies LLC. // // 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 "tmb/internal/voltdb_procedure_factory.h" #include <vector> #include "Parameter.hpp" // NOLINT(build/include) #include "WireType.h" // NOLINT(build/include) namespace tmb { namespace internal { VoltDBProcedureFactory::VoltDBProcedureFactory() { single_client_id_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); register_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); register_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_TIMESTAMP); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_SMALLINT); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_params_.emplace_back( voltdb::WIRE_TYPE_VARBINARY); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_TIMESTAMP); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_TIMESTAMP); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_SMALLINT); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_single_explicit_receiver_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_VARBINARY); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER, true); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_TIMESTAMP); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_SMALLINT); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_VARBINARY); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_TINYINT); send_to_explicit_receivers_params_.emplace_back(voltdb::WIRE_TYPE_TINYINT); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER, true); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_TIMESTAMP); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_TIMESTAMP); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_SMALLINT); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_INTEGER); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_VARBINARY); send_to_explicit_receivers_unchecked_params_.emplace_back( voltdb::WIRE_TYPE_TINYINT); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_TIMESTAMP); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_SMALLINT); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_VARBINARY); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_TINYINT); send_to_any_params_.emplace_back(voltdb::WIRE_TYPE_TINYINT); receive_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); receive_params_.emplace_back(voltdb::WIRE_TYPE_SMALLINT); receive_params_.emplace_back(voltdb::WIRE_TYPE_BIGINT); delete_messages_params_.emplace_back(voltdb::WIRE_TYPE_INTEGER); delete_messages_params_.emplace_back(voltdb::WIRE_TYPE_BIGINT, true); cancel_messages_params_.emplace_back(voltdb::WIRE_TYPE_BIGINT, true); } } // namespace internal } // namespace tmb
43.953271
79
0.81246
spring-operator
69541216aa33eccc776467608d61f99b08bda6cd
668
cpp
C++
src/examples/pcsupdater.cpp
framos-gemini/giapi-glue-cc
f59e1ce572494b57aad6985f3233f0e51167bb42
[ "BSD-3-Clause" ]
null
null
null
src/examples/pcsupdater.cpp
framos-gemini/giapi-glue-cc
f59e1ce572494b57aad6985f3233f0e51167bb42
[ "BSD-3-Clause" ]
3
2017-06-14T15:21:50.000Z
2020-08-03T19:51:57.000Z
src/examples/pcsupdater.cpp
framos-gemini/giapi-glue-cc
f59e1ce572494b57aad6985f3233f0e51167bb42
[ "BSD-3-Clause" ]
3
2017-06-13T13:59:36.000Z
2021-02-09T02:01:14.000Z
/* * A test application to demonstrate how to send zernikes corrections * to the PCS via the GIAPI * * Created on: Dec 10, 2009 * Author: anunez */ #include <iostream> #include <iomanip> #include <giapi/GeminiUtil.h> using namespace giapi; int main(int argc, char **argv) { try { std::cout << "Starting PCS Zernikes Example" << std::endl; double zernikes[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; if (GeminiUtil::postPcsUpdate(zernikes, 6) == status::ERROR) { std::cout << "Can't post zernikes to the PCS..." << std::endl; return 0; } } catch (GiapiException &e) { std::cerr << "Is the GMP up?" << std::endl; } return 0; }
17.578947
69
0.612275
framos-gemini
6956574a542563798f6067be8bd422597f891254
529
hpp
C++
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <thread> #include <SDL2/SDL.h> #include "../core/gbGameBoy.hpp" namespace Giffi { class appWindow { public: // Retruns true on success static void Init(); static void Run(); static void CleanUp(); private: static bool ShouldWindowClose(); static void DoEvents(); public: static std::shared_ptr<gbGameBoy> mGameBoy; static bool mClosing; private: static SDL_Renderer* mRenderer; static SDL_Window* mWindow; appWindow() = delete; ~appWindow() = delete; }; } // Namespace
14.694444
44
0.718336
giffi-dev
695a43ee250ed0289249ded550bd3162e6a1419a
2,082
hpp
C++
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#pragma once #include <map> #include "all_type_variant.hpp" #include "types.hpp" namespace opossum { /** * List of features usable in AbstractCostModels. * * Using enum to provide the unified "AbstractCostFeatureProxy" to access the same features for LQPs and PQPs. * Also, this makes it easy to specify Cost formulas from data only, as e.g. CostModelRuntime does. */ enum class CostFeature { /** * Numerical features */ LeftInputRowCount, RightInputRowCount, InputRowCountProduct, // LeftInputRowCount * RightInputRowCount LeftInputReferenceRowCount, RightInputReferenceRowCount, // *InputRowCount if the input is References, 0 otherwise LeftInputRowCountLogN, RightInputRowCountLogN, // *InputRowCount * log(*InputRowCount) LargerInputRowCount, SmallerInputRowCount, // Major = Input with more rows, Minor = Input with less rows LargerInputReferenceRowCount, SmallerInputReferenceRowCount, OutputRowCount, OutputReferenceRowCount, // If input is References, then OutputRowCount. 0 otherwise. /** * Categorical features */ LeftDataType, RightDataType, // Only valid for Predicated Joins, TableScans PredicateCondition, // Only valid for Predicated Joins, TableScans /** * Boolean features */ LeftInputIsReferences, RightInputIsReferences, // *Input is References RightOperandIsColumn, // Only valid for TableScans LeftInputIsMajor // LeftInputRowCount > RightInputRowCount }; using CostFeatureWeights = std::map<CostFeature, float>; /** * Wraps a Variant of all data types for CostFeatues and provides getters for the member types of the variants that * perform type checking at runtime. */ struct CostFeatureVariant { public: template <typename T> CostFeatureVariant(const T& value) : value(value) {} // NOLINT - implicit conversion is intended bool boolean() const; float scalar() const; DataType data_type() const; PredicateCondition predicate_condition() const; boost::variant<float, DataType, PredicateCondition, bool> value; }; } // namespace opossum
29.742857
115
0.747839
IanJamesMcKay
695cc8171940192e6ed4e85c2a0842a4c2c9fd07
23,568
cpp
C++
blades/xbmc/xbmc/addons/Addon.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/addons/Addon.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/addons/Addon.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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 2, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "Addon.h" #include <string.h> #include <ostream> #include <utility> #include <vector> #include "AddonManager.h" #include "addons/Service.h" #include "ContextMenuManager.h" #include "filesystem/Directory.h" #include "filesystem/File.h" #include "RepositoryUpdater.h" #include "settings/Settings.h" #include "system.h" #include "URL.h" #include "Util.h" #include "utils/log.h" #include "utils/StringUtils.h" #include "utils/URIUtils.h" #include "utils/Variant.h" #ifdef HAS_PYTHON #include "interfaces/python/XBPython.h" #endif #if defined(TARGET_DARWIN) #include "../osx/OSXGNUReplacements.h" #endif #ifdef TARGET_FREEBSD #include "freebsd/FreeBSDGNUReplacements.h" #endif using XFILE::CDirectory; using XFILE::CFile; namespace ADDON { /** * helper functions * */ typedef struct { const char* name; TYPE type; int pretty; const char* icon; } TypeMapping; static const TypeMapping types[] = {{"unknown", ADDON_UNKNOWN, 0, "" }, {"xbmc.metadata.scraper.albums", ADDON_SCRAPER_ALBUMS, 24016, "DefaultAddonAlbumInfo.png" }, {"xbmc.metadata.scraper.artists", ADDON_SCRAPER_ARTISTS, 24017, "DefaultAddonArtistInfo.png" }, {"xbmc.metadata.scraper.movies", ADDON_SCRAPER_MOVIES, 24007, "DefaultAddonMovieInfo.png" }, {"xbmc.metadata.scraper.musicvideos", ADDON_SCRAPER_MUSICVIDEOS, 24015, "DefaultAddonMusicVideoInfo.png" }, {"xbmc.metadata.scraper.tvshows", ADDON_SCRAPER_TVSHOWS, 24014, "DefaultAddonTvInfo.png" }, {"xbmc.metadata.scraper.library", ADDON_SCRAPER_LIBRARY, 24083, "DefaultAddonInfoLibrary.png" }, {"xbmc.ui.screensaver", ADDON_SCREENSAVER, 24008, "DefaultAddonScreensaver.png" }, {"xbmc.player.musicviz", ADDON_VIZ, 24010, "DefaultAddonVisualization.png" }, {"visualization-library", ADDON_VIZ_LIBRARY, 24084, "" }, {"xbmc.python.pluginsource", ADDON_PLUGIN, 24005, "" }, {"xbmc.python.script", ADDON_SCRIPT, 24009, "" }, {"xbmc.python.weather", ADDON_SCRIPT_WEATHER, 24027, "DefaultAddonWeather.png" }, {"xbmc.python.lyrics", ADDON_SCRIPT_LYRICS, 24013, "DefaultAddonLyrics.png" }, {"xbmc.python.library", ADDON_SCRIPT_LIBRARY, 24081, "DefaultAddonHelper.png" }, {"xbmc.python.module", ADDON_SCRIPT_MODULE, 24082, "DefaultAddonLibrary.png" }, {"xbmc.subtitle.module", ADDON_SUBTITLE_MODULE, 24012, "DefaultAddonSubtitles.png" }, {"kodi.context.item", ADDON_CONTEXT_ITEM, 24025, "DefaultAddonContextItem.png" }, {"xbmc.gui.skin", ADDON_SKIN, 166, "DefaultAddonSkin.png" }, {"xbmc.webinterface", ADDON_WEB_INTERFACE, 199, "DefaultAddonWebSkin.png" }, {"xbmc.addon.repository", ADDON_REPOSITORY, 24011, "DefaultAddonRepository.png" }, {"xbmc.pvrclient", ADDON_PVRDLL, 24019, "DefaultAddonPVRClient.png" }, {"xbmc.addon.video", ADDON_VIDEO, 1037, "DefaultAddonVideo.png" }, {"xbmc.addon.audio", ADDON_AUDIO, 1038, "DefaultAddonMusic.png" }, {"xbmc.addon.image", ADDON_IMAGE, 1039, "DefaultAddonPicture.png" }, {"xbmc.addon.executable", ADDON_EXECUTABLE, 1043, "DefaultAddonProgram.png" }, {"xbmc.audioencoder", ADDON_AUDIOENCODER, 200, "DefaultAddonAudioEncoder.png" }, {"kodi.audiodecoder", ADDON_AUDIODECODER, 201, "DefaultAddonAudioDecoder.png" }, {"xbmc.service", ADDON_SERVICE, 24018, "DefaultAddonService.png" }, {"kodi.resource.images", ADDON_RESOURCE_IMAGES, 24035, "DefaultAddonImages.png" }, {"kodi.resource.language", ADDON_RESOURCE_LANGUAGE, 24026, "DefaultAddonLanguage.png" }, {"kodi.resource.uisounds", ADDON_RESOURCE_UISOUNDS, 24006, "DefaultAddonUISounds.png" }, {"kodi.adsp", ADDON_ADSPDLL, 24135, "DefaultAddonAudioDSP.png" }, }; const std::string TranslateType(const ADDON::TYPE &type, bool pretty/*=false*/) { for (unsigned int index=0; index < ARRAY_SIZE(types); ++index) { const TypeMapping &map = types[index]; if (type == map.type) { if (pretty && map.pretty) return g_localizeStrings.Get(map.pretty); else return map.name; } } return ""; } TYPE TranslateType(const std::string &string) { for (unsigned int index=0; index < ARRAY_SIZE(types); ++index) { const TypeMapping &map = types[index]; if (string == map.name) return map.type; } return ADDON_UNKNOWN; } const std::string GetIcon(const ADDON::TYPE& type) { for (unsigned int index=0; index < ARRAY_SIZE(types); ++index) { const TypeMapping &map = types[index]; if (type == map.type) return map.icon; } return ""; } #define EMPTY_IF(x,y) \ { \ std::string fan=CAddonMgr::GetInstance().GetExtValue(metadata->configuration, x); \ if (fan == "true") \ y.clear(); \ } #define SS(x) (x) ? x : "" AddonProps::AddonProps(const cp_extension_t *ext) : id(SS(ext->plugin->identifier)) , version(SS(ext->plugin->version)) , minversion(SS(ext->plugin->abi_bw_compatibility)) , name(SS(ext->plugin->name)) , path(SS(ext->plugin->plugin_path)) , author(SS(ext->plugin->provider_name)) , stars(0) { if (ext->ext_point_id) type = TranslateType(ext->ext_point_id); icon = "icon.png"; fanart = URIUtils::AddFileToFolder(path, "fanart.jpg"); changelog = URIUtils::AddFileToFolder(path, "changelog.txt"); // Grab more detail from the props... const cp_extension_t *metadata = CAddonMgr::GetInstance().GetExtension(ext->plugin, "xbmc.addon.metadata"); //<! backword compatibilty if (!metadata) metadata = CAddonMgr::GetInstance().GetExtension(ext->plugin, "kodi.addon.metadata"); if (metadata) { summary = CAddonMgr::GetInstance().GetTranslatedString(metadata->configuration, "summary"); description = CAddonMgr::GetInstance().GetTranslatedString(metadata->configuration, "description"); disclaimer = CAddonMgr::GetInstance().GetTranslatedString(metadata->configuration, "disclaimer"); license = CAddonMgr::GetInstance().GetExtValue(metadata->configuration, "license"); std::string language; language = CAddonMgr::GetInstance().GetExtValue(metadata->configuration, "language"); if (!language.empty()) extrainfo.insert(std::make_pair("language",language)); broken = CAddonMgr::GetInstance().GetExtValue(metadata->configuration, "broken"); EMPTY_IF("nofanart",fanart) EMPTY_IF("noicon",icon) EMPTY_IF("nochangelog",changelog) } BuildDependencies(ext->plugin); } AddonProps::AddonProps(const cp_plugin_info_t *plugin) : id(SS(plugin->identifier)) , type(ADDON_UNKNOWN) , version(SS(plugin->version)) , minversion(SS(plugin->abi_bw_compatibility)) , name(SS(plugin->name)) , path(SS(plugin->plugin_path)) , author(SS(plugin->provider_name)) , stars(0) { BuildDependencies(plugin); } void AddonProps::Serialize(CVariant &variant) const { variant["addonid"] = id; variant["type"] = TranslateType(type); variant["version"] = version.asString(); variant["minversion"] = minversion.asString(); variant["name"] = name; variant["license"] = license; variant["summary"] = summary; variant["description"] = description; variant["path"] = path; variant["libname"] = libname; variant["author"] = author; variant["source"] = source; if (CURL::IsFullPath(icon)) variant["icon"] = icon; else variant["icon"] = URIUtils::AddFileToFolder(path, icon); variant["thumbnail"] = variant["icon"]; variant["disclaimer"] = disclaimer; variant["changelog"] = changelog; if (CURL::IsFullPath(fanart)) variant["fanart"] = fanart; else variant["fanart"] = URIUtils::AddFileToFolder(path, fanart); variant["dependencies"] = CVariant(CVariant::VariantTypeArray); for (ADDONDEPS::const_iterator it = dependencies.begin(); it != dependencies.end(); ++it) { CVariant dep(CVariant::VariantTypeObject); dep["addonid"] = it->first; dep["version"] = it->second.first.asString(); dep["optional"] = it->second.second; variant["dependencies"].push_back(dep); } if (broken.empty()) variant["broken"] = false; else variant["broken"] = broken; variant["extrainfo"] = CVariant(CVariant::VariantTypeArray); for (InfoMap::const_iterator it = extrainfo.begin(); it != extrainfo.end(); ++it) { CVariant info(CVariant::VariantTypeObject); info["key"] = it->first; info["value"] = it->second; variant["extrainfo"].push_back(info); } variant["rating"] = stars; } void AddonProps::BuildDependencies(const cp_plugin_info_t *plugin) { if (!plugin) return; for (unsigned int i = 0; i < plugin->num_imports; ++i) dependencies.insert(std::make_pair(std::string(plugin->imports[i].plugin_id), std::make_pair(AddonVersion(SS(plugin->imports[i].version)), plugin->imports[i].optional != 0))); } /** * CAddon * */ CAddon::CAddon(const cp_extension_t *ext) : m_props(ext) { BuildLibName(ext); Props().libname = m_strLibName; BuildProfilePath(); m_userSettingsPath = URIUtils::AddFileToFolder(Profile(), "settings.xml"); m_hasSettings = true; m_hasStrings = false; m_checkedStrings = false; m_settingsLoaded = false; m_userSettingsLoaded = false; } CAddon::CAddon(const cp_plugin_info_t *plugin) : m_props(plugin) { m_hasSettings = false; m_hasStrings = false; m_checkedStrings = true; m_settingsLoaded = false; m_userSettingsLoaded = false; } CAddon::CAddon(const AddonProps &props) : m_props(props) { if (props.libname.empty()) BuildLibName(); else m_strLibName = props.libname; BuildProfilePath(); m_userSettingsPath = URIUtils::AddFileToFolder(Profile(), "settings.xml"); m_hasSettings = true; m_hasStrings = false; m_checkedStrings = false; m_settingsLoaded = false; m_userSettingsLoaded = false; } CAddon::CAddon(const CAddon &rhs) : m_props(rhs.Props()), m_settings(rhs.m_settings) { m_addonXmlDoc = rhs.m_addonXmlDoc; m_settingsLoaded = rhs.m_settingsLoaded; m_userSettingsLoaded = rhs.m_userSettingsLoaded; m_hasSettings = rhs.m_hasSettings; BuildProfilePath(); m_userSettingsPath = URIUtils::AddFileToFolder(Profile(), "settings.xml"); m_strLibName = rhs.m_strLibName; m_hasStrings = false; m_checkedStrings = false; } AddonPtr CAddon::Clone() const { return AddonPtr(new CAddon(*this)); } bool CAddon::MeetsVersion(const AddonVersion &version) const { return m_props.minversion <= version && version <= m_props.version; } //TODO platform/path crap should be negotiated between the addon and // the handler for it's type void CAddon::BuildLibName(const cp_extension_t *extension) { if (!extension) { m_strLibName = "default"; std::string ext; switch (m_props.type) { case ADDON_SCRAPER_ALBUMS: case ADDON_SCRAPER_ARTISTS: case ADDON_SCRAPER_MOVIES: case ADDON_SCRAPER_MUSICVIDEOS: case ADDON_SCRAPER_TVSHOWS: case ADDON_SCRAPER_LIBRARY: ext = ADDON_SCRAPER_EXT; break; case ADDON_SCREENSAVER: ext = ADDON_SCREENSAVER_EXT; break; case ADDON_SKIN: m_strLibName = "skin.xml"; return; case ADDON_VIZ: ext = ADDON_VIS_EXT; break; case ADDON_PVRDLL: ext = ADDON_PVRDLL_EXT; break; case ADDON_ADSPDLL: ext = ADDON_DSP_AUDIO_EXT; break; case ADDON_SCRIPT: case ADDON_SCRIPT_LIBRARY: case ADDON_SCRIPT_LYRICS: case ADDON_SCRIPT_WEATHER: case ADDON_SUBTITLE_MODULE: case ADDON_PLUGIN: case ADDON_SERVICE: case ADDON_CONTEXT_ITEM: ext = ADDON_PYTHON_EXT; break; default: m_strLibName.clear(); return; } // extensions are returned as *.ext // so remove the asterisk ext.erase(0,1); m_strLibName.append(ext); } else { switch (m_props.type) { case ADDON_SCRIPT: case ADDON_SCRIPT_LIBRARY: case ADDON_SCRIPT_LYRICS: case ADDON_SCRIPT_WEATHER: case ADDON_SCRIPT_MODULE: case ADDON_SUBTITLE_MODULE: case ADDON_SCRAPER_ALBUMS: case ADDON_SCRAPER_ARTISTS: case ADDON_SCRAPER_MOVIES: case ADDON_SCRAPER_MUSICVIDEOS: case ADDON_SCRAPER_TVSHOWS: case ADDON_SCRAPER_LIBRARY: case ADDON_PLUGIN: case ADDON_WEB_INTERFACE: case ADDON_SERVICE: case ADDON_REPOSITORY: case ADDON_CONTEXT_ITEM: { std::string temp = CAddonMgr::GetInstance().GetExtValue(extension->configuration, "@library"); m_strLibName = temp; } break; case ADDON_ADSPDLL: case ADDON_AUDIODECODER: case ADDON_AUDIOENCODER: case ADDON_PVRDLL: case ADDON_SCREENSAVER: case ADDON_VIZ: { // if library attribute isn't present, look for a system-dependent one if (m_strLibName.empty()) m_strLibName = CAddonMgr::GetInstance().GetPlatformLibraryName(extension->configuration); } break; default: m_strLibName.clear(); break; } } } /** * Language File Handling */ bool CAddon::LoadStrings() { // Path where the language strings reside std::string chosenPath = URIUtils::AddFileToFolder(m_props.path, "resources/language/"); m_hasStrings = m_strings.Load(chosenPath, CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_LANGUAGE)); return m_checkedStrings = true; } void CAddon::ClearStrings() { // Unload temporary language strings m_strings.Clear(); m_hasStrings = false; } std::string CAddon::GetString(uint32_t id) { if (!m_hasStrings && ! m_checkedStrings && !LoadStrings()) return ""; return m_strings.Get(id); } /** * Settings Handling */ bool CAddon::HasSettings() { return LoadSettings(); } bool CAddon::LoadSettings(bool bForce /* = false*/) { if (m_settingsLoaded && !bForce) return true; if (!m_hasSettings) return false; std::string addonFileName = URIUtils::AddFileToFolder(m_props.path, "resources/settings.xml"); if (!m_addonXmlDoc.LoadFile(addonFileName)) { if (CFile::Exists(addonFileName)) CLog::Log(LOGERROR, "Unable to load: %s, Line %d\n%s", addonFileName.c_str(), m_addonXmlDoc.ErrorRow(), m_addonXmlDoc.ErrorDesc()); m_hasSettings = false; return false; } // Make sure that the addon XML has the settings element TiXmlElement *setting = m_addonXmlDoc.RootElement(); if (!setting || strcmpi(setting->Value(), "settings") != 0) { CLog::Log(LOGERROR, "Error loading Settings %s: cannot find root element 'settings'", addonFileName.c_str()); return false; } SettingsFromXML(m_addonXmlDoc, true); LoadUserSettings(); m_settingsLoaded = true; return true; } bool CAddon::HasUserSettings() { if (!LoadSettings()) return false; return m_userSettingsLoaded; } bool CAddon::ReloadSettings() { return LoadSettings(true); } bool CAddon::LoadUserSettings() { m_userSettingsLoaded = false; CXBMCTinyXML doc; if (doc.LoadFile(m_userSettingsPath)) m_userSettingsLoaded = SettingsFromXML(doc); return m_userSettingsLoaded; } bool CAddon::HasSettingsToSave() const { return !m_settings.empty(); } void CAddon::SaveSettings(void) { if (!HasSettingsToSave()) return; // no settings to save // break down the path into directories std::string strAddon = URIUtils::GetDirectory(m_userSettingsPath); URIUtils::RemoveSlashAtEnd(strAddon); std::string strRoot = URIUtils::GetDirectory(strAddon); URIUtils::RemoveSlashAtEnd(strRoot); // create the individual folders if (!CDirectory::Exists(strRoot)) CDirectory::Create(strRoot); if (!CDirectory::Exists(strAddon)) CDirectory::Create(strAddon); // create the XML file CXBMCTinyXML doc; SettingsToXML(doc); doc.SaveFile(m_userSettingsPath); m_userSettingsLoaded = true; CAddonMgr::GetInstance().ReloadSettings(ID());//push the settings changes to the running addon instance #ifdef HAS_PYTHON g_pythonParser.OnSettingsChanged(ID()); #endif } std::string CAddon::GetSetting(const std::string& key) { if (!LoadSettings()) return ""; // no settings available std::map<std::string, std::string>::const_iterator i = m_settings.find(key); if (i != m_settings.end()) return i->second; return ""; } void CAddon::UpdateSetting(const std::string& key, const std::string& value) { LoadSettings(); if (key.empty()) return; m_settings[key] = value; } bool CAddon::SettingsFromXML(const CXBMCTinyXML &doc, bool loadDefaults /*=false */) { if (!doc.RootElement()) return false; if (loadDefaults) m_settings.clear(); const TiXmlElement* category = doc.RootElement()->FirstChildElement("category"); if (!category) category = doc.RootElement(); bool foundSetting = false; while (category) { const TiXmlElement *setting = category->FirstChildElement("setting"); while (setting) { const char *id = setting->Attribute("id"); const char *value = setting->Attribute(loadDefaults ? "default" : "value"); if (id && value) { m_settings[id] = value; foundSetting = true; } setting = setting->NextSiblingElement("setting"); } category = category->NextSiblingElement("category"); } return foundSetting; } void CAddon::SettingsToXML(CXBMCTinyXML &doc) const { TiXmlElement node("settings"); doc.InsertEndChild(node); for (std::map<std::string, std::string>::const_iterator i = m_settings.begin(); i != m_settings.end(); ++i) { TiXmlElement nodeSetting("setting"); nodeSetting.SetAttribute("id", i->first.c_str()); nodeSetting.SetAttribute("value", i->second.c_str()); doc.RootElement()->InsertEndChild(nodeSetting); } doc.SaveFile(m_userSettingsPath); } TiXmlElement* CAddon::GetSettingsXML() { return m_addonXmlDoc.RootElement(); } void CAddon::BuildProfilePath() { m_profile = StringUtils::Format("special://profile/addon_data/%s/", ID().c_str()); } const std::string CAddon::Icon() const { if (CURL::IsFullPath(m_props.icon)) return m_props.icon; return URIUtils::AddFileToFolder(m_props.path, m_props.icon); } const std::string CAddon::LibPath() const { return URIUtils::AddFileToFolder(m_props.path, m_strLibName); } AddonVersion CAddon::GetDependencyVersion(const std::string &dependencyID) const { const ADDON::ADDONDEPS &deps = GetDeps(); ADDONDEPS::const_iterator it = deps.find(dependencyID); if (it != deps.end()) return it->second.first; return AddonVersion("0.0.0"); } void OnEnabled(const std::string& id) { // If the addon is a special, call enabled handler AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_PVRDLL) || CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_ADSPDLL)) return addon->OnEnabled(); if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_SERVICE)) std::static_pointer_cast<CService>(addon)->Start(); if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_CONTEXT_ITEM)) CContextMenuManager::GetInstance().Register(std::static_pointer_cast<CContextMenuAddon>(addon)); if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_REPOSITORY)) CRepositoryUpdater::GetInstance().ScheduleUpdate(); //notify updater there is a new addon } void OnDisabled(const std::string& id) { AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_PVRDLL, false) || CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_ADSPDLL, false)) return addon->OnDisabled(); if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_SERVICE, false)) std::static_pointer_cast<CService>(addon)->Stop(); if (CAddonMgr::GetInstance().GetAddon(id, addon, ADDON_CONTEXT_ITEM, false)) CContextMenuManager::GetInstance().Unregister(std::static_pointer_cast<CContextMenuAddon>(addon)); } void OnPreInstall(const AddonPtr& addon) { //Before installing we need to stop/unregister any local addon //that have this id, regardless of what the 'new' addon is. AddonPtr localAddon; if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_SERVICE)) std::static_pointer_cast<CService>(localAddon)->Stop(); if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_CONTEXT_ITEM)) CContextMenuManager::GetInstance().Unregister(std::static_pointer_cast<CContextMenuAddon>(localAddon)); //Fallback to the pre-install callback in the addon. //BUG: If primary extension point have changed we're calling the wrong method. addon->OnPreInstall(); } void OnPostInstall(const AddonPtr& addon, bool update, bool modal) { AddonPtr localAddon; if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_SERVICE)) std::static_pointer_cast<CService>(localAddon)->Start(); if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_CONTEXT_ITEM)) CContextMenuManager::GetInstance().Register(std::static_pointer_cast<CContextMenuAddon>(localAddon)); if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_REPOSITORY)) CRepositoryUpdater::GetInstance().ScheduleUpdate(); //notify updater there is a new addon or version addon->OnPostInstall(update, modal); } void OnPreUnInstall(const AddonPtr& addon) { AddonPtr localAddon; if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_SERVICE)) std::static_pointer_cast<CService>(localAddon)->Stop(); if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_CONTEXT_ITEM)) CContextMenuManager::GetInstance().Unregister(std::static_pointer_cast<CContextMenuAddon>(localAddon)); if (CAddonMgr::GetInstance().GetAddon(addon->ID(), localAddon, ADDON_REPOSITORY)) { CAddonDatabase database; database.Open(); database.DeleteRepository(addon->ID()); } addon->OnPreUnInstall(); } void OnPostUnInstall(const AddonPtr& addon) { addon->OnPostUnInstall(); } /** * CAddonLibrary * */ CAddonLibrary::CAddonLibrary(const cp_extension_t *ext) : CAddon(ext) , m_addonType(SetAddonType()) { } CAddonLibrary::CAddonLibrary(const AddonProps& props) : CAddon(props) , m_addonType(SetAddonType()) { } AddonPtr CAddonLibrary::Clone() const { return AddonPtr(new CAddonLibrary(*this)); } TYPE CAddonLibrary::SetAddonType() { if (Type() == ADDON_VIZ_LIBRARY) return ADDON_VIZ; else return ADDON_UNKNOWN; } } /* namespace ADDON */
30.6875
137
0.681814
krattai
695d90ca7d2170399ec7ba8c66ab5355e1365be4
363
cpp
C++
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
null
null
null
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
null
null
null
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
1
2022-03-19T16:36:09.000Z
2022-03-19T16:36:09.000Z
#include <bits/stdc++.h> using namespace std; const int N = 100; int f[N]; int main(){ int n, m; scanf("%d%d",&n, &m); for(int i = 0; i < m; i++) scanf("%d", &f[i]); sort(f, f + m); int ans = f[n-1] - f[0]; for(int i = 0; i + n - 1 < m; i++){ ans = min(ans, f[i + n - 1] - f[i]); } printf("%d\n", ans); return 0; }
18.15
50
0.424242
imeplusplus
696037a3bc442b3bb621e969d50de7e921795a43
950
hpp
C++
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
55
2018-06-19T08:22:47.000Z
2022-03-30T01:02:59.000Z
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
null
null
null
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
21
2019-04-19T15:39:08.000Z
2022-02-20T11:21:13.000Z
#ifndef C_ProjectileAttack_hpp #define C_ProjectileAttack_hpp #include "Component.hpp" #include "C_Animation.hpp" #include "Input.hpp" #include "ObjectCollection.hpp" #include "WorkingDirectory.hpp" class C_ProjectileAttack : public Component { public: C_ProjectileAttack(Object* owner); void Awake() override; void Start() override; void Update(float deltaTime) override; void SetInput(Input* input); void SetObjectCollection(ObjectCollection* objects); void SetWorkingDirectory(WorkingDirectory* workingDirectory); void SetTextureAllocator(ResourceAllocator<sf::Texture>* textureAllocator); private: void SpawnProjectile(); std::shared_ptr<C_Animation> animation; Input* input; ObjectCollection* objects; WorkingDirectory* workingDirectory; ResourceAllocator<sf::Texture>* textureAllocator; int projectileTextureID; }; #endif /* C_ProjectileAttack_hpp */
25
79
0.742105
ThatGamesGuy
696126e293cc4b8ef990ec222c6fca82d0914430
1,241
cpp
C++
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_SampleMomentCollection.cpp //! \author Alex Robinson //! \brief The sample moment collection class definition //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "FRENSIE_Archives.hpp" #include "Utility_SampleMomentCollection.hpp" EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,1,2> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,1,2> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,2,1> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,2,1> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,1,2,3,4> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,1,2,3,4> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,4,3,2,1> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,4,3,2,1> ); //---------------------------------------------------------------------------// // end Utility_SampleMomentCollection.cpp //---------------------------------------------------------------------------//
44.321429
81
0.603546
bam241
6963d1bb9788c97622a89edfdf28a71440a7195b
1,268
cc
C++
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
#include "insertion_sort.h" void insertion_sort(int *arr, int n) { for (int i = 1; i < n; ++i) { for (int j = i; j > 0; --j) { if (arr[j] < arr[j - 1]) { int tmp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = tmp; } } } } void insertion_sort2(int *arr, int n) { for (int i = 1; i < n; ++i) { int tmp = arr[i]; // search the position where the value is smaller than or equals to tmp. int j; for (j = i; j > 0; --j) { if (arr[j - 1] <= tmp) { break; } arr[j] = arr[j - 1]; } arr[j] = tmp; } } void insertion_sort3(int *arr, int n) { if (n == 0) return; int min_pos = n - 1; for (int i = n - 1; i > 0; --i) { if (arr[i - 1] < arr[min_pos]) { min_pos = i - 1; } } int tmp = arr[min_pos]; arr[min_pos] = arr[0]; arr[0] = tmp; for (int i = 2; i < n; ++i) { int tmp = arr[i]; // search the position where the value is smaller than or equals to tmp. int j = i; while (tmp < arr[j - 1]) { arr[j] = arr[j - 1]; --j; } arr[j] = tmp; } }
23.481481
80
0.391956
stn
69665ef375600e78e26e0cb11b8b112afb6df471
37,479
cpp
C++
experiments/aqfp.cpp
eletesta/mockturtle
40e4e4cfc18ff2567ad7e89bfa22df99e06ad8fb
[ "MIT" ]
null
null
null
experiments/aqfp.cpp
eletesta/mockturtle
40e4e4cfc18ff2567ad7e89bfa22df99e06ad8fb
[ "MIT" ]
null
null
null
experiments/aqfp.cpp
eletesta/mockturtle
40e4e4cfc18ff2567ad7e89bfa22df99e06ad8fb
[ "MIT" ]
null
null
null
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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 "experiments.hpp" #include <lorina/lorina.hpp> #include <mockturtle/algorithms/balancing.hpp> #include <mockturtle/algorithms/balancing/sop_balancing.hpp> #include <mockturtle/algorithms/cleanup.hpp> #include <mockturtle/algorithms/collapse_mapped.hpp> #include <mockturtle/algorithms/cut_rewriting.hpp> #include <mockturtle/algorithms/detail/database_generator.hpp> #include <mockturtle/algorithms/lut_mapping.hpp> #include <mockturtle/algorithms/mig_algebraic_rewriting.hpp> #include <mockturtle/algorithms/mig_algebraic_rewriting_buffers.hpp> #include <mockturtle/algorithms/mig_algebraic_rewriting_splitters.hpp> #include <mockturtle/algorithms/mig_feasible_resub.hpp> #include <mockturtle/algorithms/mig_resub.hpp> #include <mockturtle/algorithms/mig_resub_splitters.hpp> #include <mockturtle/algorithms/node_resynthesis.hpp> #include <mockturtle/algorithms/node_resynthesis/akers.hpp> #include <mockturtle/algorithms/node_resynthesis/exact.hpp> #include <mockturtle/algorithms/node_resynthesis/mig4_npn.hpp> #include <mockturtle/algorithms/node_resynthesis/mig_npn.hpp> #include <mockturtle/algorithms/refactoring.hpp> #include <mockturtle/io/aiger_reader.hpp> #include <mockturtle/io/blif_reader.hpp> #include <mockturtle/io/index_list.hpp> #include <mockturtle/io/verilog_reader.hpp> #include <mockturtle/io/write_verilog.hpp> #include <mockturtle/networks/aig.hpp> #include <mockturtle/views/depth_view.hpp> #include <mockturtle/views/fanout_limit_view.hpp> #include <mockturtle/views/fanout_view.hpp> #include <mockturtle/views/mapping_view.hpp> #include <fmt/format.h> #include <string> #include <vector> /*namespace detail { template<class Ntk> struct jj_cost { uint32_t operator()( Ntk const& ntk, mockturtle::node<Ntk> const& n ) const { uint32_t cost = 0; if ( ntk.fanout_size( n ) == 1 ) cost = ntk.fanout_size( n ); else if ( ntk.fanout_size( n ) <= 4 ) cost = 3; else cost = 11; return cost; } }; template<class Ntk> int used_as_po( Ntk const& ntk, mockturtle::node<Ntk> const& n ) { int count = 0; ntk.foreach_po( [&]( auto s ) { if ( ntk.get_node( s ) == n ) count++; return true; } ); return count; } template<class Ntk> struct fanout_cost_depth_local { uint32_t operator()( Ntk const& ntk, mockturtle::node<Ntk> const& n ) const { uint32_t cost = 0; if ( ntk.is_pi( n ) ) cost = 0; else if ( ntk.fanout_size( n ) + used_as_po( n ) == 1 ) cost = 1; else if ( ( ntk.fanout_size( n ) + used_as_po( n ) > 1 ) && ( ntk.fanout_size( n ) + used_as_po( n ) < 5 ) ) cost = 2; else if ( ( ntk.fanout_size( n ) + used_as_po( n ) > 4 ) ) //&& ( ntk.fanout_size( n ) < 17 ) ) cost = 3; return cost; } }; template<class Ntk> uint32_t compute_maxfanout( Ntk ntk ) { auto max_fanout = 0; ntk.foreach_gate( [&]( auto const& n ) { if ( ntk.fanout_size( n ) + used_as_po( n ) > max_fanout ) max_fanout = ntk.fanout_size( n ) + used_as_po( n ); return true; } ); return max_fanout; } template<class Ntk> int compute_buffers( Ntk mig ) { mockturtle::depth_view_params ps_d; mockturtle::depth_view depth_mig{mig, detail::fanout_cost_depth_local<Ntk>(), ps_d}; std::vector<int> buffers( mig.size(), 0 ); int number_buff = 0; mig.foreach_gate( [&]( auto f ) { auto main_depth = depth_mig.level( f ); mig.foreach_fanin( f, [&]( auto const& s ) { if ( mig.is_pi( mig.get_node( s ) ) ) return true; auto index = mig.node_to_index( mig.get_node( s ) ); if ( index == 0 ) return true; int diff = main_depth - 1 - depth_mig.level( mig.get_node( s ) ) - buffers[index]; if ( diff >= 0 ) { buffers[index] = buffers[index] + diff; } return true; } ); } ); auto total_depth = depth_mig.depth(); mig.foreach_po( [&]( auto s, auto i ) { if ( depth_mig.level( mig.get_node( s ) ) == total_depth ) return true; auto index = mig.node_to_index( mig.get_node( s ) ); if ( index == 0 ) return true; int diff = total_depth - depth_mig.level( mig.get_node( s ) ) - buffers[index]; if ( diff >= 0 ) { buffers[index] = buffers[index] + diff; } return true; } ); for ( auto h = 0u; h < buffers.size(); h++ ) { number_buff = number_buff + buffers[h]; } return number_buff; } template<class Ntk> int cost( Ntk ntk, mockturtle::node<Ntk> const& n ) { auto cost = 0; if ( ( ntk.fanout_size( n ) + used_as_po( n ) > 1 ) && ( ntk.fanout_size( n ) + used_as_po( n ) < 5 ) ) cost = 1; else if ( ( ntk.fanout_size( n ) + used_as_po( n ) > 4 ) ) //&& ( ntk.fanout_size( n ) < 17 ) ) cost = 2; return cost; } template<class Ntk> int compute_buffers_not_shared( Ntk mig ) { mockturtle::depth_view_params ps_d; mockturtle::depth_view depth_mig{mig, detail::fanout_cost_depth_local<Ntk>(), ps_d}; std::vector<std::vector<int>> buffers( mig.size() ); int number_buff = 0; mig.foreach_gate( [&]( auto f ) { auto main_depth = depth_mig.level( f ); auto index2 = mig.node_to_index( f ); mig.foreach_fanin( f, [&]( auto const& s ) { auto index = mig.node_to_index( mig.get_node( s ) ); if ( index == 0 ) return true; if ( is_pi( ntk.get_node( s ) ) ) /* this will not balance the pis return true; int diff = main_depth - 1 - depth_mig.level( mig.get_node( s ) ) - detail::cost( mig, f ); for ( auto g = 0u; g < diff; g++ ) { if ( g < buffers[index].size() ) buffers[index][g]++; else buffers[index].push_back( 1 ); } return true; } ); } ); // balacing pos auto total_depth = depth_mig.depth(); mig.foreach_po( [&]( auto s ) { if ( depth_mig.level( mig.get_node( s ) ) == total_depth ) return true; auto index = mig.node_to_index( mig.get_node( s ) ); if ( index == 0 ) return true; int diff = total_depth - depth_mig.level( mig.get_node( s ) ); // - buffers[index]; for ( auto g = 0u; g < diff; g++ ) { if ( g < buffers[index].size() ) buffers[index][g]++; else buffers[index].push_back( 1 ); } return true; } ); for ( auto h = 0u; h < buffers.size(); h++ ) { if ( buffers[h].size() == 0 ) continue; number_buff = number_buff + buffers[h].size(); for ( auto g = 0; g < buffers[h].size(); g++ ) { int x = buffers[h][g] / 4 + ( buffers[h][g] % 4 != 0 ); number_buff = number_buff + x - 1; } } return number_buff; } template<class Ntk> uint32_t JJ_number_final( Ntk ntk ) { auto JJ = 0; ntk.foreach_gate( [&]( auto const& n ) { if ( ntk.fanout_size( n ) + used_as_po( n ) == 1 ) JJ = JJ + 6; else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 4 ) JJ = JJ + 8; else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 16 ) JJ = JJ + 16; // this should not happen in the new limit fanout view else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 20 ) JJ = JJ + 16 + 8; else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 32 ) JJ = JJ + 16 * 2; else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 36 ) JJ = JJ + 16 * 2 + 8; else if ( ntk.fanout_size( n ) + used_as_po( n ) <= 48 ) JJ = JJ + 16 * 3; return true; } ); auto buffers = compute_buffers_not_shared( ntk ); JJ = JJ + buffers * 2; return JJ; } template<class Ntk> uint32_t compute_maxfanout_inputs( Ntk ntk ) { auto max_fanout = 0; ntk.foreach_pi( [&]( auto const& n, auto i ) { if ( ntk.fanout_size( n ) + used_as_po( n ) > max_fanout ) max_fanout = ntk.fanout_size( n ) + used_as_po( n ); return true; } ); return max_fanout; } template<class Ntk> uint32_t compute_fanout4_inputs( Ntk ntk ) { auto fanout4 = 0; ntk.foreach_pi( [&]( auto const& n, auto i ) { if ( ntk.fanout_size( n ) + used_as_po( n ) > 16 ) fanout4++; return true; } ); return fanout4; } template<class Ntk> uint32_t compute_fanout4( Ntk ntk ) { auto fanout4 = 0; ntk.foreach_gate( [&]( auto const& n, auto i ) { if ( ntk.fanout_size( n ) + used_as_po( n ) > 16 ) fanout4++; return true; } ); return fanout4; } } // namespace detail template<typename Ntk> mockturtle::klut_network lut_map( Ntk const& ntk, uint32_t k = 4 ) { mockturtle::write_verilog( ntk, "/tmp/network.v" ); system( fmt::format( "../../abc/abc -q \"/tmp/network.v; &get; &if -a -K {}; &put; write_blif /tmp/output.blif\"", k ).c_str() ); mockturtle::klut_network klut; if ( lorina::read_blif( "/tmp/output.blif", mockturtle::blif_reader( klut ) ) != lorina::return_code::success ) { std::cout << "ERROR 1" << std::endl; std::abort(); return klut; } return klut; } using view_t = mockturtle::depth_view<mockturtle::fanout_view<mockturtle::mig_network>>; using view_f = mockturtle::fanout_view<mockturtle::mig_network>; void example_aqfp() { using namespace experiments; /* load database from file mockturtle::mig_network mig_db; read_verilog( "db.v", mockturtle::verilog_reader( mig_db ) ); /* option 1: XMG strategy using database from file mockturtle::mig4_npn_resynthesis_params ps; mockturtle::mig4_npn_resynthesis<mockturtle::mig_network> mig_resyn( mockturtle::detail::to_index_list( mig_db ), ps ); experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, float, float, bool> exp( "mig_aqfp", "benchmark", "size MIG", "depth", "size MIG our", "depth our", "impro. size", "impro. depth ", "eq cec" ); std::map<std::string, std::tuple<uint32_t, uint32_t>> opt_aig; opt_aig.emplace( "c432", std::make_tuple( 2784, 36 ) ); opt_aig.emplace( "c499", std::make_tuple( 4982, 27 ) ); opt_aig.emplace( "c880", std::make_tuple( 5104, 35 ) ); opt_aig.emplace( "c1355", std::make_tuple( 4790, 25 ) ); opt_aig.emplace( "c1908", std::make_tuple( 6164, 41 ) ); opt_aig.emplace( "c2670", std::make_tuple( 11574, 26 ) ); opt_aig.emplace( "c3540", std::make_tuple( 11618, 58 ) ); opt_aig.emplace( "c5315", std::make_tuple( 22860, 49 ) ); opt_aig.emplace( "c6288", std::make_tuple( 52806, 176 ) ); opt_aig.emplace( "c7552", std::make_tuple( 23834, 52 ) ); std::map<std::string, std::tuple<uint32_t, uint32_t>> soa_mig; soa_mig.emplace( "c432", std::make_tuple( 3072, 39 ) ); soa_mig.emplace( "c880", std::make_tuple( 5914, 30 ) ); soa_mig.emplace( "c1908", std::make_tuple( 6818, 38 ) ); soa_mig.emplace( "c5315", std::make_tuple( 30910, 40 ) ); soa_mig.emplace( "c6288", std::make_tuple( 25870, 94 ) ); std::map<std::string, std::tuple<uint32_t, uint32_t>> soa_mig_sd; soa_mig_sd.emplace( "c17", std::make_tuple( 6, 3 ) ); soa_mig_sd.emplace( "c432", std::make_tuple( 121, 26 ) ); soa_mig_sd.emplace( "c880", std::make_tuple( 274, 18 ) ); soa_mig_sd.emplace( "c1908", std::make_tuple( 263, 21 ) ); soa_mig_sd.emplace( "c5315", std::make_tuple( 1248, 23 ) ); soa_mig_sd.emplace( "c6288", std::make_tuple( 984, 48 ) ); for ( auto const& benchmark : aqfp_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); /* read aig mockturtle::aig_network aig; if ( lorina::read_aiger( experiments::benchmark_aqfp_path( benchmark ), mockturtle::aiger_reader( aig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } mockturtle::depth_view_params ps_d; mockturtle::depth_view aig_d{aig}; mockturtle::depth_view aig_d_s{aig, detail::fanout_cost_depth_local<mockturtle::aig_network>(), ps_d}; //auto const size_a = aig.num_gates(); //auto const depth_a = aig_d.depth(); auto const JJ_a = std::get<0>( soa_mig_sd[benchmark] ); auto const depth_a_splitters = std::get<1>( soa_mig_sd[benchmark] ); //auto const max_fanout_a = detail::compute_maxfanout( aig ); //auto const node_larger_16_a = detail::compute_fanout4( aig ); /* LUT map AIG into k-LUT network auto klut = lut_map( aig, 4u ); mockturtle::mig_network mig1; mig1 = mockturtle::node_resynthesis<mockturtle::mig_network>( klut, mig_resyn ); mockturtle::depth_view mig1_d{mig1}; mockturtle::depth_view mig1_d_s{mig1, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; /*auto const size_a = mig1.num_gates(); auto const depth_a = mig1_d.depth(); auto const JJ_a = JJ_number_final(mig1); auto const depth_a_splitters = mig1_d_s.depth(); auto const max_fanout_a = detail::compute_maxfanout( mig1 ); auto const node_larger_16_a = detail::compute_fanout4( mig1 ); std::cout << " cut rewriting ... \n"; mockturtle::cut_rewriting_params ps; ps.cut_enumeration_ps.cut_size = 4; auto i = 0; while ( i < 10 ) { i++; mig1 = cut_rewriting( mig1, mig_resyn, ps, nullptr ); //mig1 = cut_rewriting<mockturtle::mig_network, decltype( mig_resyn ), mockturtle::fanout_cost<mockturtle::mig_network>>( mig1, mig_resyn, ps, nullptr ); //cut_rewriting_with_compatibility_graph( mig1, mig_resyn, ps, nullptr, detail::fanout_cost<mockturtle::mig_network>() ); mig1 = cleanup_dangling( mig1 ); } mockturtle::depth_view mig1_dd{mig1}; mockturtle::depth_view mig1_dd_s{mig1, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto size_b = mig1.num_gates(); auto depth_b = mig1_dd.depth(); auto depth_b_splitters = mig1_dd_s.depth(); auto max_fanout_b = detail::compute_maxfanout( mig1 ); auto node_larger_16_b = detail::compute_fanout4( mig1 ); // Option 1 -- not consider splitters in the delay -- limit fanout // Option 2 -- consider splitters // -> almost same results std::cout << " depth ... \n"; mockturtle::mig_algebraic_depth_rewriting_params ps2; while ( true ) { mockturtle::depth_view mig1_dd_d{mig1}; auto depth = mig1_dd_d.depth(); ps2.strategy = mockturtle::mig_algebraic_depth_rewriting_params::aggressive; //ps2.allow_area_increase = false; //mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps2 ); mig_algebraic_depth_rewriting( mig1_dd_d, ps2 ); ps2.strategy = mockturtle::mig_algebraic_depth_rewriting_params::dfs; //mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps2 ); mig_algebraic_depth_rewriting( mig1_dd_d, ps2 ); if ( mig1_dd_d.depth() >= depth ) break; mig1 = mig1_dd_d; mig1 = cleanup_dangling( mig1 ); } mockturtle::mig_network mig2 = mig1_dd; mig2 = cleanup_dangling( mig2 ); mockturtle::depth_view mig2_dd{mig2}; mockturtle::depth_view mig2_dd_s{mig2, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto size_c = mig2.num_gates(); auto depth_c = mig2_dd.depth(); auto depth_c_splitters = mig2_dd_s.depth(); auto max_fanout_c = detail::compute_maxfanout( mig2 ); auto node_larger_16_c = detail::compute_fanout4( mig2 ); size_b = mig2.num_gates(); depth_b = mig2_dd.depth(); depth_b_splitters = mig2_dd_s.depth(); max_fanout_b = detail::compute_maxfanout( mig2 ); node_larger_16_b = detail::compute_fanout4( mig2 ); std::cout << " resub ... \n"; mockturtle::resubstitution_params ps_r; ps_r.max_divisors = 150; ps_r.max_inserts = 1; while ( true ) { auto size_o = mig2.num_gates(); //mockturtle::depth_view mig2_dd_r{mig2, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; //mig_resubstitution_splitters( mig2_dd_r, ps_r ); mockturtle::depth_view mig2_dd_r{mig2}; mig_resubstitution( mig2_dd_r, ps_r ); mig2 = mig2_dd_r; mig2 = cleanup_dangling( mig2 ); if ( mig2.num_gates() >= size_o ) break; } while ( true ) { mockturtle::depth_view mig1_dd_d{mig2}; auto depth = mig1_dd_d.depth(); ps2.strategy = mockturtle::mig_algebraic_depth_rewriting_params::aggressive; //ps2.allow_area_increase = false; //mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps2 ); mig_algebraic_depth_rewriting( mig1_dd_d, ps2 ); ps2.strategy = mockturtle::mig_algebraic_depth_rewriting_params::dfs; //mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps2 ); mig_algebraic_depth_rewriting( mig1_dd_d, ps2 ); if ( mig1_dd_d.depth() >= depth ) break; mig2 = mig1_dd_d; mig2 = cleanup_dangling( mig2 ); } mig2 = cleanup_dangling( mig2 ); std::cout << " resub ... \n"; while ( true ) { auto size_o = mig2.num_gates(); //mockturtle::depth_view mig2_dd_r{mig2, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; //mig_resubstitution_splitters( mig2_dd_r, ps_r ); mockturtle::depth_view mig2_dd_r{mig2}; mig_resubstitution( mig2, ps_r ); //mig2 = mig2_dd_r; mig2 = cleanup_dangling( mig2 ); if ( mig2.num_gates() >= size_o ) break; } mockturtle::depth_view mig3_dd{mig2}; mockturtle::depth_view mig3_dd_s{mig2, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; size_c = mig2.num_gates(); depth_c = mig3_dd.depth(); depth_c_splitters = mig3_dd_s.depth(); auto const JJ_c = detail::JJ_number_final( mig2 ); max_fanout_c = detail::compute_maxfanout( mig2 ); node_larger_16_c = detail::compute_fanout4( mig2 ); //float impr_JJ = ( float( JJ_a ) - float( JJ_c ) ) / float( JJ_a ) * 100; //float impr_levels = ( float( depth_a_splitters ) - float( depth_c_splitters ) ) / float( depth_a_splitters ) * 100; float impr_size = ( float( JJ_a ) - float( size_c ) ) / float( JJ_a ) * 100; float impr_levels = ( float( depth_a_splitters ) - float( depth_c ) ) / float( depth_a_splitters ) * 100; //mockturtle::write_verilog( mig2, fmt::format( "{}_mig_aqfp.v", benchmark ) ); exp( benchmark, JJ_a, depth_a_splitters, size_c, depth_c, //max_fanout_c, node_larger_16_c, impr_size, impr_levels, experiments::abc_cec_aqfp( mig2, benchmark ) ); } exp.save(); exp.table(); } void start_aig() { using namespace experiments; experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, int, int, uint32_t, uint32_t, bool> exp( "mig_aqfp", "benchmark", "size Soa AIG", "depthsoa AIG", "size our AIG", "depth our AIG", "diff size", "diff depth ", "max fanout", "# nodes > 16", "eq cec" ); std::map<std::string, std::tuple<uint32_t, uint32_t>> opt_aig; opt_aig.emplace( "c17", std::make_tuple( 6, 3 ) ); opt_aig.emplace( "c432", std::make_tuple( 122, 26 ) ); opt_aig.emplace( "c880", std::make_tuple( 306, 27 ) ); opt_aig.emplace( "c1908", std::make_tuple( 296, 21 ) ); opt_aig.emplace( "c5315", std::make_tuple( 1325, 26 ) ); opt_aig.emplace( "c6288", std::make_tuple( 1870, 89 ) ); for ( auto const& benchmark : aqfp_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); /* read aig mockturtle::aig_network aig; if ( lorina::read_aiger( experiments::benchmark_aqfp_path( benchmark ), mockturtle::aiger_reader( aig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } auto const size_a = std::get<0>( opt_aig[benchmark] ); auto const depth_a = std::get<1>( opt_aig[benchmark] ); mockturtle::depth_view aig_d{aig}; auto const size_b = aig.num_gates(); auto const depth_b = aig_d.depth(); auto const max_fanout_b = detail::compute_maxfanout( aig ); auto const node_larger_16_b = detail::compute_fanout4( aig ); exp( benchmark, size_a, depth_a, size_b, depth_b, //max_fanout_c, node_larger_16_c, size_a - size_b, depth_a - depth_b, max_fanout_b, node_larger_16_b, experiments::abc_cec_aqfp( aig, benchmark ) ); } exp.save(); exp.table(); } void check_cost() { using namespace experiments; experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t> exp( "mig_aqfp", "benchmark", "size", "depth", "# JJs", "Depth JJs", "Number of buffers" ); for ( auto const& benchmark : test_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); //if ( benchmark != "test2" ) //continue; /* read aig mockturtle::mig_network mig; if ( lorina::read_verilog( experiments::benchmark_test_path( benchmark ), mockturtle::verilog_reader( mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } mig = cleanup_dangling( mig ); mockturtle::depth_view_params ps_d; mockturtle::depth_view mig_d{mig}; mockturtle::depth_view mig_d_s{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto const JJ_b = detail::JJ_number_final( mig ); auto const depth_b_spli = mig_d_s.depth(); auto const size_b = mig.num_gates(); auto const depth_b = mig_d.depth(); auto const buffers = detail::compute_buffers_not_shared( mig ); exp( benchmark, size_b, depth_b, JJ_b, depth_b_spli, buffers ); } exp.save(); exp.table(); } void debug() { mockturtle::mig_network mig; auto benchmark = "c6288"; if ( read_verilog( "c6288_mig_aqfp.v", mockturtle::verilog_reader( mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } mockturtle::resubstitution_params ps; ps.max_inserts = 1; ps.max_divisors = 150; auto i = 0; while ( true ) { i++; auto size_o = mig.num_gates(); mig_resubstitution( mig, ps ); mig = cleanup_dangling( mig ); if ( experiments::abc_cec_aqfp( mig, benchmark ) == false ) { std::cout << "iteration numero " << i << std::endl; break; } if ( mig.num_gates() >= size_o ) break; } mockturtle::write_verilog( mig, fmt::format( "{}_mig_resub.v", benchmark ) ); } void start_mig() { using namespace experiments; mockturtle::mig_network mig_db; read_verilog( "db.v", mockturtle::verilog_reader( mig_db ) ); /* option 1: XMG strategy using database from file mockturtle::mig4_npn_resynthesis_params ps; ps.multiple_depth = true; mockturtle::mig4_npn_resynthesis<mockturtle::mig_network> mig_resyn( mockturtle::detail::to_index_list( mig_db ), ps ); experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, int, int, uint32_t, uint32_t, bool> exp( "mig_aqfp", "benchmark", "size Soa MIG", "depth Soa MIG", "size our AIG", "depth our MIG", "diff size", "diff depth ", "max fanout", "# nodes > 16", "eq cec" ); std::map<std::string, std::tuple<uint32_t, uint32_t>> opt_mig; opt_mig.emplace( "c17", std::make_tuple( 6, 3 ) ); opt_mig.emplace( "c432", std::make_tuple( 121, 26 ) ); opt_mig.emplace( "c880", std::make_tuple( 274, 18 ) ); opt_mig.emplace( "c1908", std::make_tuple( 263, 21 ) ); opt_mig.emplace( "c5315", std::make_tuple( 1248, 23 ) ); opt_mig.emplace( "c6288", std::make_tuple( 984, 48 ) ); for ( auto const& benchmark : aqfp_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); /* read aig mockturtle::mig_network mig; if ( lorina::read_aiger( experiments::benchmark_aqfp_path( benchmark ), mockturtle::aiger_reader( mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } auto const size_a = std::get<0>( opt_mig[benchmark] ); auto const depth_a = std::get<1>( opt_mig[benchmark] ); mockturtle::cut_rewriting_params ps_c; ps_c.cut_enumeration_ps.cut_size = 4; while ( true ) { std::cout << " wowo\n"; auto size_opt = mig.num_gates(); mig = cut_rewriting( mig, mig_resyn, ps_c, nullptr ); mig = cleanup_dangling( mig ); if ( mig.num_gates() >= size_opt ) break; } mockturtle::depth_view aig_d{mig}; auto const size_b = mig.num_gates(); auto const depth_b = aig_d.depth(); auto const max_fanout_b = detail::compute_maxfanout( mig ); auto const node_larger_16_b = detail::compute_fanout4( mig ); exp( benchmark, size_a, depth_a, size_b, depth_b, //max_fanout_c, node_larger_16_c, size_a - size_b, depth_a - depth_b, max_fanout_b, node_larger_16_b, experiments::abc_cec_aqfp( mig, benchmark ) ); } exp.save(); exp.table(); } void flow_mig() { using namespace experiments; mockturtle::mig_network mig_db; read_verilog( "db.v", mockturtle::verilog_reader( mig_db ) ); /* option 1: XMG strategy using database from file mockturtle::mig4_npn_resynthesis_params ps; ps.multiple_depth = true; mockturtle::mig4_npn_resynthesis<mockturtle::mig_network> mig_resyn( mockturtle::detail::to_index_list( mig_db ), ps ); experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, int, int, uint32_t, uint32_t, bool> exp( "mig_aqfp", "benchmark", "# JJs Soa MIG", "depth JJs Soa MIG", "# JJs opt. MIG", "depth JJs opt. MIG", "diff size", "diff depth ", "max fanout", "# nodes > 16", "eq cec" ); std::map<std::string, std::tuple<uint32_t, uint32_t>> opt_mig; opt_mig.emplace( "c17", std::make_tuple( 6, 3 ) ); opt_mig.emplace( "c432", std::make_tuple( 121, 26 ) ); opt_mig.emplace( "c880", std::make_tuple( 274, 18 ) ); opt_mig.emplace( "c1908", std::make_tuple( 263, 21 ) ); opt_mig.emplace( "c5315", std::make_tuple( 1248, 23 ) ); opt_mig.emplace( "c6288", std::make_tuple( 984, 48 ) ); std::map<std::string, std::tuple<uint32_t, uint32_t>> soa_mig; soa_mig.emplace( "c17", std::make_tuple( 60, 5 ) ); soa_mig.emplace( "c432", std::make_tuple( 3072, 39 ) ); soa_mig.emplace( "c880", std::make_tuple( 5914, 30 ) ); soa_mig.emplace( "c1908", std::make_tuple( 6818, 38 ) ); soa_mig.emplace( "c5315", std::make_tuple( 30910, 40 ) ); soa_mig.emplace( "c6288", std::make_tuple( 25870, 94 ) ); for ( auto const& benchmark : aqfp_benchmarks() ) { fmt::print( "[i] processing {}\n", benchmark ); /* read aig mockturtle::mig_network mig; if ( lorina::read_aiger( experiments::benchmark_aqfp_path( benchmark ), mockturtle::aiger_reader( mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } auto const size_a = std::get<0>( soa_mig[benchmark] ); auto const depth_a = std::get<1>( soa_mig[benchmark] ); mockturtle::cut_rewriting_params ps_c; ps_c.cut_enumeration_ps.cut_size = 4; while ( true ) { std::cout << " wowo\n"; auto size_opt = mig.num_gates(); mig = cut_rewriting( mig, mig_resyn, ps_c, nullptr ); mig = cleanup_dangling( mig ); if ( mig.num_gates() >= size_opt ) break; } std::cout << " depth ... \n"; mockturtle::mig_algebraic_depth_rewriting_params ps_a; mockturtle::depth_view mig1_dd{mig}; //, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; while ( true ) { mockturtle::depth_view mig1_dd_d{mig}; auto depth = mig1_dd_d.depth(); ps_a.overhead = 1.1; ps_a.strategy = mockturtle::mig_algebraic_depth_rewriting_params::aggressive; mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps_a ); mig = mig1_dd_d; mig = cleanup_dangling( mig ); //ps_a.strategy = mockturtle::mig_algebraic_depth_rewriting_params::dfs; //mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps_a ); //mig = mig1_dd_d; //mig = cleanup_dangling( mig ); if ( mig1_dd_d.depth() >= depth ) break; } mockturtle::depth_view_params ps_d; mockturtle::depth_view mig2_dd{mig}; mockturtle::depth_view mig2_dd_s{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; std::cout << " resub ... \n"; mockturtle::resubstitution_params ps_r; ps_r.max_divisors = 150; ps_r.max_inserts = 1; //ps_r.progress = true; auto i = 0; while ( true ) { //i++; // if ( i > 1 ) // break; auto size_o = mig.num_gates(); mockturtle::depth_view mig2_dd_r{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; mig_resubstitution_splitters( mig2_dd_r, ps_r ); mig = mig2_dd_r; mig = cleanup_dangling( mig ); if ( mig.num_gates() >= size_o ) break; } while ( true ) { mockturtle::depth_view mig1_dd_d{mig}; auto depth = mig1_dd_d.depth(); mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps_a ); mig = mig1_dd_d; mig = cleanup_dangling( mig ); if ( mig1_dd_d.depth() >= depth ) break; } mig = cleanup_dangling( mig ); std::cout << " resub ... \n"; i = 0; while ( true ) { i++; if ( i > 2 ) break; auto size_o = mig.num_gates(); mockturtle::depth_view mig2_dd_r{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; mig_resubstitution_splitters( mig2_dd_r, ps_r ); mig = mig2_dd_r; mig = cleanup_dangling( mig ); if ( mig.num_gates() >= size_o ) break; } mockturtle::depth_view mig3_dd{mig}; mockturtle::depth_view mig3_dd_s{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto const size_c = mig.num_gates(); auto const depth_c = mig3_dd.depth(); auto const depth_c_splitters = mig3_dd_s.depth(); auto const JJ_c = detail::JJ_number_final( mig ); auto const max_fanout_c = detail::compute_maxfanout( mig ); auto const node_larger_16_c = detail::compute_fanout4( mig ); exp( benchmark, size_a, depth_a, JJ_c, depth_c_splitters, size_a - JJ_c, depth_a - depth_c_splitters, max_fanout_c, node_larger_16_c, experiments::abc_cec_aqfp( mig, benchmark ) ); } exp.save(); exp.table(); } void flow_mig_final() { using namespace experiments; mockturtle::mig_network mig_db; read_verilog( "db.v", mockturtle::verilog_reader( mig_db ) ); /* option 1: XMG strategy using database from file mockturtle::mig4_npn_resynthesis_params ps; using view_mig_t = mockturtle::fanout_limit_view<mockturtle::mig_network>; //ps.multiple_depth = true; mockturtle::mig4_npn_resynthesis<mockturtle::mig_network> mig_resyn( mockturtle::detail::to_index_list( mig_db ), ps ); experiments::experiment<std::string, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, float, uint32_t, float, uint32_t, uint32_t, uint32_t, float, uint32_t, float, bool> exp( "mig_aqfp", "benchmark", "size MIG", "Size MIG f", "depth MIG", "max. fanout", "# nodes > 16", "JJs MIG", "Levels JJs MIG", "size Opt. MIG", "SIze Opt MIG f", "imrp. size", "depth Opt. MIG", "imrp. depth", "max. fanout Opt MIG", "# nodes > 16 Opt MIG", "JJs Opt MIG", "imrp. JJS", "Levels JJs Opt MIG", "imrp Levels", "eq cec" ); for ( auto const& benchmark : aqfp_benchmarks() ) { if ( benchmark != "c5315" ) continue; fmt::print( "[i] processing {}\n", benchmark ); /* read aig mockturtle::mig_network mig; if ( lorina::read_verilog( experiments::benchmark_aqfp_path( benchmark ), mockturtle::verilog_reader( mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } std::cout << "_____________________\n"; mig.foreach_gate( [&]( const auto& n ) { if ( mig.fanout_size( n ) >= 16 ) { std::cout << "[mig] node " << n << " has " << mig.fanout_size( n ) << " fanouts" << std::endl; } } ); mockturtle::depth_view_params ps_d; mockturtle::depth_view mig_d2{mig}; mockturtle::depth_view mig2_dd2{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto const size_b = mig.num_gates(); auto const depth_b = mig_d2.depth(); auto const depth_b_splitters = mig2_dd2.depth(); auto const JJ_b = detail::JJ_number_final( mig ); auto const max_fanout_b = detail::compute_maxfanout( mig ); auto const node_larger_16_b = detail::compute_fanout4( mig ); mockturtle::fanout_limit_view_params ps{15u}; mockturtle::mig_network mig2; mockturtle::fanout_limit_view lim_mig{mig2, ps}; if ( lorina::read_verilog( experiments::benchmark_aqfp_path( benchmark ), mockturtle::verilog_reader( lim_mig ) ) != lorina::return_code::success ) { std::cout << "ERROR 2" << std::endl; std::abort(); return; } lim_mig.foreach_gate( [&]( const auto& n ) { if ( lim_mig.fanout_size( n ) >= 16 ) { std::cout << "[lim_mig] node " << n << " has " << lim_mig.fanout_size( n ) << " fanouts" << std::endl; } } ); auto const size_fanout_b = lim_mig.num_gates(); // auto klut = lut_map( mig, 4u ); //&lim_mig = mockturtle::node_resynthesis<view_mig_t>( klut, mig_resyn ); //mig = mockturtle::node_resynthesis<mockturtle::mig_network>( klut, mig_resyn ); //mig = cleanup_dangling( mig ); //mockturtle::write_verilog( mig, fmt::format( "../experiments/benchmarks_aqfp/{}.v", benchmark ) ); //&lim_mig = cleanup_dangling( lim_mig ); //mockturtle::depth_view mig2_d2_f{lim_mig}; auto i = 0; while ( true ) { i++; if ( i > 10 ) break; mockturtle::mig_algebraic_depth_rewriting_params ps_a; mockturtle::depth_view mig1_dd_d{lim_mig}; auto depth = mig1_dd_d.depth(); ps_a.overhead = 1; ps_a.strategy = mockturtle::mig_algebraic_depth_rewriting_params::aggressive; ps_a.allow_area_increase = false; mig_algebraic_depth_rewriting_splitters( mig1_dd_d, ps_a ); mig = mig1_dd_d; mig = cleanup_dangling( mig ); //mockturtle::depth_view mig2_dd_s{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; mockturtle::resubstitution_params ps_r; ps_r.max_divisors = 200; ps_r.max_inserts = 1; auto size_o = mig.num_gates(); mockturtle::depth_view mig2_dd_r{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; //mig_resubstitution( mig, ps_r ); mig_resubstitution_splitters( mig2_dd_r, ps_r ); mig = mig2_dd_r; mig = cleanup_dangling( mig ); auto const mig2 = cleanup_dangling( mig ); mockturtle::akers_resynthesis<mockturtle::mig_network> resyn; refactoring( mig, resyn, {}, nullptr, detail::jj_cost<mockturtle::mig_network>() ); mig = cleanup_dangling( mig ); mockturtle::depth_view mig2_dd_a{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; mockturtle::depth_view mig2_dd{mig}; if ( ( mig.num_gates() > mig2.num_gates() ) || ( mig2_dd_a.depth() > mig2_dd_r.depth() ) || ( mig2_dd.depth() > mig1_dd_d.depth() ) ) mig = mig2; mig = cleanup_dangling( mig ); mockturtle::depth_view mig2_dd_d_y{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; mockturtle::depth_view mig2_dd_y{mig}; if ( ( mig.num_gates() >= size_o ) || ( mig1_dd_d.depth() >= depth ) ) break; } mockturtle::depth_view mig3_dd{mig}; mockturtle::depth_view mig3_dd_s{mig, detail::fanout_cost_depth_local<mockturtle::mig_network>(), ps_d}; auto const size_c = mig.num_gates(); auto const size_fanout_c = 0; //lim_mig2.num_gates(); auto const depth_c = mig3_dd.depth(); //assert( depth_c == mig3_dd_f.depth() ); auto const depth_c_splitters = mig3_dd_s.depth(); auto const JJ_c = detail::JJ_number_final( mig ); auto const max_fanout_c = detail::compute_maxfanout( mig ); auto const node_larger_16_c = detail::compute_fanout4( mig ); exp( benchmark, size_b, size_fanout_b, depth_b, max_fanout_b, node_larger_16_b, JJ_b, depth_b_splitters, size_c, size_fanout_c, float( float( size_b - size_c ) / float( size_b ) * 100 ), depth_c, float( float( depth_b - depth_c ) / float( depth_b ) * 100 ), max_fanout_c, node_larger_16_c, JJ_c, float( float( JJ_b - JJ_c ) / float( JJ_b ) * 100 ), depth_c_splitters, float( float( depth_b_splitters - depth_c_splitters ) / float( depth_b_splitters ) * 100 ), experiments::abc_cec_aqfp( mig, benchmark ) ); } exp.save(); exp.table(); }*/ int main() { //flow_mig_final(); return 0; }
36.002882
547
0.653112
eletesta
69667186065462c9306a5071a4ddc0aac6fb719b
1,447
cpp
C++
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
#include "PackageDeclaration.hpp" #include <assert.h> namespace Dwarf { PackageDeclaration::PackageDeclaration (std::string name, std::vector<Declaration *> declarationsInside) : name_ (name), declarationsInside_ (declarationsInside) { } PackageDeclaration::~PackageDeclaration () { if (!declarationsInside_.empty ()) for (int index = 0; index < declarationsInside_.size (); index++) delete declarationsInside_.at (index); declarationsInside_.clear (); } Declaration *PackageDeclaration::GetDeclarationByIndex (int index) { assert (index < declarationsInside_.size ()); return declarationsInside_.at (index); } int PackageDeclaration::GetDeclarationsCount () { return declarationsInside_.size (); } std::string PackageDeclaration::GetName () { return name_; } std::string PackageDeclaration::GetType () { return "Package"; } std::string PackageDeclaration::ToString (int addSpacesIndentation) { std::string result; std::string indent = ""; if (addSpacesIndentation > 0) for (int index = 0; index < addSpacesIndentation; index++) indent += " "; result += indent + "[package " + name_ + "; content:\n"; for (int index = 0; index < declarationsInside_.size (); index++) result += declarationsInside_.at (index)->ToString (addSpacesIndentation + 4) + "\n"; result += indent + "end of package " + name_ + "]"; return result; } }
24.525424
106
0.67519
KonstantinTomashevich
696bc84d688fd35ea25b6456adca2b8d8b5a2073
4,894
hpp
C++
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
1
2022-02-08T14:01:20.000Z
2022-02-08T14:01:20.000Z
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
null
null
null
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
null
null
null
/*! * Copyright (c) 2012, 2013 BlackBerry Limited. * * 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. */ #ifndef APP_HPP #define APP_HPP #include "pushwoosh/PushNotificationService.h" #include "service/PushHandler.hpp" #include <bb/cascades/GroupDataModel> #include <bb/system/InvokeManager> #include <bb/system/SystemCredentialsPrompt> class PushContentController; class App : public QObject { Q_OBJECT // The data model that contains all received pushes Q_PROPERTY(bb::cascades::GroupDataModel* model READ model CONSTANT) Q_PROPERTY(bool modelIsEmpty READ modelIsEmpty NOTIFY modelIsEmptyChanged) // The title and body text for the notification dialog Q_PROPERTY(QString notificationTitle READ notificationTitle NOTIFY notificationChanged) Q_PROPERTY(QString notificationBody READ notificationBody NOTIFY notificationChanged) // The title and body text for the activity dialog Q_PROPERTY(QString activityDialogTitle READ activityDialogTitle NOTIFY activityDialogChanged) Q_PROPERTY(QString activityDialogBody READ activityDialogBody NOTIFY activityDialogChanged) // The controller object for the push content page Q_PROPERTY(PushContentController* currentPushContent READ currentPushContent CONSTANT) public: App(); /** * Calls the push service create channel */ Q_INVOKABLE void createChannel(); /** * Calls the push service destroy channel */ Q_INVOKABLE void destroyChannel(); Q_INVOKABLE void deletePush(const QVariantMap &item); Q_INVOKABLE void deleteAllPushes(); Q_INVOKABLE void markAllPushesAsRead(); /** * Marks the passed push as current one and prepares the controller * object of the PushContentPage. */ Q_INVOKABLE void selectPush(const QVariantList &indexPath); Q_INVOKABLE QString convertToUtf8String(const QVariant &pushContent); public Q_SLOTS: void onInvoked(const bb::system::InvokeRequest &request); void registeredForPushNotifications(const QString & token); void errorRegisteringForPushNotifications(const QString & error); void onNoPushServiceConnection(); void onFullscreen(); void setTagsFinished(PWRequest * request); void getTagsFinished(PWRequest * request); Q_SIGNALS: void modelIsEmptyChanged(); void notificationChanged(); void activityDialogChanged(); void openActivityDialog(); void closeActivityDialog(); private: // A helper function to initialize the push session void initializePushSession(); bool validateUser(const QString &dialogTitle, const QString &username, const QString &password); void setPromptDefaultText(bb::system::SystemCredentialsPrompt* prompt,const QString &username, const QString &password); void pushNotificationHandler(bb::network::PushPayload &pushPayload); void showDialog(const QString &title, const QString &message); void openActivityDialog(const QString &title, const QString &message); // used to open and display a push when a notification is selected in the BlackBerry Hub void openPush(QByteArray pushContent); // a helper function which marks the push as read, and updates the displayed push content void updatePushContent(Push &push, const QVariantList &indexPath); // The accessor methods of the properties bb::cascades::GroupDataModel* model() const; bool modelIsEmpty() const; QString notificationTitle() const; QString notificationBody() const; QString activityDialogTitle() const; QString activityDialogBody() const; PushContentController* currentPushContent() const; // The manager object to react to invocations bb::system::InvokeManager *m_invokeManager; PushNotificationService m_pushNotificationService; PushHandler m_pushHandler; // Whether or not the application has at some point in time been running in the foreground bool m_hasBeenInForeground; // Whether or not the Configuration is in the process of being saved bool m_configSaveAction; // The controller object for the push content page PushContentController* m_pushContentController; // The property values bb::cascades::GroupDataModel *m_model; QString m_notificationTitle; QString m_notificationBody; QString m_activityDialogTitle; QString m_activityDialogBody; bool m_launchApplicationOnPush; }; #endif
33.751724
124
0.759297
robertrumney
696e00b7f954b87499a5b283968c390faf40164a
19,133
cpp
C++
examples/guidedFilter_kinect_rgb.cpp
skn123/GuidedFilter
d701b41c46205e96587801a0382d6ce43fe51e94
[ "MIT" ]
29
2017-06-08T03:59:03.000Z
2021-12-03T09:02:14.000Z
examples/guidedFilter_kinect_rgb.cpp
skn123/GuidedFilter
d701b41c46205e96587801a0382d6ce43fe51e94
[ "MIT" ]
2
2018-01-31T20:16:49.000Z
2019-09-17T15:36:35.000Z
examples/guidedFilter_kinect_rgb.cpp
skn123/GuidedFilter
d701b41c46205e96587801a0382d6ce43fe51e94
[ "MIT" ]
11
2017-07-02T12:40:14.000Z
2020-07-24T02:10:34.000Z
/*! \file guidedFilter_kinect_rgb.cpp * \brief An example showcasing the effect of the `Guided Filter` algorithm on color images. * \details This example demonstrates the performance of the [Guided Image Filtering] * (http://research.microsoft.com/en-us/um/people/kahe/eccv10/) * algorithm on a live video stream. It processes the Kinect RGB * stream in OpenCL with the `GuidedFilter` pipeline. * \author Nick Lamprianidis * \version 1.2.0 * \date 2015 * \copyright The MIT License (MIT) * \par * Copyright (c) 2015 Nick Lamprianidis * \par * 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: * \par * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \par * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <string> #include <chrono> #include <mutex> #include <GL/glew.h> // Add before CLUtils.hpp #include <CLUtils.hpp> #include <GuidedFilter/algorithms.hpp> #if defined(__APPLE__) || defined(__MACOSX) #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <libfreenect.hpp> // Window parameters const int gl_win_width = 1280; const int gl_win_height = 480; int glWinId; // GL texture IDs GLuint glRGBTex, glRGBTexFilt; // Freenect class MyFreenectDevice; Freenect::Freenect freenect; MyFreenectDevice *device; double freenectAngle = 0; // OpenCL const std::vector<std::string> kernel_files = { "kernels/imageSupport_kernels.cl", "kernels/scan_kernels.cl", "kernels/transpose_kernels.cl", "kernels/boxFilter_kernels.cl", "kernels/math_kernels.cl", "kernels/guidedFilter_kernels.cl", "kernels/examples_kernels.cl" }; const int imgWidth = 640; const int imgHeight = 480; const int dRadius = 5; const float dEps = 0.02f; class GFilterRGB; GFilterRGB *gFilter; /*! \brief Creates an OpenCL environment with CL-GL interoperability. */ class CLEnvGL : public clutils::CLEnv { public: /*! \brief Initializes the OpenCL environment. */ CLEnvGL () : CLEnv () { addContext (0, true); addQueueGL (0); addQueueGL (0); addProgram (0, kernel_files); } private: /*! \brief Initializes the OpenGL memory buffers. * \note Do not call directly. `initGLMemObjects` is called by `addContext` * when creating the GL-shared CL context. */ void initGLMemObjects () { glGenTextures (1, &glRGBTex); glBindTexture (GL_TEXTURE_2D, glRGBTex); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32F, imgWidth, imgHeight, 0, GL_RGBA, GL_FLOAT, nullptr); glGenTextures (1, &glRGBTexFilt); glBindTexture (GL_TEXTURE_2D, glRGBTexFilt); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32F, imgWidth, imgHeight, 0, GL_RGBA, GL_FLOAT, nullptr); glBindTexture (GL_TEXTURE_2D, 0); } }; /*! \brief Applies `Guided Image Filtering` on a `Kinect` RGB frame and * delivers the data to `OpenGL`. */ class GFilterRGB { public: GFilterRGB () : env (), context (env.getContext (0)), queue0 (env.getQueue (0, 0)), queue1 (env.getQueue (0, 1)), kernelGLIn (env.getProgram (0), "combineRGBGL"), kernelGLOut (env.getProgram (0), "combineRGBGL"), global (imgWidth * imgHeight), info (0, 0, 0, { 0, 1 }, 0), kGFRGB (env, info), bufferSize (imgWidth * imgHeight * sizeof (cl_float)), waitListGLIn (1), waitListGLObj (1), normalizeRGB (0) { size_t wgMultiple = kernelGLIn.getWorkGroupInfo <CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE> (env.devices[0][0]); // The local workspace should be a multiple of 3 size_t wgM = wgMultiple; unsigned int pixels = imgWidth * imgHeight; while (pixels % (3 * wgM) != 0) wgM >>= 1; local = cl::NDRange (3 * wgM); // Initialize the Guided Image Filtering pipeline kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF::Kinect::GuidedFilterRGBConfig::SEPARATED> ::Memory::D_OUT_R) = cl::Buffer (context, CL_MEM_READ_WRITE, bufferSize); kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF::Kinect::GuidedFilterRGBConfig::SEPARATED> ::Memory::D_OUT_G) = cl::Buffer (context, CL_MEM_READ_WRITE, bufferSize); kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF::Kinect::GuidedFilterRGBConfig::SEPARATED> ::Memory::D_OUT_B) = cl::Buffer (context, CL_MEM_READ_WRITE, bufferSize); kGFRGB.init (imgWidth, imgHeight, dRadius, dEps, cl_algo::GF::Staging::I); // Create GL-shared images imagesGL.emplace_back (context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, glRGBTex); imagesGL.emplace_back (context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, glRGBTexFilt); // Set arguments for the kernel instance responsible for handling the original frame kernelGLIn.setArg (0, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_INTR_R)); kernelGLIn.setArg (1, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_INTR_G)); kernelGLIn.setArg (2, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_INTR_B)); kernelGLIn.setArg (3, imagesGL[0]); kernelGLIn.setArg (4, cl::Local (3 * local[0] * sizeof (cl_float))); kernelGLIn.setArg (5, imgWidth); kernelGLIn.setArg (6, normalizeRGB); // Set arguments for the kernel instance responsible for handling the processed frame kernelGLOut.setArg (0, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_OUT_R)); kernelGLOut.setArg (1, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_OUT_G)); kernelGLOut.setArg (2, kGFRGB.get (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_OUT_B)); kernelGLOut.setArg (3, imagesGL[1]); kernelGLOut.setArg (4, cl::Local (3 * local[0] * sizeof (cl_float))); kernelGLOut.setArg (5, imgWidth); kernelGLOut.setArg (6, normalizeRGB); } /*! \brief Processes an RGB frame on the GPU. * \details The processed frame is delivered directly to OpenGL from the GPU. * * \param[in] rgb frame to be processed. */ void process (cl_uchar *rgb) { // Transfer data to device kGFRGB.write (cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF ::Kinect::GuidedFilterRGBConfig::SEPARATED>::Memory::D_IN, rgb); glFinish (); // Wait for OpenGL pending operations on buffers to finish // Take ownership of OpenGL textures queue1.enqueueAcquireGLObjects ((std::vector<cl::Memory> *) &imagesGL); // Dispatch kernels kGFRGB.run (nullptr, &gfEvent); waitListGLIn[0] = gfEvent; queue1.enqueueNDRangeKernel (kernelGLIn, cl::NullRange, global, local, &waitListGLIn, &glEventIn); queue0.enqueueNDRangeKernel (kernelGLOut, cl::NullRange, global, local); waitListGLObj[0] = glEventIn; // Give up ownership of OpenGL textures queue0.enqueueReleaseGLObjects ((std::vector<cl::Memory> *) &imagesGL, &waitListGLObj); queue0.finish (); } void radiusUp () { kGFRGB.setRadius (kGFRGB.getRadius () + 1); } void radiusDown () { if (kGFRGB.getRadius () == 1) return; kGFRGB.setRadius (kGFRGB.getRadius () - 1); } void resetRadius () { kGFRGB.setRadius (dRadius); } int getRadius () { return kGFRGB.getRadius (); } void epsUp () { kGFRGB.setEps (kGFRGB.getEps () + 0.005f); } void epsDown () { float tmp = kGFRGB.getEps () - 0.005f; if (tmp < 0.f) return; kGFRGB.setEps (tmp); } void resetEps () { kGFRGB.setEps (dEps); } float getEps () { return kGFRGB.getEps (); } void toggleRGBNorm () { normalizeRGB = !normalizeRGB; kernelGLIn.setArg (6, normalizeRGB); kernelGLOut.setArg (6, normalizeRGB); } private: CLEnvGL env; cl::Context &context; cl::CommandQueue &queue0, &queue1; cl::Kernel kernelGLIn, kernelGLOut; std::vector<cl::ImageGL> imagesGL; /*!< GL-shared images */ cl::NDRange global, local; cl::Event gfEvent, glEventIn; std::vector<cl::Event> waitListGLIn, waitListGLObj; clutils::CLEnvInfo<2> info; cl_algo::GF::Kinect::GuidedFilterRGB<cl_algo::GF::Kinect::GuidedFilterRGBConfig::SEPARATED> kGFRGB; unsigned int bufferSize; int normalizeRGB; }; /*! \brief A class that extends Freenect::FreenectDevice by defining * the VideoCallback function so we can be getting updates * with the latest RGB frame. */ class MyFreenectDevice : public Freenect::FreenectDevice { public: /*! \note The creation of the device is done through the Freenect class. * * \param[in] ctx context to open device through (handled by the library). * \param[in] idx index of the device on the bus. */ MyFreenectDevice (freenect_context *ctx, int idx) : Freenect::FreenectDevice (ctx, idx), newRGBFrame (false) { // setVideoFormat (FREENECT_VIDEO_YUV_RGB, FREENECT_RESOLUTION_MEDIUM); rgbBuffer = new cl_uchar[freenect_find_video_mode ( FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB).bytes]; } virtual ~MyFreenectDevice () { delete[] rgbBuffer; } /*! \brief Delivers the latest RGB frame. * \note Do not call directly, it's only used by the library. * * \param[in] rgb an array holding the rgb frame. * \param[in] timestamp a time stamp. */ void VideoCallback (void *rgb, uint32_t timestamp) { std::lock_guard<std::mutex> lock (rgbMutex); std::copy ((cl_uchar *) rgb, (cl_uchar *) rgb + getVideoBufferSize (), rgbBuffer); newRGBFrame = true; } /*! \brief Processes the most recently received RGB frame. * \note The frame is left on the GPU to be handled by OpenGL. * * \return A flag to indicate whether a new frame was present. */ bool updateFrame () { std::lock_guard<std::mutex> lock (rgbMutex); if (!newRGBFrame) return false; gFilter->process (rgbBuffer); newRGBFrame = false; return true; } private: std::mutex rgbMutex; cl_uchar *rgbBuffer; bool newRGBFrame; }; /*! \brief Display callback for the window. */ void drawGLScene () { static uint8_t frameCount = 0; if (device->updateFrame ()) frameCount++; glClear (GL_COLOR_BUFFER_BIT); glEnable (GL_TEXTURE_2D); glBindTexture (GL_TEXTURE_2D, glRGBTex); glBegin (GL_QUADS); glColor4f (1.f, 1.f, 1.f, 1.f); glVertex2i (0, 0); glTexCoord2f (1.f, 0.f); glVertex2i (imgWidth, 0); glTexCoord2f (1.f, 1.f); glVertex2i (imgWidth, imgHeight); glTexCoord2f (0.f, 1.f); glVertex2i (0, imgHeight); glTexCoord2f (0.f, 0.f); glEnd (); glBindTexture (GL_TEXTURE_2D, glRGBTexFilt); glBegin (GL_QUADS); glColor4f (1.f, 1.f, 1.f, 1.f); glVertex2i (imgWidth, 0); glTexCoord2f (1.f, 0.f); glVertex2i (imgWidth + imgWidth, 0); glTexCoord2f (1.f, 1.f); glVertex2i (imgWidth + imgWidth, imgHeight); glTexCoord2f (0.f, 1.f); glVertex2i (imgWidth, imgHeight); glTexCoord2f (0.f, 0.f); glEnd (); static float fps; std::ostringstream fpsBuffer; static std::string fpsStr; static std::chrono::time_point<std::chrono::system_clock> timeRef = std::chrono::system_clock::now (); // Calculate and display the frame rate if (frameCount == 10) { std::chrono::duration<float> elapsed = std::chrono::system_clock::now () - timeRef; fps = 10.f / elapsed.count (); fpsBuffer << std::fixed << std::setprecision (2) << std::setfill ('0') << std::setw (5) << fps << " fps"; fpsStr = fpsBuffer.str (); frameCount = 0; timeRef = std::chrono::system_clock::now (); } glRasterPos2f (1210.f, 25.f); for (auto c : fpsStr) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_12, c); // Display the filter parameters std::ostringstream paramStr; paramStr << "Radius: " << gFilter->getRadius (); glRasterPos2f (20.f, 445.f); for (auto c : paramStr.str ()) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_12, c); paramStr.str (std::string ()); paramStr.clear (); paramStr << "Eps: " << std::fixed << std::setprecision (3) << gFilter->getEps (); glRasterPos2f (20.f, 460.f); for (auto c : paramStr.str ()) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_12, c); glutSwapBuffers (); } /*! \brief Idle callback for the window. */ void idleGLScene () { glutPostRedisplay (); } /*! \brief Reshape callback for the window. */ void resizeGLScene (int width, int height) { glViewport (0, 0, width, height); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho (0.0, gl_win_width, gl_win_height, 0.0, -1.0, 1.0); glMatrixMode (GL_MODELVIEW); } /*! \brief Keyboard callback for the window. */ void keyPressed (unsigned char key, int x, int y) { switch (key) { case 0x1B: // ESC case 'Q': case 'q': glutDestroyWindow (glWinId); break; case 'I': case 'i': gFilter->radiusDown (); break; case 'O': case 'o': gFilter->resetRadius (); break; case 'P': case 'p': gFilter->radiusUp (); break; case 'J': case 'j': gFilter->epsDown (); break; case 'K': case 'k': gFilter->resetEps (); break; case 'L': case 'l': gFilter->epsUp (); break; case 'N': case 'n': gFilter->toggleRGBNorm (); break; case 'W': case 'w': if (++freenectAngle > 30) freenectAngle = 30; device->setTiltDegrees (freenectAngle); break; case 'S': case 's': if (--freenectAngle < -30) freenectAngle = -30; device->setTiltDegrees (freenectAngle); break; case 'R': case 'r': freenectAngle = 0; device->setTiltDegrees (freenectAngle); break; case '1': device->setLed (LED_GREEN); break; case '2': device->setLed (LED_RED); break; case '3': device->setLed (LED_YELLOW); break; case '4': case '5': device->setLed (LED_BLINK_GREEN); break; case '6': device->setLed (LED_BLINK_RED_YELLOW); break; case '0': device->setLed (LED_OFF); break; } } /*! \brief Initializes GLUT. */ void initGL (int argc, char **argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA); glutInitWindowSize (gl_win_width, gl_win_height); glutInitWindowPosition ((glutGet (GLUT_SCREEN_WIDTH) - gl_win_width) / 2, (glutGet (GLUT_SCREEN_HEIGHT) - gl_win_height) / 2 - 70); glWinId = glutCreateWindow ("Guided Image Filtering on an RGB stream"); glutDisplayFunc (&drawGLScene); glutIdleFunc (&idleGLScene); glutReshapeFunc (&resizeGLScene); glutKeyboardFunc (&keyPressed); glClearColor (0.f, 0.f, 0.f, 0.f); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel (GL_SMOOTH); } // Displays the available controls void printInfo () { std::cout << "\nAvailable Controls:\n"; std::cout << "===================\n"; std::cout << " Adjust Filter Radius [-/r/+] : I/O/P\n"; std::cout << " Adjust Filter Epsilon [-/r/+] : J/K/L\n"; std::cout << " Toggle RGB Normalization : N\n"; std::cout << " Kinect Tilt Angle [-/r/+] : S/R/W\n"; std::cout << " Update LED State : 0-6\n"; std::cout << " Quit : Q or Esc\n\n"; } int main (int argc, char **argv) { try { printInfo (); device = &freenect.createDevice<MyFreenectDevice> (0); device->startVideo (); initGL (argc, argv); // The OpenCL environment must be created after the OpenGL environment // has been initialized and before OpenGL starts rendering gFilter = new GFilterRGB (); glutMainLoop (); device->stopVideo (); delete gFilter; return 0; } catch (const std::runtime_error &error) { std::cerr << "Kinect: " << error.what () << std::endl; } catch (const cl::Error &error) { std::cerr << error.what () << " (" << clutils::getOpenCLErrorCodeString (error.err ()) << ")" << std::endl; } exit (EXIT_FAILURE); }
32.650171
111
0.606596
skn123
696fb7ad018d4e05ca177d3e382f8f0333793921
38,018
cpp
C++
mainwindow.cpp
mohawkjohn/bskQtViz
cf54077a82f9674273044a8305069056a3aaf0a0
[ "0BSD" ]
null
null
null
mainwindow.cpp
mohawkjohn/bskQtViz
cf54077a82f9674273044a8305069056a3aaf0a0
[ "0BSD" ]
null
null
null
mainwindow.cpp
mohawkjohn/bskQtViz
cf54077a82f9674273044a8305069056a3aaf0a0
[ "0BSD" ]
null
null
null
/* ISC License Copyright (c) 2016-2017, Autonomous Vehicle Systems Lab, University of Colorado at Boulder 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 "mainwindow.h" // DEF: header file generated by the wizard #include "ui_mainwindow.h" // DEF: UI header file generated by the uic tool #include "scenewidget.h" #include "ipaddressdialog.h" #include "adcssimdatamanager.h" #include <QMessageBox> #include <QPixmap> #include <QFile> #include <QFileInfo> #include <QSettings> #include <QDoubleSpinBox> #include <QInputDialog> #include <QFileDialog> #include <QVBoxLayout> #include <QSignalMapper> #include <qkeysequence.h> extern "C" { #include "astroFunctions.h" } MainWindow::MainWindow() : QMainWindow(0) , ui(new Ui::MainWindow) // NOTE: Change the next line to implement an individual simulation data manager , m_simDataManager(new AdcsSimDataManager(this)) , m_connectionStatus(new QLabel(this)) , m_modelsDisplayInfo (new ModelsDisplayInfo(this)) , m_orbitElementsInfo (new OrbitElementsInfo(this)) , m_reactionWheelsInfo (new ReactionWheelsInfo(this, m_simDataManager)) , m_simTimeInfo( new SimTimeInfo(this)) , m_cssInfo(new CssInfo(this)) , m_angularRatesInfo(new AngularRatesInfo(this)) , m_controlStateInfo(new ControlStateInfo(this)) , m_torqueRodInfo(new TorqueRodInfo(this)) , m_thrustersInfo(new ThrustersInfo(this, m_simDataManager)) , m_totalPowerInfo(new TotalPowerInfo(this)) , m_podInfo(new PodInfo(this)) , m_iruInfo(new IruInfo(this)) , m_tamInfo(new TamInfo(this)) , m_starTrackerInfo(new StarTrackerInfo(this)) , m_cameraTargetCombo(new QComboBox(this)) , m_cameraModeCombo(new QComboBox(this)) , m_zoomSpeedLabel(new QLabel(this)) , m_zoomSpeed(new QDoubleSpinBox(this)) , m_panSpeedLabel(new QLabel(this)) , m_panSpeed(new QDoubleSpinBox(this)) , m_fpvTranslateLabel(new QLabel(this)) , m_fpvTranslate(new QDoubleSpinBox(this)) , m_fpvRotateLabel(new QLabel(this)) , m_fpvRotate(new QDoubleSpinBox(this)) , m_styleActionGroup(new QActionGroup(this)) , m_initialCameraMode(-1) { ui->setupUi(this); ui->actionOpen_Connection->setIcon(style()->standardIcon(QStyle::SP_DriveNetIcon)); ui->actionOpen_File->setIcon(style()->standardIcon(QStyle::SP_FileIcon)); ui->menuBar->setEnabled(true); ui->menuBar->setFocusPolicy(Qt::StrongFocus); ui->menuBar->setNativeMenuBar(false); // Add action for perturbing rates QAction *action = new QAction(tr("Perturb Rates"), this); action->setShortcut(QKeySequence(Qt::Key_P)); this->addAction(action); // connect(action, SIGNAL(triggered()), m_simDataManager, SLOT(perturbRates())); // connect(m_angularRatesInfo, SIGNAL(perturbRates()), m_simDataManager, SLOT(perturbRates())); // Hook up actions for changing control status // connect(m_controlStateInfo, SIGNAL(setControlState(CommandedState_t)), m_simDataManager, SLOT(setControlState(CommandedState_t))); // connect(m_controlStateInfo, SIGNAL(setAdcsState(ADCSState_t)), m_simDataManager, SLOT(setAdcsState(ADCSState_t))); // connect(m_controlStateInfo, SIGNAL(setThrustingControlMode(int)), m_simDataManager, SLOT(setThrustingControlMode(int))); // connect(m_reactionWheelsInfo, SIGNAL(setOnOffState(ComponentState_t, int)), m_simDataManager, SLOT(setOnOffState(ComponentState_t, int))); // connect(m_cssInfo, SIGNAL(setStateCSS(ComponentState_t, int)), m_simDataManager, SLOT(setStateCSS(ComponentState_t, int))); // connect(m_torqueRodInfo, SIGNAL(setStateTR(ComponentState_t,int)), m_simDataManager, SLOT(setStateTR(ComponentState_t, int))); // connect(m_podInfo, SIGNAL(setStatePOD(ComponentState_t)), m_simDataManager, SLOT(setStatePOD(ComponentState_t))); // connect(m_iruInfo, SIGNAL(setStateIRU(ComponentState_t)), m_simDataManager, SLOT(setStateIRU(ComponentState_t))); // connect(m_tamInfo, SIGNAL(setStateTAM(ComponentState_t)), m_simDataManager, SLOT(setStateTAM(ComponentState_t))); connect(m_simDataManager, SIGNAL(setOnOffLegendRW(bool)), m_reactionWheelsInfo, SLOT(setOnOffLegendRW(bool))); connect(m_simDataManager, SIGNAL(setOnOffLegendRW(bool)), this, SLOT(openLegendRW(bool))); connect(m_simDataManager, SIGNAL(simConnected()), m_reactionWheelsInfo, SLOT(configureLayout())); connect(m_simDataManager, SIGNAL(simConnected()), m_thrustersInfo, SLOT(configureLayout())); // connect(m_simDataManager, SIGNAL(setOnOffLegendTR(bool)), m_torqueRodInfo, SLOT(setOnOffLegendTR(bool))); // connect(m_simDataManager, SIGNAL(setOnOffLegendTR(bool)), this, SLOT(openLegendTR(bool))); // connect(m_simDataManager, SIGNAL(setOnOffDefaults(CelestialObject_t)), this, SLOT(setOnOffDefaults(CelestialObject_t))); // connect(m_modelsDisplayInfo, SIGNAL(setGravityGradientTorque(int)), m_simDataManager, SLOT(setGravityGradientTorque(int))); // connect(m_modelsDisplayInfo, SIGNAL(setReactionWheelJitter(int)), m_simDataManager, SLOT(setReactionWheelJitter(int))); // connect(m_modelsDisplayInfo, SIGNAL(setGravityPerturbModel(int)), m_simDataManager, SLOT(setGravityPerturbModel(int))); // connect(m_modelsDisplayInfo, SIGNAL(setAtmosDragModel(int)), m_simDataManager, SLOT(setAtmosDragModel(int))); // connect(m_modelsDisplayInfo, SIGNAL(setSrpModel(int)), m_simDataManager, SLOT(setSrpModel(int))); // connect(m_modelsDisplayInfo, SIGNAL (setAlbedoModel(AlbedoModel_t)), m_simDataManager, SLOT (setAlbedoModel(AlbedoModel_t))); // connect(m_modelsDisplayInfo, SIGNAL(setEarthMagField(EarthMagFieldModel_t)), m_simDataManager, SLOT (setEarthMagField(EarthMagFieldModel_t))); // connect(m_thrustersInfo, SIGNAL(setNewManeuver(double,double)), m_simDataManager, SLOT (setNewManeuver(double,double))); // Add in default widgets // Scene widget must be created before shortcuts widget createSceneWidget(); // main scene in MainWindow createPlaybackWidget(); createShortcutsWidget(); createToggleablesWidget(); ui->actionPlayback_Controls->setChecked(true); ui->actionPlayback_Controls->setVisible(true); // Add in custom dock widgets: //addDockWidget(Qt::RightDockWidgetArea, m_modelsDisplayInfo); //connect(ui->actionSimInfo, SIGNAL(toggled(bool)), m_modelsDisplayInfo, SLOT(setVisible(bool))); ui->actionSimInfo->setChecked(false); ui->actionSimInfo->setVisible(false); m_modelsDisplayInfo->hide(); addDockWidget(Qt::RightDockWidgetArea, m_orbitElementsInfo); connect(ui->actionOE, SIGNAL(toggled(bool)),m_orbitElementsInfo, SLOT(setVisible(bool))); ui->actionOE->setChecked(true); //addDockWidget(Qt::LeftDockWidgetArea,m_controlStateInfo); //connect(ui->actionCtrl, SIGNAL(toggled(bool)), m_controlStateInfo, SLOT(setVisible(bool))); ui->actionCtrl->setChecked(false); ui->actionCtrl->setVisible(false); m_controlStateInfo->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_reactionWheelsInfo); connect(ui->actionRW, SIGNAL(toggled(bool)),m_reactionWheelsInfo, SLOT(setVisible(bool))); ui->actionRW->setChecked(true); //addDockWidget(Qt::LeftDockWidgetArea, m_cssInfo); //connect(ui->actionCSS, SIGNAL(toggled(bool)), m_cssInfo, SLOT(setVisible(bool))); ui->actionCSS->setChecked(false); ui->actionCSS->setVisible(false); m_cssInfo->hide(); //addDockWidget(Qt::LeftDockWidgetArea, m_angularRatesInfo); //connect(ui->actionRates, SIGNAL(toggled(bool)), m_angularRatesInfo, SLOT(setVisible(bool))); ui->actionRates->setChecked(false); ui->actionRates->setVisible(false); m_angularRatesInfo->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_simTimeInfo); connect(ui->actionSimTime, SIGNAL(toggled(bool)),m_simTimeInfo, SLOT(setVisible(bool))); ui->actionSimTime->setChecked(true); m_simTimeInfo->hide(); addDockWidget(Qt::RightDockWidgetArea, m_thrustersInfo); connect(ui->actionThrusters, SIGNAL(toggled(bool)), m_thrustersInfo, SLOT(setVisible(bool))); ui->actionThrusters->setChecked(true); m_thrustersInfo->hide(); //addDockWidget(Qt::LeftDockWidgetArea, m_torqueRodInfo); //connect(ui->actionTR, SIGNAL(toggled(bool)), m_torqueRodInfo, SLOT(setVisible(bool))); ui->actionTR->setChecked(false); ui->actionTR->setVisible(false); m_torqueRodInfo->hide(); //addDockWidget(Qt::RightDockWidgetArea, m_starTrackerInfo); //connect(ui->actionST, SIGNAL(toggled(bool)), m_starTrackerInfo, SLOT(setVisible(bool))); ui->actionST->setChecked(false); ui->actionST->setVisible(false); m_starTrackerInfo->hide(); //addDockWidget(Qt::LeftDockWidgetArea, m_totalPowerInfo); //connect(ui->actionTotalPower, SIGNAL(toggled(bool)), m_totalPowerInfo, SLOT(setVisible(bool))); ui->actionTotalPower->setChecked(false); ui->actionTotalPower->setVisible(false); m_totalPowerInfo->hide(); //addDockWidget(Qt::LeftDockWidgetArea, m_podInfo); //connect(ui->actionPOD, SIGNAL(toggled(bool)), m_podInfo, SLOT(setVisible(bool))); ui->actionPOD->setChecked(false); ui->actionPOD->setVisible(false); m_podInfo->hide(); //addDockWidget(Qt::RightDockWidgetArea, m_iruInfo); //connect(ui->actionIRU, SIGNAL(toggled(bool)), m_iruInfo, SLOT(setVisible(bool))); ui->actionIRU->setChecked(false); ui->actionIRU->setVisible(false); m_iruInfo->hide(); //addDockWidget(Qt::RightDockWidgetArea, m_tamInfo); //connect(ui->actionTAM, SIGNAL(toggled(bool)), m_tamInfo, SLOT(setVisible(bool))); ui->actionTAM->setChecked(false); ui->actionTAM->setVisible(false); m_tamInfo->hide(); // Add style options m_styleActionGroup->setExclusive(true); m_styleActionGroup->addAction(ui->actionDefaultStyle); m_styleActionGroup->addAction(ui->actionDarkStyle); connect(m_styleActionGroup, SIGNAL(triggered(QAction *)), this, SLOT(setWindowStyle(QAction *))); ui->actionDarkStyle->setChecked(true); setWindowStyle(ui->actionDarkStyle); // Add source information to the status bar ui->statusBar->addPermanentWidget(m_connectionStatus); m_connectionStatus->setText("Source: None"); connect(m_simDataManager, SIGNAL(showMessage(QString)), ui->statusBar, SLOT(showMessage(QString))); connect(m_simDataManager, SIGNAL(showMessage(QString, int)), ui->statusBar, SLOT(showMessage(QString, int))); loadSettings(); simDataUpdated(); } MainWindow::~MainWindow() { delete ui; } QSize MainWindow::minimumSizeHint() const { return QSize(50, 50); } QSize MainWindow::sizeHint() const { return QSize(800, 600); } /*! * Purpose: Set the data path to where the application is to look for supporting libraries. * * @param[in] QString *dataPath path to supporting libraries */ void MainWindow::setDataPath(QString &dataPath) { m_dataPath = &dataPath; } /*! * Purpose: Set the data path to where the application is to look for supporting libraries. * * @param[out] QString *dataPath path to supporting libraries */ QString MainWindow::dataPath() // get dataPath { return *m_dataPath; } int MainWindow::loadSpiceFiles() { if (m_dataPath) { loadSpiceKernels(m_dataPath->toStdString().c_str()); return 0; } return 1; } int MainWindow::loadStarCatalog() { if (m_dataPath) { m_starTrackerInfo->parseStarsData(m_dataPath->toStdString().c_str()); return 0; } return 1; } void MainWindow::openLegendRW(bool open) { if (m_reactionWheelsInfo->isHidden() && open == true) { m_reactionWheelsInfo->setVisible(true); ui->actionRW->setChecked(true); } } void MainWindow::openLegendTR(bool open) { if (m_torqueRodInfo->isHidden() && open == true) { m_torqueRodInfo->setVisible(true); ui->actionTR->setChecked(true); } } void MainWindow::setOnOffDefaults(CelestialObject_t mainBody) { switch (mainBody) { case CELESTIAL_EARTH: // Update Toggleable's checkbox for (int i=0; i<toggleablesCheckBoxList.size(); i++) { if (toggleablesCheckBoxList[i]->text() == "Spacecraft Magnetic Field Vector" || toggleablesCheckBoxList[i]->text() == "Torque Rod Pyramid") { toggleablesCheckBoxList[i]->show(); } } // Update Panels Available ui->actionTAM->setVisible(true); ui->actionTAM->setCheckable(true); ui->actionTR->setVisible(true); ui->actionTR->setVisible(true); ui->actionPOD->setVisible(true); ui->actionPOD->setVisible(true); break; case CELESTIAL_MARS: // Update Toggleable's checkbox for (int i=0; i<toggleablesCheckBoxList.size(); i++) { if (toggleablesCheckBoxList[i]->text() == "Spacecraft Magnetic Field Vector" || toggleablesCheckBoxList[i]->text() == "Torque Rod Pyramid") { toggleablesCheckBoxList[i]->hide(); } } // Update Panels Available ui->actionTAM->setVisible(false); m_tamInfo->setVisible(false); ui->actionTAM->setCheckable(false); ui->actionTR->setVisible(false); m_torqueRodInfo->setVisible(false); ui->actionTR->setVisible(false); ui->actionPOD->setVisible(false); m_podInfo->setVisible(false); ui->actionPOD->setVisible(false); break; case CELESTIAL_SUN: // Update Toggleable's checkbox for (int i=0; i<toggleablesCheckBoxList.size(); i++) { if (toggleablesCheckBoxList[i]->text() == "Spacecraft Magnetic Field Vector" || toggleablesCheckBoxList[i]->text() == "Torque Rod Pyramid") { toggleablesCheckBoxList[i]->hide(); } } // Update Panels Available ui->actionTAM->setVisible(false); m_tamInfo->setVisible(false); ui->actionTAM->setCheckable(false); ui->actionTR->setVisible(false); m_torqueRodInfo->setVisible(false); ui->actionTR->setVisible(false); ui->actionPOD->setVisible(false); m_podInfo->setVisible(false); ui->actionPOD->setVisible(false); break; default: break; } } void MainWindow::simDataUpdated() { // Update camera targets (of m_simDataManager and m_sceneWidget according to the box selected) // Removing and readding causes issues with selecting camera target // so just remove excess and rename things as necessary int selectedTargetIndex = m_cameraTargetCombo->currentIndex(); QString selectedTargetName = m_cameraTargetCombo->currentText(); QVector<SimObject> simObjects = m_simDataManager->getSimObjects(); for(int i = m_cameraTargetCombo->count(); i >= simObjects.size(); i--) { m_cameraTargetCombo->removeItem(i); // remove excess items fins que nomes quedi el nombre d'obj del SimObject } for(int i = 0; i < simObjects.size(); i++) { if(m_cameraTargetCombo->count() > i) { m_cameraTargetCombo->setItemText(i, simObjects.at(i).name); } else { m_cameraTargetCombo->addItem(simObjects.at(i).name); } if(simObjects.at(i).name.compare(selectedTargetName) == 0) { selectedTargetIndex = i; m_initialCameraMode = i; } } if(selectedTargetIndex == -1) { selectedTargetIndex = m_simDataManager->getPreferredCameraTarget(); } // -1 is the value of currentIndex: int when no current item is set in the combo box m_cameraTargetCombo->setCurrentIndex(selectedTargetIndex); m_simDataManager->setTargetObject(selectedTargetIndex); m_sceneWidget->setTargetObject(selectedTargetIndex); // Update Displays //m_modelsDisplayInfo->getModelInfo(m_simDataManager); m_orbitElementsInfo->updateOrbitElements(m_simDataManager); m_reactionWheelsInfo->updateReactionWheels(m_simDataManager); m_simTimeInfo->updateSimTime(m_simDataManager); m_cssInfo->updateCSS(m_simDataManager); m_angularRatesInfo->updateAngularRates(m_simDataManager); // m_controlStateInfo->updateControl(m_simDataManager); // m_torqueRodInfo->updateTorqueRods(m_simDataManager); m_thrustersInfo->updateThrusters(m_simDataManager); // m_totalPowerInfo->updatePower(m_simDataManager); // m_podInfo->updatePOD(m_simDataManager); // m_iruInfo->updateIRU(m_simDataManager); // m_tamInfo->updateTAM(m_simDataManager); // m_starTrackerInfo->updateST(m_simDataManager); // Update the playbackControls SpacecraftSim *scSim = m_simDataManager->getSpacecraftSim(); // m_playbackControls->setDateTimeBounds(scSim->ics.JD0); m_playbackControls->setCurrentDateTime(scSim->spiceTime.J2000Current); m_playbackControls->setPlaySpeed(scSim->realTimeSpeedUpFactor); } void MainWindow::setWindowStyle(QAction *action) { QString name = action->objectName(); if(name == "actionDefaultStyle") { qApp->setStyleSheet(""); } else if(name == "actionDarkStyle") { QFile file(":/qdarkstyle/style.qss"); if(file.exists()) { file.open(QFile::ReadOnly | QFile::Text); QTextStream ts(&file); qApp->setStyleSheet(ts.readAll()); } else { qApp->setStyleSheet(""); } } } void MainWindow::cycleCameraMode() { m_cameraModeCombo->setCurrentIndex((m_cameraModeCombo->currentIndex() + 1) % m_cameraModeCombo->count()); } void MainWindow::openConnection() { IpAddressDialog *dialog = new IpAddressDialog(this); if(dialog->exec()) { QString ipAddress = dialog->getIpAddress(); QString port = dialog->getPort(); ui->statusBar->showMessage("Opening " + ipAddress + "::" + port + " and initializing geometries..."); if(m_simDataManager->openConnection(ipAddress, port)) { m_connectionStatus->setText("Source: " + ipAddress + "::" + port); ui->actionClose_Connection->setEnabled(true); } ui->statusBar->clearMessage(); } } void MainWindow::closeConnection() { if(m_simDataManager->closeConnection()) { ui->actionClose_Connection->setEnabled(false); m_connectionStatus->setText("Source: None"); } } void MainWindow::openFile() { QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation Data File"), QDir::currentPath()); if(!filename.isEmpty()) { ui->statusBar->showMessage("Opening " + filename + " and initializing geometries..."); if(m_simDataManager->openFile(filename)) { ui->actionClose_File->setEnabled(true); m_connectionStatus->setText("Source: " + filename); } ui->statusBar->clearMessage(); } } void MainWindow::closeFile() { if(m_simDataManager->closeFile()) { ui->actionClose_File->setEnabled(false); m_connectionStatus->setText("Source: None"); } } void MainWindow::toggleFullScreen() { if(isFullScreen()) { showNormal(); ui->statusBar->showMessage("Fullscreen disabled", 5000); } else { showFullScreen(); ui->statusBar->showMessage("Fullscreen enabled, press " + ui->actionFull_Screen->shortcut().toString() + " to exit"); } } void MainWindow::closeEvent(QCloseEvent *event) { saveSettings(); QMainWindow::closeEvent(event); } void MainWindow::createShortcutsWidget() { // Add in actions QList<QAction *> actions = this->findChildren<QAction *>(); ui->shortcutsTable->setColumnCount(2); ui->shortcutsTable->setRowCount(actions.length()); QStringList headers; headers.push_back("Shortcuts"); headers.push_back("Description"); ui->shortcutsTable->setHorizontalHeaderLabels(headers); ui->shortcutsTable->verticalHeader()->hide(); int row = 0; for(int i = 0; i < actions.size(); i++) { QAction *action = actions.at(i); QString shortcut = action->shortcut().toString(); if(!shortcut.isEmpty()) { ui->shortcutsTable->setItem(row, 1, new QTableWidgetItem(action->iconText())); ui->shortcutsTable->setItem(row, 0, new QTableWidgetItem(shortcut)); row++; } } // Add in scene shortcuts QVector<shortcutPair> sceneShortcuts = m_sceneWidget->getShortcuts(); for(int i = 0; i < sceneShortcuts.size(); i++) { ui->shortcutsTable->setItem(row, 1, new QTableWidgetItem(sceneShortcuts.at(i).first)); ui->shortcutsTable->setItem(row, 0, new QTableWidgetItem(sceneShortcuts.at(i).second.toString())); row++; } ui->shortcutsTable->setRowCount(row); int tot=ui->shortcutsTable->rowCount(); if(m_initialCameraMode!=2){ for (int i=tot; i>=(tot-sceneShortcuts.size());i--){ ui->shortcutsTable->hideRow(i); } } else { for (int i=(tot-sceneShortcuts.size()); i<=tot; i++){ ui->shortcutsTable->showRow(i); } } } void MainWindow::createSceneWidget() { m_sceneWidget = new SceneWidget(ui->centralWidget, m_simDataManager); m_sceneWidget->setObjectName(QStringLiteral("sceneWidget")); m_sceneWidget->setMinimumSize(QSize(50, 50)); ui->centralWidgetLayout->addWidget(m_sceneWidget); // adding m_sceneWidget at centralWidgetLayout ui->centralWidgetLayout->setStretch(0, 1); connect(ui->actionReset_Camera, SIGNAL(triggered()), m_sceneWidget, SLOT(resetAll())); connect(ui->actionWireframe, SIGNAL(toggled(bool)), m_sceneWidget, SLOT(setWireframe(bool))); connect(ui->actionCamera_Target, SIGNAL(toggled(bool)), m_sceneWidget, SLOT(setCameraTargetVisible(bool))); // Setup the simulation data manager connect(m_simDataManager, SIGNAL(simDataUpdated()), m_sceneWidget, SLOT(update())); connect(m_simDataManager, SIGNAL(simDataUpdated()), this, SLOT(simDataUpdated())); // Camera target combobox QLabel *label = new QLabel("Camera Target:"); label->setMargin(5); ui->viewToolbar->addWidget(label); ui->viewToolbar->addWidget(m_cameraTargetCombo); connect(m_cameraTargetCombo, SIGNAL(currentIndexChanged(int)), m_sceneWidget, SLOT(setTargetObject(int))); ui->viewToolbar->addSeparator(); // Camera mode combobox label = new QLabel("Camera Mode:"); label->setMargin(5); ui->viewToolbar->addWidget(label); ui->viewToolbar->addWidget(m_cameraModeCombo); connect(m_cameraModeCombo, SIGNAL(currentIndexChanged(int)), m_sceneWidget, SLOT(setCameraMode(int))); connect(m_cameraModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateViewToolbarStates())); connect(m_cameraModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateShortcutsStates())); m_cameraModeCombo->addItem("Arcball"); m_cameraModeCombo->addItem("Pan"); m_cameraModeCombo->addItem("FPV"); // Zoom speed spin box m_zoomSpeedLabel->setText("Zoom Speed:"); m_zoomSpeedLabel->setMargin(5); m_zoomActions.push_back(ui->viewToolbar->addWidget(m_zoomSpeedLabel)); m_zoomActions.push_back(ui->viewToolbar->addWidget(m_zoomSpeed)); m_zoomSpeed->setDecimals(2); m_zoomSpeed->setMinimum(0.01); m_zoomSpeed->setValue(0.1); m_zoomSpeed->setMinimumWidth(70); connect(m_zoomSpeed, SIGNAL(valueChanged(double)), m_sceneWidget, SLOT(setZoomSpeed(double))); // Pan speed spin box m_panSpeedLabel->setText("Translate Speed:"); m_panSpeedLabel->setMargin(5); m_panActions.push_back(ui->viewToolbar->addWidget(m_panSpeedLabel)); m_panActions.push_back(ui->viewToolbar->addWidget(m_panSpeed)); m_panSpeed->setDecimals(2); m_panSpeed->setMinimum(0.01); m_panSpeed->setValue(0.1); m_panSpeed->setMinimumWidth(70); connect(m_panSpeed, SIGNAL(valueChanged(double)), m_sceneWidget, SLOT(setPanSpeed(double))); // FPV translate spin box m_fpvTranslateLabel->setText("Translate Speed:"); m_fpvTranslateLabel->setMargin(5); m_fpvActions.push_back(ui->viewToolbar->addWidget(m_fpvTranslateLabel)); m_fpvActions.push_back(ui->viewToolbar->addWidget(m_fpvTranslate)); m_fpvTranslate->setDecimals(2); m_fpvTranslate->setMinimum(0.01); m_fpvTranslate->setValue(0.1); m_fpvTranslate->setMinimumWidth(70); connect(m_fpvTranslate, SIGNAL(valueChanged(double)), m_sceneWidget, SLOT(setFpvTranslateSpeed(double))); // FPV rotate spin box m_fpvRotateLabel->setText("Rotate Speed:"); m_fpvRotateLabel->setMargin(5); m_fpvActions.push_back(ui->viewToolbar->addWidget(m_fpvRotateLabel)); m_fpvActions.push_back(ui->viewToolbar->addWidget(m_fpvRotate)); m_fpvRotate->setDecimals(2); m_fpvRotate->setMinimum(0.01); m_fpvRotate->setValue(1.0); m_fpvRotate->setMinimumWidth(70); connect(m_fpvRotate, SIGNAL(valueChanged(double)), m_sceneWidget, SLOT(setFpvRotateSpeed(double))); m_initialCameraMode =m_cameraModeCombo->currentIndex(); updateViewToolbarStates(); updateShortcutsStates(); } void MainWindow::createPlaybackWidget() { m_playbackControls = new PlaybackControls(ui->centralWidget); m_playbackControls->setObjectName(QStringLiteral("playbackControls")); ui->centralWidgetLayout->addWidget(m_playbackControls); connect(m_playbackControls, SIGNAL(dateTimeRequested(double)), m_simDataManager, SLOT(setSimTime(double))); connect(m_playbackControls, SIGNAL(playSpeedRequested(double)), m_simDataManager, SLOT(setPlaySpeed(double))); connect(m_playbackControls, SIGNAL (estPlaySpeedUpdated(double)), m_simTimeInfo, SLOT(setEstPlaySpeed(double))); connect(ui->actionPlayback_Controls, SIGNAL(triggered(bool)), this, SLOT(setPlaybackControlsVisible(bool))); } void MainWindow::createToggleablesWidget() { toggleableObjectMap toggleableObjects = m_simDataManager->getToggleableObjects(); QSignalMapper *signalMapper = new QSignalMapper(ui->toggleablesWidget); for(toggleableObjectMap::iterator i = toggleableObjects.begin(); i != toggleableObjects.end(); ++i) { QCheckBox *checkBox = new QCheckBox; checkBox->setObjectName(i.key()); checkBox->setText(i.key()); checkBox->setChecked(i.value()); connect(checkBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); signalMapper->setMapping(checkBox, checkBox); ui->toggleablesLayout->addWidget(checkBox); toggleablesCheckBoxList.append(checkBox); } ui->toggleablesLayout->addStretch(); connect(signalMapper, SIGNAL(mapped(QWidget *)), this, SLOT(updateToggleables(QWidget *))); } void MainWindow::saveSettings() { QSettings settings(QSettings::IniFormat, QSettings::UserScope, "AVSLab", "ADCSSimulationTool"); settings.beginGroup("mainwindow"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); settings.setValue("isMaximized", isMaximized()); if(!isMaximized()) { settings.setValue("pos", pos()); settings.setValue("size", size()); } settings.setValue("windowStyle", m_styleActionGroup->checkedAction()->objectName()); settings.endGroup(); settings.beginGroup("viewtoolbar"); settings.setValue("cameraMode", m_cameraModeCombo->currentIndex()); settings.setValue("zoomSpeed", m_zoomSpeed->value()); settings.setValue("fpvTranslate", m_fpvTranslate->value()); settings.setValue("fpvRotate", m_fpvRotate->value()); settings.endGroup(); settings.beginGroup("camera"); settings.setValue("wireframe", ui->actionWireframe->isChecked()); settings.setValue("cameraTarget", ui->actionCamera_Target->isChecked()); settings.endGroup(); m_modelsDisplayInfo->saveSettings(&settings); m_orbitElementsInfo->saveSettings(&settings); m_reactionWheelsInfo->saveSettings(&settings); m_cssInfo->saveSettings(&settings); m_torqueRodInfo->saveSettings(&settings); m_thrustersInfo->saveSettings(&settings); m_totalPowerInfo->saveSettings(&settings); m_angularRatesInfo->saveSettings(&settings); m_simTimeInfo->saveSettings(&settings); m_playbackControls->saveSettings(&settings); m_podInfo->saveSettings(&settings); m_iruInfo->saveSettings(&settings); m_tamInfo->saveSettings(&settings); m_starTrackerInfo->saveSettings(&settings); settings.beginGroup("view"); settings.setValue("togWidget", ui->actionScene_Options->isChecked()); settings.setValue("shortcutsWidget", ui->actionShortcuts->isChecked()); settings.setValue("statusWidget", ui->actionStatus_Bar->isChecked()); settings.setValue("toolbarWidget",ui->actionViewToolbar->isChecked()); settings.setValue("playbackWidget",ui->actionPlayback_Controls->isChecked()); settings.endGroup(); settings.beginGroup("infoPanels"); settings.setValue("simInfoDisplay",ui->actionSimInfo->isChecked()); settings.setValue("simTime",ui->actionSimTime->isChecked()); settings.setValue("thrusters",ui->actionThrusters->isChecked()); settings.setValue("TR",ui->actionTR->isChecked()); settings.setValue("CSS",ui->actionCSS->isChecked()); settings.setValue("RW",ui->actionRW->isChecked()); settings.setValue("OE",ui->actionOE->isChecked()); settings.setValue("ctrl",ui->actionCtrl->isChecked()); settings.setValue("rates",ui->actionRates->isChecked()); settings.setValue("power", ui->actionTotalPower->isChecked()); settings.setValue("POD", ui->actionPOD->isChecked()); settings.setValue("IRU", ui->actionIRU->isChecked()); settings.setValue("TAM", ui->actionTAM->isChecked()); settings.setValue("ST", ui->actionST->isChecked()); settings.endGroup(); settings.beginGroup("Toggleable Objects"); toggleableObjectMap toggleableObjects = m_simDataManager->getToggleableObjects(); for(toggleableObjectMap::iterator iter = toggleableObjects.begin(); iter != toggleableObjects.end(); ++iter) { settings.setValue(iter.key(), iter.value()); } settings.endGroup(); settings.setValue("playbackControlsVisible", ui->actionPlayback_Controls->isChecked()); } void MainWindow::loadSettings() { QSettings settings(QSettings::IniFormat, QSettings::UserScope, "AVSLab", "ADCSSimulationTool"); settings.beginGroup("mainwindow"); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); move(settings.value("pos", pos()).toPoint()); resize(settings.value("size", size()).toSize()); if(settings.value("maximized", isMaximized()).toBool()) { showMaximized(); } QString currentStyle = settings.value("windowStyle").toString(); if(!currentStyle.isEmpty()) { QAction *action = this->findChild<QAction *>(currentStyle); if(action) { action->setChecked(true); setWindowStyle(action); } } settings.endGroup(); settings.beginGroup("viewtoolbar"); m_cameraModeCombo->setCurrentIndex(settings.value("cameraMode").toInt()); m_zoomSpeed->setValue(settings.value("zoomSpeed").toDouble()); m_fpvTranslate->setValue(settings.value("fpvTranslate").toDouble()); m_fpvRotate->setValue(settings.value("fpvRotate").toDouble()); settings.endGroup(); settings.beginGroup("camera"); ui->actionWireframe->setChecked(settings.value("wireframe").toBool()); ui->actionCamera_Target->setChecked(settings.value("cameraTarget").toBool()); settings.endGroup(); settings.beginGroup("infoPanels"); ui->actionSimInfo->setChecked(settings.value("simInfoDisplay").toBool()); ui->actionSimTime->setChecked(settings.value("simTime").toBool()); ui->actionThrusters->setChecked(settings.value("thrusters").toBool()); ui->actionTR->setChecked(settings.value("TR").toBool()); ui->actionCSS->setChecked(settings.value("CSS").toBool()); ui->actionCSS->setChecked(settings.value("CSS").toBool()); ui->actionRW->setChecked(settings.value("RW").toBool()); ui->actionOE->setChecked(settings.value("OE").toBool()); ui->actionCtrl->setChecked(settings.value("ctrl").toBool()); ui->actionRates->setChecked(settings.value("rates").toBool()); ui->actionTotalPower->setChecked(settings.value("power").toBool()); ui->actionPOD->setChecked(settings.value("POD").toBool()); ui->actionIRU->setChecked(settings.value("IRU").toBool()); ui->actionTAM->setChecked(settings.value("TAM").toBool()); ui->actionST->setChecked(settings.value("ST").toBool()); settings.endGroup(); settings.beginGroup("view"); ui->actionScene_Options->setChecked(settings.value("togWidget").toBool()); ui->actionShortcuts->setChecked(settings.value("shortcutsWidget").toBool()); ui->actionStatus_Bar->setChecked(settings.value("statusWidget").toBool()); ui->actionViewToolbar->setChecked(settings.value("toolbarWidget").toBool()); ui->actionPlayback_Controls->setChecked(settings.value("playbackWidget").toBool()); settings.endGroup(); m_modelsDisplayInfo->loadSettings(&settings); m_orbitElementsInfo->loadSettings(&settings); m_reactionWheelsInfo->loadSettings(&settings); m_cssInfo->loadSettings(&settings); m_torqueRodInfo->loadSettings(&settings); m_thrustersInfo->loadSettings(&settings); m_totalPowerInfo->loadSettings(&settings); m_angularRatesInfo->loadSettings(&settings); m_simTimeInfo->loadSettings(&settings); m_playbackControls->loadSettings(&settings); m_podInfo->loadSettings(&settings); m_iruInfo->loadSettings(&settings); m_tamInfo->loadSettings(&settings); m_starTrackerInfo->loadSettings(&settings); settings.beginGroup("Toggleable Objects"); QStringList childKeys = settings.childKeys(); for(int i = 0; i < childKeys.count(); i++) { m_simDataManager->setToggleableObjectStatus(childKeys.at(i), settings.value(childKeys.at(i)).toBool()); QCheckBox *checkBox = ui->toggleablesWidget->findChild<QCheckBox*>(childKeys.at(i)); if(checkBox) { checkBox->setChecked(settings.value(childKeys.at(i)).toBool()); } } settings.endGroup(); setPlaybackControlsVisible(settings.value("playbackControlsVisible").toBool()); } void MainWindow::about() { QString translatedTextAboutCaption; // translatedTextAboutCaption = QMessageBox::tr( // "<h3>ADCS Simulation Tool</h3>" // "<p>SVN Revision: %1</p>" // "<p>SVN Status: %2</p>" // "<p>Built on %3 at %4</p>" // ).arg(QLatin1String(SVNVERSION), // QLatin1String(SVNSTATUS), // QLatin1String(__DATE__), // QLatin1String(__TIME__)); QString translatedTextAboutText; translatedTextAboutText = QMessageBox::tr( "<p>The program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.</p>"); QMessageBox *about = new QMessageBox(this); about->setAttribute(Qt::WA_DeleteOnClose); about->setWindowTitle(tr("About ADCS Simulation Tool")); about->setText(translatedTextAboutCaption); about->setInformativeText(translatedTextAboutText); QPixmap logo(":/resources/images/AVSlogo5-Large.png"); about->setIconPixmap(logo.scaledToHeight(100, Qt::SmoothTransformation)); about->show(); about->exec(); } void MainWindow::updateViewToolbarStates() { for(int i = 0; i < m_zoomActions.size(); i++) { m_zoomActions.at(i)->setVisible(m_cameraModeCombo->currentIndex() != 2); } for(int i = 0; i < m_panActions.size(); i++) { m_panActions.at(i)->setVisible(m_cameraModeCombo->currentIndex() == 1); } for(int i = 0; i < m_fpvActions.size(); i++) { m_fpvActions.at(i)->setVisible(m_cameraModeCombo->currentIndex() == 2); } } void MainWindow::updateShortcutsStates() { QVector<shortcutPair> sceneShortcuts = m_sceneWidget->getShortcuts(); int tot=ui->shortcutsTable->rowCount(); if(m_cameraModeCombo->currentIndex() !=2){ for (int i=tot; i>=(tot-sceneShortcuts.size());i--){ ui->shortcutsTable->hideRow(i); } } else { for (int i=(tot-sceneShortcuts.size()); i<=tot; i++){ ui->shortcutsTable->showRow(i); } } } void MainWindow::updateToggleables(QWidget *widget) { QCheckBox *checkBox = (QCheckBox *)widget; m_simDataManager->setToggleableObjectStatus(checkBox->text(), checkBox->isChecked()); } void MainWindow::setPlaybackControlsVisible(bool value) { if(value) { m_playbackControls->setFixedHeight(QWIDGETSIZE_MAX); } else { m_playbackControls->setFixedHeight(0); } }
41.413943
192
0.690647
mohawkjohn
69727009d55ca59e3f3d27bf829c440bb003129e
247
cpp
C++
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
#include "Chromosome.h" Chromosome::Chromosome() : genes() {}; Chromosome::Chromosome(int32_t size) { genes.resize(size); for (size_t i = 0; i < size; i++) { genes[i] = Gene(size); } } size_t Chromosome::Size() { return genes.size(); }
13
36
0.62753
DimaSidorenko
6973333093d5a9b67e56918efc65ae4890baac11
3,416
cpp
C++
gdfast/src/functions.cpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
1
2018-12-01T04:10:34.000Z
2018-12-01T04:10:34.000Z
gdfast/src/functions.cpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
null
null
null
gdfast/src/functions.cpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
null
null
null
#include "functions.hpp" #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> namespace gd { using namespace boost::numeric::ublas; void py_export_functions() { using namespace boost::python; def("matmul_2d_3d", matmul_2d_3d); def("matmul_3d_3d", matmul_3d_3d); def("velocity_cartesian_to_spherical", velocity_cartesian_to_spherical); def("add_to_matrix_indexed", add_to_matrix_indexed); } void add_to_matrix_indexed(double_matrix M, int_vector _i, int_vector _j, double_vector weight) { double* Mp = M.data().begin(); double* wp = weight.data().begin(); int* ip = _i.data().begin(); int* jp = _j.data().begin(); int size1 = M.size1(); int size2 = M.size2(); int length = min(min(_i.size(), _j.size()), weight.size()); for(int k = 0; k < length; k++) { int i = *ip++; int j = *jp++; double w = *wp++; if((i < size1) && (j < size2) && (i >= 0) && (j >= 0)) { int index = j + i * size2; Mp[index] += w; } } } void matmul_2d_3d(double_matrix M, double_vector x, double_vector y, double_vector xt, double_vector yt, double_vector zt) { double* Mp = M.data().begin(); int Mstride = M.size2(); double* xp = x.data().begin(); double* yp = y.data().begin(); double* xtp = xt.data().begin(); double* ytp = yt.data().begin(); double* ztp = zt.data().begin(); int size = x.size(); for(int i = 0; i < size; i++) { //for(int j = 0; j < 3; j++) { *xtp++ = (*xp) * Mp[0+Mstride*0] + (*yp) * Mp[0+Mstride*1]; *ytp++ = (*xp) * Mp[1+Mstride*0] + (*yp) * Mp[1+Mstride*1]; *ztp++ = (*xp) * Mp[2+Mstride*0] + (*yp) * Mp[2+Mstride*1]; xp++; yp++; //} } } void matmul_3d_3d(double_matrix M, double_vector x, double_vector y, double_vector z, double_vector xt, double_vector yt, double_vector zt) { double* Mp = M.data().begin(); int Mstride = M.size2(); double* xp = x.data().begin(); double* yp = y.data().begin(); double* zp = z.data().begin(); double* xtp = xt.data().begin(); double* ytp = yt.data().begin(); double* ztp = zt.data().begin(); int size = x.size(); for(int i = 0; i < size; i++) { *xtp++ = (*xp) * Mp[0+Mstride*0] + (*yp) * Mp[0+Mstride*1] + (*zp) * Mp[0+Mstride*2]; *ytp++ = (*xp) * Mp[1+Mstride*0] + (*yp) * Mp[1+Mstride*1] + (*zp) * Mp[1+Mstride*2]; *ztp++ = (*xp) * Mp[2+Mstride*0] + (*yp) * Mp[2+Mstride*1] + (*zp) * Mp[2+Mstride*2]; xp++; yp++; zp++; } } void velocity_cartesian_to_spherical(double_vector xv, double_vector yv, double_vector zv, double_vector vxv, double_vector vyv, double_vector vzv, double_vector vrv, double_vector vphiv, double_vector vthetav) { double *xp = xv.data().begin(); double *yp = yv.data().begin(); double *zp = zv.data().begin(); double *vxp = vxv.data().begin(); double *vyp = vyv.data().begin(); double *vzp = vzv.data().begin(); double *vrp = vrv.data().begin(); double *vphip = vphiv.data().begin(); double *vthetap = vthetav.data().begin(); double *xpend = xv.data().end(); while(xp != xpend) { double x = *xp++; double y = *yp++; double z = *zp++; double vx = *vxp++; double vy = *vyp++; double vz = *vzp++; double r = sqrt(x*x+y*y+z*z); double rhosq = (x*x+y*y); double rho = sqrt(rhosq); //double cosatan2xy = x / rho; //double sinatan2xy = y / rho; *vrp++ = (vx*x + vy*y + vz*z)/r; *vphip++ = (vy*x - vx*y)/rho; *vthetap++ = (vx*z*x/rho + vy*z*y/rho - vz*rho)/r; } } }
32.533333
212
0.60685
maartenbreddels
69755c97c66a733c90f12ed00a62408cd847e140
459
cpp
C++
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> using namespace std; #define FOR(i, n) for (int i = 1; i <= n; ++i) int main() { int n, m, a, b, c; int w[320][320]; long long s; scanf("%d", &n); FOR(i, n) FOR(j, n) scanf("%d", &w[i][j]); scanf("%d", &m); FOR(k, m) { scanf("%d%d%d", &a, &b, &c); s = 0; FOR(i, n) FOR(j, n) s += (w[i][j] = min(w[i][j], min(w[i][a] + c + w[b][j], w[i][b] + c + w[a][j]))); printf("%I64d\n", s / 2); } return 0; }
17.653846
103
0.457516
TiwariAnil
69773e46211d2b7a26e767416e7d3141f95437fd
1,312
hpp
C++
include/callable_to_funcptr/callable_to_funcptr.hpp
ncorgan/cpp-callable-to-funcptr
fafc8bf4beba3f9398ba5e62a193b8636560a9c3
[ "MIT" ]
1
2019-09-13T08:25:03.000Z
2019-09-13T08:25:03.000Z
include/callable_to_funcptr/callable_to_funcptr.hpp
ncorgan/cpp-callable-to-funcptr
fafc8bf4beba3f9398ba5e62a193b8636560a9c3
[ "MIT" ]
null
null
null
include/callable_to_funcptr/callable_to_funcptr.hpp
ncorgan/cpp-callable-to-funcptr
fafc8bf4beba3f9398ba5e62a193b8636560a9c3
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef CALLABLE_TO_FUNCPTR_HPP #define CALLABLE_TO_FUNCPTR_HPP #include "detail/define_internal_macros.hpp" #include "detail/callable/callable.hpp" #include "detail/funcptr_helper.hpp" #include <cassert> #include <functional> BEGIN_CALLABLE_TO_FUNCPTR_CLIENT_NAMESPACE template <size_t _UniqueId, typename _Callable> auto callable_to_funcptr(_Callable f) { auto func = to_stdfunction(f); assert(func); return detail::stdfunction_to_funcptr<detail::template_hash<_UniqueId, _Callable>()>(std::move(func)); } template <size_t _UniqueId, typename _Callable, typename _Res, typename... _Args> auto callable_to_funcptr(_Callable f) { std::function<_Res(_Args...)> func(f); assert(func); return detail::stdfunction_to_funcptr<detail::template_hash<_UniqueId, _Callable>()>(std::move(func)); } #define CALLABLE_TO_FUNCPTR(f) \ CALLABLE_TO_FUNCPTR_CLIENT_NAMESPACE::callable_to_funcptr< \ CALLABLE_TO_FUNCPTR_CLIENT_NAMESPACE::detail::hash_location(__FILE__, __LINE__), \ decltype(f)>(f) END_CALLABLE_TO_FUNCPTR_CLIENT_NAMESPACE #endif /* CALLABLE_TO_FUNCPTR_HPP */
27.914894
106
0.765244
ncorgan
6981a6356647992695df325bb03489f783c4828d
37,810
cc
C++
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 The Android Open Source Project * * 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 "src/trace_processor/importers/proto/graphics_event_parser.h" #include <inttypes.h> #include "perfetto/ext/base/utils.h" #include "perfetto/protozero/field.h" #include "src/trace_processor/importers/common/args_tracker.h" #include "src/trace_processor/importers/common/event_tracker.h" #include "src/trace_processor/importers/common/process_tracker.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/storage/trace_storage.h" #include "src/trace_processor/types/trace_processor_context.h" #include "protos/perfetto/common/gpu_counter_descriptor.pbzero.h" #include "protos/perfetto/trace/android/graphics_frame_event.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_counter_event.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_log.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_render_stage_event.pbzero.h" #include "protos/perfetto/trace/gpu/vulkan_api_event.pbzero.h" #include "protos/perfetto/trace/gpu/vulkan_memory_event.pbzero.h" #include "protos/perfetto/trace/interned_data/interned_data.pbzero.h" namespace perfetto { namespace trace_processor { namespace { // https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkObjectType.html typedef enum VkObjectType { VK_OBJECT_TYPE_UNKNOWN = 0, VK_OBJECT_TYPE_INSTANCE = 1, VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2, VK_OBJECT_TYPE_DEVICE = 3, VK_OBJECT_TYPE_QUEUE = 4, VK_OBJECT_TYPE_SEMAPHORE = 5, VK_OBJECT_TYPE_COMMAND_BUFFER = 6, VK_OBJECT_TYPE_FENCE = 7, VK_OBJECT_TYPE_DEVICE_MEMORY = 8, VK_OBJECT_TYPE_BUFFER = 9, VK_OBJECT_TYPE_IMAGE = 10, VK_OBJECT_TYPE_EVENT = 11, VK_OBJECT_TYPE_QUERY_POOL = 12, VK_OBJECT_TYPE_BUFFER_VIEW = 13, VK_OBJECT_TYPE_IMAGE_VIEW = 14, VK_OBJECT_TYPE_SHADER_MODULE = 15, VK_OBJECT_TYPE_PIPELINE_CACHE = 16, VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17, VK_OBJECT_TYPE_RENDER_PASS = 18, VK_OBJECT_TYPE_PIPELINE = 19, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20, VK_OBJECT_TYPE_SAMPLER = 21, VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22, VK_OBJECT_TYPE_DESCRIPTOR_SET = 23, VK_OBJECT_TYPE_FRAMEBUFFER = 24, VK_OBJECT_TYPE_COMMAND_POOL = 25, VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION = 1000156000, VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE = 1000085000, VK_OBJECT_TYPE_SURFACE_KHR = 1000000000, VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000, VK_OBJECT_TYPE_DISPLAY_KHR = 1000002000, VK_OBJECT_TYPE_DISPLAY_MODE_KHR = 1000002001, VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT = 1000011000, VK_OBJECT_TYPE_OBJECT_TABLE_NVX = 1000086000, VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX = 1000086001, VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT = 1000128000, VK_OBJECT_TYPE_VALIDATION_CACHE_EXT = 1000160000, VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV = 1000165000, VK_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000, VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR = VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE, VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR = VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION, VK_OBJECT_TYPE_MAX_ENUM = 0x7FFFFFFF } VkObjectType; } // anonymous namespace GraphicsEventParser::GraphicsEventParser(TraceProcessorContext* context) : context_(context), vulkan_memory_tracker_(context), description_id_(context->storage->InternString("description")), gpu_render_stage_scope_id_( context->storage->InternString("gpu_render_stage")), graphics_event_scope_id_( context->storage->InternString("graphics_frame_event")), unknown_event_name_id_(context->storage->InternString("unknown_event")), no_layer_name_name_id_(context->storage->InternString("no_layer_name")), layer_name_key_id_(context->storage->InternString("layer_name")), event_type_name_ids_{ {context->storage->InternString( "unspecified_event") /* UNSPECIFIED */, context->storage->InternString("Dequeue") /* DEQUEUE */, context->storage->InternString("Queue") /* QUEUE */, context->storage->InternString("Post") /* POST */, context->storage->InternString( "AcquireFenceSignaled") /* ACQUIRE_FENCE */, context->storage->InternString("Latch") /* LATCH */, context->storage->InternString( "HWCCompositionQueued") /* HWC_COMPOSITION_QUEUED */, context->storage->InternString( "FallbackComposition") /* FALLBACK_COMPOSITION */, context->storage->InternString( "PresentFenceSignaled") /* PRESENT_FENCE */, context->storage->InternString( "ReleaseFenceSignaled") /* RELEASE_FENCE */, context->storage->InternString("Modify") /* MODIFY */, context->storage->InternString("Detach") /* DETACH */, context->storage->InternString("Attach") /* ATTACH */, context->storage->InternString("Cancel") /* CANCEL */}}, present_frame_name_(present_frame_buffer_, base::ArraySize(present_frame_buffer_)), present_frame_layer_name_(present_frame_layer_buffer_, base::ArraySize(present_frame_layer_buffer_)), present_frame_numbers_(present_frame_numbers_buffer_, base::ArraySize(present_frame_numbers_buffer_)), gpu_log_track_name_id_(context_->storage->InternString("GPU Log")), gpu_log_scope_id_(context_->storage->InternString("gpu_log")), tag_id_(context_->storage->InternString("tag")), log_message_id_(context->storage->InternString("message")), log_severity_ids_{{context_->storage->InternString("UNSPECIFIED"), context_->storage->InternString("VERBOSE"), context_->storage->InternString("DEBUG"), context_->storage->InternString("INFO"), context_->storage->InternString("WARNING"), context_->storage->InternString("ERROR"), context_->storage->InternString( "UNKNOWN_SEVERITY") /* must be last */}}, vk_event_track_id_(context->storage->InternString("Vulkan Events")), vk_event_scope_id_(context->storage->InternString("vulkan_events")), vk_queue_submit_id_(context->storage->InternString("vkQueueSubmit")) {} void GraphicsEventParser::ParseGpuCounterEvent(int64_t ts, ConstBytes blob) { protos::pbzero::GpuCounterEvent::Decoder event(blob.data, blob.size); protos::pbzero::GpuCounterDescriptor::Decoder descriptor( event.counter_descriptor()); // Add counter spec to ID map. for (auto it = descriptor.specs(); it; ++it) { protos::pbzero::GpuCounterDescriptor_GpuCounterSpec::Decoder spec(*it); if (!spec.has_counter_id()) { PERFETTO_ELOG("Counter spec missing counter id"); context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); continue; } if (!spec.has_name()) { context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); continue; } auto counter_id = spec.counter_id(); auto name = spec.name(); if (gpu_counter_track_ids_.find(counter_id) == gpu_counter_track_ids_.end()) { auto desc = spec.description(); StringId unit_id = kNullStringId; if (spec.has_numerator_units() || spec.has_denominator_units()) { char buffer[1024]; base::StringWriter unit(buffer, sizeof(buffer)); for (auto numer = spec.numerator_units(); numer; ++numer) { if (unit.pos()) { unit.AppendChar(':'); } unit.AppendInt(*numer); } char sep = '/'; for (auto denom = spec.denominator_units(); denom; ++denom) { unit.AppendChar(sep); unit.AppendInt(*denom); sep = ':'; } unit_id = context_->storage->InternString(unit.GetStringView()); } auto name_id = context_->storage->InternString(name); auto desc_id = context_->storage->InternString(desc); auto track_id = context_->track_tracker->CreateGpuCounterTrack( name_id, 0 /* gpu_id */, desc_id, unit_id); gpu_counter_track_ids_.emplace(counter_id, track_id); if (spec.has_groups()) { for (auto group = spec.groups(); group; ++group) { tables::GpuCounterGroupTable::Row row; row.group_id = *group; row.track_id = track_id; context_->storage->mutable_gpu_counter_group_table()->Insert(row); } } else { tables::GpuCounterGroupTable::Row row; row.group_id = protos::pbzero::GpuCounterDescriptor::UNCLASSIFIED; row.track_id = track_id; context_->storage->mutable_gpu_counter_group_table()->Insert(row); } } else { // Either counter spec was repeated or it came after counter data. PERFETTO_ELOG("Duplicated counter spec found. (counter_id=%d, name=%s)", counter_id, name.ToStdString().c_str()); context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); } } for (auto it = event.counters(); it; ++it) { protos::pbzero::GpuCounterEvent_GpuCounter::Decoder counter(*it); if (counter.has_counter_id() && (counter.has_int_value() || counter.has_double_value())) { auto counter_id = counter.counter_id(); // Check missing counter_id if (gpu_counter_track_ids_.find(counter_id) == gpu_counter_track_ids_.end()) { char buffer[64]; base::StringWriter writer(buffer, sizeof(buffer)); writer.AppendString("gpu_counter("); writer.AppendUnsignedInt(counter_id); writer.AppendString(")"); auto name_id = context_->storage->InternString(writer.GetStringView()); TrackId track = context_->track_tracker->CreateGpuCounterTrack( name_id, 0 /* gpu_id */); gpu_counter_track_ids_.emplace(counter_id, track); context_->storage->IncrementStats(stats::gpu_counters_missing_spec); } if (counter.has_int_value()) { context_->event_tracker->PushCounter( ts, counter.int_value(), gpu_counter_track_ids_[counter_id]); } else { context_->event_tracker->PushCounter( ts, counter.double_value(), gpu_counter_track_ids_[counter_id]); } } } } const StringId GraphicsEventParser::GetFullStageName( const protos::pbzero::GpuRenderStageEvent_Decoder& event) const { size_t stage_id = static_cast<size_t>(event.stage_id()); StringId stage_name; if (stage_id < gpu_render_stage_ids_.size()) { stage_name = gpu_render_stage_ids_[stage_id].first; } else { char buffer[64]; snprintf(buffer, sizeof(buffer), "render stage(%zu)", stage_id); stage_name = context_->storage->InternString(buffer); } return stage_name; } /** * Create a GPU render stage track based * GpuRenderStageEvent.Specifications.Description. */ void GraphicsEventParser::InsertGpuTrack( const protos::pbzero:: GpuRenderStageEvent_Specifications_Description_Decoder& hw_queue) { StringId track_name = context_->storage->InternString(hw_queue.name()); if (gpu_hw_queue_counter_ >= gpu_hw_queue_ids_.size() || !gpu_hw_queue_ids_[gpu_hw_queue_counter_].has_value()) { tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track.description = context_->storage->InternString(hw_queue.description()); if (gpu_hw_queue_counter_ >= gpu_hw_queue_ids_.size()) { gpu_hw_queue_ids_.emplace_back( context_->track_tracker->InternGpuTrack(track)); } else { // If a gpu_render_stage_event is received before the specification, it is // possible that the slot has already been allocated. gpu_hw_queue_ids_[gpu_hw_queue_counter_] = context_->track_tracker->InternGpuTrack(track); } } else { // If a gpu_render_stage_event is received before the specification, a track // will be automatically generated. In that case, update the name and // description. auto track_id = gpu_hw_queue_ids_[gpu_hw_queue_counter_]; if (track_id.has_value()) { auto row = context_->storage->mutable_gpu_track_table() ->id() .IndexOf(track_id.value()) .value(); context_->storage->mutable_gpu_track_table()->mutable_name()->Set( row, track_name); context_->storage->mutable_gpu_track_table()->mutable_description()->Set( row, context_->storage->InternString(hw_queue.description())); } else { tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track.description = context_->storage->InternString(hw_queue.description()); } } ++gpu_hw_queue_counter_; } base::Optional<std::string> GraphicsEventParser::FindDebugName( int32_t vk_object_type, uint64_t vk_handle) const { auto map = debug_marker_names_.find(vk_object_type); if (map == debug_marker_names_.end()) { return base::nullopt; } auto name = map->second.find(vk_handle); if (name == map->second.end()) { return base::nullopt; } else { return name->second; } } void GraphicsEventParser::ParseGpuRenderStageEvent(int64_t ts, ConstBytes blob) { protos::pbzero::GpuRenderStageEvent::Decoder event(blob.data, blob.size); if (event.has_specifications()) { protos::pbzero::GpuRenderStageEvent_Specifications::Decoder spec( event.specifications().data, event.specifications().size); for (auto it = spec.hw_queue(); it; ++it) { protos::pbzero::GpuRenderStageEvent_Specifications_Description::Decoder hw_queue(*it); if (hw_queue.has_name()) { InsertGpuTrack(hw_queue); } } for (auto it = spec.stage(); it; ++it) { protos::pbzero::GpuRenderStageEvent_Specifications_Description::Decoder stage(*it); if (stage.has_name()) { gpu_render_stage_ids_.emplace_back(std::make_pair( context_->storage->InternString(stage.name()), context_->storage->InternString(stage.description()))); } } } auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { size_t stage_id = static_cast<size_t>(event.stage_id()); if (stage_id < gpu_render_stage_ids_.size()) { auto description = gpu_render_stage_ids_[stage_id].second; if (description != kNullStringId) { inserter->AddArg(description_id_, Variadic::String(description)); } } for (auto it = event.extra_data(); it; ++it) { protos::pbzero::GpuRenderStageEvent_ExtraData_Decoder datum(*it); StringId name_id = context_->storage->InternString(datum.name()); StringId value = context_->storage->InternString( datum.has_value() ? datum.value() : base::StringView()); inserter->AddArg(name_id, Variadic::String(value)); } }; if (event.has_event_id()) { TrackId track_id; uint32_t hw_queue_id = static_cast<uint32_t>(event.hw_queue_id()); if (hw_queue_id < gpu_hw_queue_ids_.size() && gpu_hw_queue_ids_[hw_queue_id].has_value()) { track_id = gpu_hw_queue_ids_[hw_queue_id].value(); } else { // If the event has a hw_queue_id that does not have a Specification, // create a new track for it. char buf[128]; base::StringWriter writer(buf, sizeof(buf)); writer.AppendLiteral("Unknown GPU Queue "); if (hw_queue_id > 1024) { // We don't expect this to happen, but just in case there is a corrupt // packet, make sure we don't allocate a ridiculous amount of memory. hw_queue_id = 1024; context_->storage->IncrementStats( stats::gpu_render_stage_parser_errors); PERFETTO_ELOG("Invalid hw_queue_id."); } else { writer.AppendInt(event.hw_queue_id()); } StringId track_name = context_->storage->InternString(writer.GetStringView()); tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track_id = context_->track_tracker->InternGpuTrack(track); gpu_hw_queue_ids_.resize(hw_queue_id + 1); gpu_hw_queue_ids_[hw_queue_id] = track_id; } auto render_target_name = FindDebugName(VK_OBJECT_TYPE_FRAMEBUFFER, event.render_target_handle()); auto render_target_name_id = render_target_name.has_value() ? context_->storage->InternString( render_target_name.value().c_str()) : kNullStringId; auto render_pass_name = FindDebugName(VK_OBJECT_TYPE_RENDER_PASS, event.render_pass_handle()); auto render_pass_name_id = render_pass_name.has_value() ? context_->storage->InternString( render_pass_name.value().c_str()) : kNullStringId; auto command_buffer_name = FindDebugName(VK_OBJECT_TYPE_COMMAND_BUFFER, event.command_buffer_handle()); auto command_buffer_name_id = command_buffer_name.has_value() ? context_->storage->InternString( command_buffer_name.value().c_str()) : kNullStringId; tables::GpuSliceTable::Row row; row.ts = ts; row.track_id = track_id; row.name = GetFullStageName(event); row.dur = static_cast<int64_t>(event.duration()); row.context_id = static_cast<int64_t>(event.context()); row.render_target = static_cast<int64_t>(event.render_target_handle()); row.render_target_name = render_target_name_id; row.render_pass = static_cast<int64_t>(event.render_pass_handle()); row.render_pass_name = render_pass_name_id; row.command_buffer = static_cast<int64_t>(event.command_buffer_handle()); row.command_buffer_name = command_buffer_name_id; row.submission_id = event.submission_id(); row.hw_queue_id = hw_queue_id; context_->slice_tracker->ScopedGpu(row, args_callback); } } void GraphicsEventParser::ParseGraphicsFrameEvent(int64_t timestamp, ConstBytes blob) { using GraphicsFrameEvent = protos::pbzero::GraphicsFrameEvent; protos::pbzero::GraphicsFrameEvent_Decoder frame_event(blob.data, blob.size); if (!frame_event.has_buffer_event()) { return; } ConstBytes bufferBlob = frame_event.buffer_event(); protos::pbzero::GraphicsFrameEvent_BufferEvent_Decoder event(bufferBlob.data, bufferBlob.size); if (!event.has_buffer_id()) { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with missing buffer id field."); return; } StringId event_name_id = unknown_event_name_id_; if (event.has_type()) { const auto type = static_cast<size_t>(event.type()); if (type < event_type_name_ids_.size()) { event_name_id = event_type_name_ids_[type]; graphics_frame_stats_map_[event.buffer_id()][type] = timestamp; } else { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with unknown type %zu.", type); } } else { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with missing type field."); } const uint32_t buffer_id = event.buffer_id(); StringId layer_name_id; char buffer[4096]; const size_t layerNameMaxLength = 4000; base::StringWriter track_name(buffer, sizeof(buffer)); if (event.has_layer_name()) { const base::StringView layer_name(event.layer_name()); layer_name_id = context_->storage->InternString(layer_name); track_name.AppendString(layer_name.substr(0, layerNameMaxLength)); } else { layer_name_id = no_layer_name_name_id_; track_name.AppendLiteral("unknown_layer"); } track_name.AppendLiteral("[buffer:"); track_name.AppendUnsignedInt(buffer_id); track_name.AppendChar(']'); const StringId track_name_id = context_->storage->InternString(track_name.GetStringView()); const int64_t duration = event.has_duration_ns() ? static_cast<int64_t>(event.duration_ns()) : 0; const uint32_t frame_number = event.has_frame_number() ? event.frame_number() : 0; tables::GpuTrackTable::Row track(track_name_id); track.scope = graphics_event_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); { char frame_number_buffer[256]; base::StringWriter frame_numbers(frame_number_buffer, base::ArraySize(frame_number_buffer)); frame_numbers.AppendUnsignedInt(frame_number); tables::GraphicsFrameSliceTable::Row row; row.ts = timestamp; row.track_id = track_id; row.name = event_name_id; row.dur = duration; row.frame_numbers = context_->storage->InternString(frame_numbers.GetStringView()); row.layer_names = layer_name_id; context_->slice_tracker->ScopedFrameEvent(row); } /* Displayed Frame track */ if (event.type() == GraphicsFrameEvent::PRESENT_FENCE) { // Insert the frame stats for the buffer that was presented auto acquire_ts = graphics_frame_stats_map_[event.buffer_id()] [GraphicsFrameEvent::ACQUIRE_FENCE]; auto queue_ts = graphics_frame_stats_map_[event.buffer_id()][GraphicsFrameEvent::QUEUE]; auto latch_ts = graphics_frame_stats_map_[event.buffer_id()][GraphicsFrameEvent::LATCH]; tables::GraphicsFrameStatsTable::Row stats_row; // AcquireFence can signal before Queue sometimes, so have 0 as a bound. stats_row.queue_to_acquire_time = std::max(acquire_ts - queue_ts, static_cast<int64_t>(0)); stats_row.acquire_to_latch_time = latch_ts - acquire_ts; stats_row.latch_to_present_time = timestamp - latch_ts; auto stats_row_id = context_->storage->mutable_graphics_frame_stats_table()->Insert( stats_row); if (previous_timestamp_ == 0) { const StringId present_track_name_id = context_->storage->InternString("Displayed Frame"); tables::GpuTrackTable::Row present_track(present_track_name_id); present_track.scope = graphics_event_scope_id_; present_track_id_ = context_->track_tracker->InternGpuTrack(present_track); } // The displayed frame is a slice from one present fence to another present // fence. If multiple buffers have present fence at the same time, they all // are shown on screen at the same time. So that particular displayed frame // slice should include info from all those buffers in it. // Since the events are parsed one by one, the following bookkeeping is // needed to create the slice properly. if (previous_timestamp_ == timestamp && previous_timestamp_ != 0) { // Same timestamp as previous present fence. This buffer should also // contribute to this slice. present_frame_name_.AppendLiteral(", "); present_frame_name_.AppendUnsignedInt(buffer_id); // Append Layer names present_frame_layer_name_.AppendLiteral(", "); present_frame_layer_name_.AppendString(event.layer_name()); // Append Frame numbers present_frame_numbers_.AppendLiteral(", "); present_frame_numbers_.AppendUnsignedInt(frame_number); // Add the current stats row to the list of stats that go with this frame graphics_frame_stats_idx_.push_back(stats_row_id.row); } else { if (previous_timestamp_ != 0) { StringId present_frame_layer_name_id = context_->storage->InternString( present_frame_layer_name_.GetStringView()); // End the current slice that's being tracked. const auto opt_slice_id = context_->slice_tracker->EndFrameEvent( timestamp, present_track_id_); if (opt_slice_id) { // The slice could have had additional buffers in it, so we need to // update the table. auto* graphics_frame_slice_table = context_->storage->mutable_graphics_frame_slice_table(); uint32_t row_idx = *graphics_frame_slice_table->id().IndexOf(*opt_slice_id); StringId frame_name_id = context_->storage->InternString( present_frame_name_.GetStringView()); graphics_frame_slice_table->mutable_name()->Set(row_idx, frame_name_id); StringId present_frame_numbers_id = context_->storage->InternString( present_frame_numbers_.GetStringView()); graphics_frame_slice_table->mutable_frame_numbers()->Set( row_idx, present_frame_numbers_id); graphics_frame_slice_table->mutable_layer_names()->Set( row_idx, present_frame_layer_name_id); // Set the slice_id for the frame_stats rows under this displayed // frame auto* slice_table = context_->storage->mutable_slice_table(); uint32_t slice_idx = *slice_table->id().IndexOf(*opt_slice_id); for (uint32_t i = 0; i < graphics_frame_stats_idx_.size(); i++) { context_->storage->mutable_graphics_frame_stats_table() ->mutable_slice_id() ->Set(graphics_frame_stats_idx_[i], slice_idx); } } present_frame_layer_name_.reset(); present_frame_name_.reset(); present_frame_numbers_.reset(); graphics_frame_stats_idx_.clear(); } // Start a new slice present_frame_name_.AppendUnsignedInt(buffer_id); previous_timestamp_ = timestamp; present_frame_layer_name_.AppendString(event.layer_name()); present_frame_numbers_.AppendUnsignedInt(frame_number); present_event_name_id_ = context_->storage->InternString(present_frame_name_.GetStringView()); graphics_frame_stats_idx_.push_back(stats_row_id.row); tables::GraphicsFrameSliceTable::Row row; row.ts = timestamp; row.track_id = present_track_id_; row.name = present_event_name_id_; context_->slice_tracker->BeginFrameEvent(row); } } } void GraphicsEventParser::UpdateVulkanMemoryAllocationCounters( UniquePid upid, const VulkanMemoryEvent::Decoder& event) { StringId track_str_id = kNullStringId; TrackId track = kInvalidTrackId; auto allocation_scope = VulkanMemoryEvent::SCOPE_UNSPECIFIED; uint32_t memory_type = std::numeric_limits<uint32_t>::max(); switch (event.source()) { case VulkanMemoryEvent::SOURCE_DRIVER: allocation_scope = static_cast<VulkanMemoryEvent::AllocationScope>( event.allocation_scope()); if (allocation_scope == VulkanMemoryEvent::SCOPE_UNSPECIFIED) return; switch (event.operation()) { case VulkanMemoryEvent::OP_CREATE: vulkan_driver_memory_counters_[allocation_scope] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY: vulkan_driver_memory_counters_[allocation_scope] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_BIND: case VulkanMemoryEvent::OP_DESTROY_BOUND: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindAllocationScopeCounterString( allocation_scope); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_driver_memory_counters_[allocation_scope], track); break; case VulkanMemoryEvent::SOURCE_DEVICE_MEMORY: memory_type = static_cast<uint32_t>(event.memory_type()); switch (event.operation()) { case VulkanMemoryEvent::OP_CREATE: vulkan_device_memory_counters_allocate_[memory_type] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY: vulkan_device_memory_counters_allocate_[memory_type] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_BIND: case VulkanMemoryEvent::OP_DESTROY_BOUND: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindMemoryTypeCounterString( memory_type, VulkanMemoryTracker::DeviceCounterType::kAllocationCounter); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_device_memory_counters_allocate_[memory_type], track); break; case VulkanMemoryEvent::SOURCE_BUFFER: case VulkanMemoryEvent::SOURCE_IMAGE: memory_type = static_cast<uint32_t>(event.memory_type()); switch (event.operation()) { case VulkanMemoryEvent::OP_BIND: vulkan_device_memory_counters_bind_[memory_type] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY_BOUND: vulkan_device_memory_counters_bind_[memory_type] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_CREATE: case VulkanMemoryEvent::OP_DESTROY: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindMemoryTypeCounterString( memory_type, VulkanMemoryTracker::DeviceCounterType::kBindCounter); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_device_memory_counters_bind_[memory_type], track); break; case VulkanMemoryEvent::SOURCE_UNSPECIFIED: case VulkanMemoryEvent::SOURCE_DEVICE: return; } } void GraphicsEventParser::ParseVulkanMemoryEvent( PacketSequenceStateGeneration* sequence_state, ConstBytes blob) { using protos::pbzero::InternedData; VulkanMemoryEvent::Decoder vulkan_memory_event(blob.data, blob.size); tables::VulkanMemoryAllocationsTable::Row vulkan_memory_event_row; vulkan_memory_event_row.source = vulkan_memory_tracker_.FindSourceString( static_cast<VulkanMemoryEvent::Source>(vulkan_memory_event.source())); vulkan_memory_event_row.operation = vulkan_memory_tracker_.FindOperationString( static_cast<VulkanMemoryEvent::Operation>( vulkan_memory_event.operation())); vulkan_memory_event_row.timestamp = vulkan_memory_event.timestamp(); vulkan_memory_event_row.upid = context_->process_tracker->GetOrCreateProcess(vulkan_memory_event.pid()); if (vulkan_memory_event.has_device()) vulkan_memory_event_row.device = static_cast<int64_t>(vulkan_memory_event.device()); if (vulkan_memory_event.has_device_memory()) vulkan_memory_event_row.device_memory = static_cast<int64_t>(vulkan_memory_event.device_memory()); if (vulkan_memory_event.has_heap()) vulkan_memory_event_row.heap = vulkan_memory_event.heap(); if (vulkan_memory_event.has_memory_type()) vulkan_memory_event_row.memory_type = vulkan_memory_event.memory_type(); if (vulkan_memory_event.has_caller_iid()) { vulkan_memory_event_row.function_name = vulkan_memory_tracker_ .GetInternedString<InternedData::kFunctionNamesFieldNumber>( sequence_state, static_cast<uint64_t>(vulkan_memory_event.caller_iid())); } if (vulkan_memory_event.has_object_handle()) vulkan_memory_event_row.object_handle = static_cast<int64_t>(vulkan_memory_event.object_handle()); if (vulkan_memory_event.has_memory_address()) vulkan_memory_event_row.memory_address = static_cast<int64_t>(vulkan_memory_event.memory_address()); if (vulkan_memory_event.has_memory_size()) vulkan_memory_event_row.memory_size = static_cast<int64_t>(vulkan_memory_event.memory_size()); if (vulkan_memory_event.has_allocation_scope()) vulkan_memory_event_row.scope = vulkan_memory_tracker_.FindAllocationScopeString( static_cast<VulkanMemoryEvent::AllocationScope>( vulkan_memory_event.allocation_scope())); UpdateVulkanMemoryAllocationCounters(vulkan_memory_event_row.upid.value(), vulkan_memory_event); auto* allocs = context_->storage->mutable_vulkan_memory_allocations_table(); VulkanAllocId id = allocs->Insert(vulkan_memory_event_row).id; if (vulkan_memory_event.has_annotations()) { auto inserter = context_->args_tracker->AddArgsTo(id); for (auto it = vulkan_memory_event.annotations(); it; ++it) { protos::pbzero::VulkanMemoryEventAnnotation::Decoder annotation(*it); auto key_id = vulkan_memory_tracker_ .GetInternedString<InternedData::kVulkanMemoryKeysFieldNumber>( sequence_state, static_cast<uint64_t>(annotation.key_iid())); if (annotation.has_int_value()) { inserter.AddArg(key_id, Variadic::Integer(annotation.int_value())); } else if (annotation.has_double_value()) { inserter.AddArg(key_id, Variadic::Real(annotation.double_value())); } else if (annotation.has_string_iid()) { auto string_id = vulkan_memory_tracker_ .GetInternedString<InternedData::kVulkanMemoryKeysFieldNumber>( sequence_state, static_cast<uint64_t>(annotation.string_iid())); inserter.AddArg(key_id, Variadic::String(string_id)); } } } } void GraphicsEventParser::ParseGpuLog(int64_t ts, ConstBytes blob) { protos::pbzero::GpuLog::Decoder event(blob.data, blob.size); tables::GpuTrackTable::Row track(gpu_log_track_name_id_); track.scope = gpu_log_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { if (event.has_tag()) { inserter->AddArg( tag_id_, Variadic::String(context_->storage->InternString(event.tag()))); } if (event.has_log_message()) { inserter->AddArg(log_message_id_, Variadic::String(context_->storage->InternString( event.log_message()))); } }; auto severity = static_cast<size_t>(event.severity()); StringId severity_id = severity < log_severity_ids_.size() ? log_severity_ids_[static_cast<size_t>(event.severity())] : log_severity_ids_[log_severity_ids_.size() - 1]; tables::GpuSliceTable::Row row; row.ts = ts; row.track_id = track_id; row.name = severity_id; row.dur = 0; context_->slice_tracker->ScopedGpu(row, args_callback); } void GraphicsEventParser::ParseVulkanApiEvent(int64_t ts, ConstBytes blob) { protos::pbzero::VulkanApiEvent::Decoder vk_event(blob.data, blob.size); if (vk_event.has_vk_debug_utils_object_name()) { protos::pbzero::VulkanApiEvent_VkDebugUtilsObjectName::Decoder event( vk_event.vk_debug_utils_object_name()); debug_marker_names_[event.object_type()][event.object()] = event.object_name().ToStdString(); } if (vk_event.has_vk_queue_submit()) { protos::pbzero::VulkanApiEvent_VkQueueSubmit::Decoder event( vk_event.vk_queue_submit()); // Once flow table is implemented, we can create a nice UI that link the // vkQueueSubmit to GpuRenderStageEvent. For now, just add it as in a GPU // track so that they can appear close to the render stage slices. tables::GpuTrackTable::Row track(vk_event_track_id_); track.scope = vk_event_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); tables::GpuSliceTable::Row row; row.ts = ts; row.dur = static_cast<int64_t>(event.duration_ns()); row.track_id = track_id; row.name = vk_queue_submit_id_; if (event.has_vk_command_buffers()) { row.command_buffer = static_cast<int64_t>(*event.vk_command_buffers()); } row.submission_id = event.submission_id(); auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { inserter->AddArg(context_->storage->InternString("pid"), Variadic::Integer(event.pid())); inserter->AddArg(context_->storage->InternString("tid"), Variadic::Integer(event.tid())); }; context_->slice_tracker->ScopedGpu(row, args_callback); } } } // namespace trace_processor } // namespace perfetto
43.063781
107
0.687834
kuscsik
6981d94a4378de6858f672b08a598c7278f2b7d8
1,887
cpp
C++
ext/nuvo_image/src/SSIM.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
null
null
null
ext/nuvo_image/src/SSIM.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
5
2016-08-02T13:33:02.000Z
2020-11-03T15:22:52.000Z
ext/nuvo_image/src/SSIM.cpp
crema/nuvo-image
365e4a54429fe4180e03adb1968ab9989e7ee5fb
[ "MIT" ]
null
null
null
#include "SSIM.h" int QualitySSIM::InterpolationTargetSSIM(const QualitySSIM& min, const QualitySSIM& max, const double targetSSIM) { auto slope = (max.quality - min.quality) / (max.ssim - min.ssim); return (int)round(slope * (targetSSIM - min.ssim)) + min.quality; } SSIMData::SSIMData(const cv::Mat& mat) { mat.convertTo(image, CV_32F); imageSquare = image.mul(image); GaussianBlur(image, imageBlur, cv::Size(11, 11), 1.5); imageBlurSquare = imageBlur.mul(imageBlur); GaussianBlur(imageSquare, sigma, cv::Size(11, 11), 1.5); sigma -= imageBlurSquare; } double SSIMData::GetSSIM(const SSIMData& a, const SSIMData& b) { const double C1 = 6.5025, C2 = 58.5225; auto& I1 = a.image; auto& I2 = b.image; auto& I1_2 = a.imageSquare; auto& I2_2 = b.imageSquare; cv::Mat I1_I2 = I1.mul(I2); // I1 * I2 /*************************** END INITS **********************************/ auto& mu1 = a.imageBlur; auto& mu2 = b.imageBlur; auto& mu1_2 = a.imageBlurSquare; auto& mu2_2 = b.imageBlurSquare; cv::Mat mu1_mu2 = mu1.mul(mu2); auto& sigma1_2 = a.sigma; auto& sigma2_2 = b.sigma; cv::Mat sigma12; GaussianBlur(I1_I2, sigma12, cv::Size(11, 11), 1.5); sigma12 -= mu1_mu2; ///////////////////////////////// FORMULA //////////////////////////////// cv::Mat t1, t2, t3; t1 = 2 * mu1_mu2 + C1; t2 = 2 * sigma12 + C2; t3 = t1.mul(t2); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2)) t1 = mu1_2 + mu2_2 + C1; t2 = sigma1_2 + sigma2_2 + C2; t1 = t1.mul(t2); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2)) cv::Mat ssim_map; divide(t3, t1, ssim_map); // ssim_map = t3./t1; cv::Scalar mssim = mean(ssim_map); // mssim = average of ssim map if (mssim[1] == 0 && mssim[2] == 0 && mssim[3] == 0) { return mssim[0]; } else { auto ssim = (mssim[0] + mssim[1] + mssim[2]) / 3; return ssim; } }
28.164179
115
0.578166
crema
6982eb81b8671793a852a2d46155e8aaa3a3de45
2,716
cpp
C++
src/common/types/statistics.cpp
xhochy/duckdb
20ba65f96794ab53f7a66e22d9bc58d59d8bc623
[ "MIT" ]
null
null
null
src/common/types/statistics.cpp
xhochy/duckdb
20ba65f96794ab53f7a66e22d9bc58d59d8bc623
[ "MIT" ]
null
null
null
src/common/types/statistics.cpp
xhochy/duckdb
20ba65f96794ab53f7a66e22d9bc58d59d8bc623
[ "MIT" ]
1
2019-09-06T09:58:14.000Z
2019-09-06T09:58:14.000Z
#include "common/types/statistics.hpp" #include "common/exception.hpp" #include "common/limits.hpp" #include "common/printer.hpp" #include "common/types/vector.hpp" #include "common/value_operations/value_operations.hpp" #include "common/vector_operations/vector_operations.hpp" using namespace duckdb; using namespace std; void ExpressionStatistics::Verify(Vector &vector) { #ifdef DEBUG if (!has_stats || vector.count == 0) return; if (!can_have_null) { assert(!VectorOperations::HasNull(vector)); } if (!min.is_null) { Value actual_min = VectorOperations::Min(vector); assert(actual_min.is_null || min <= actual_min); } if (!max.is_null) { Value actual_max = VectorOperations::Max(vector); assert(actual_max.is_null || max >= actual_max); } if (vector.type == TypeId::VARCHAR) { Value actual_max_strlen = VectorOperations::MaximumStringLength(vector); Value stats_max_strlen = Value::Numeric(actual_max_strlen.type, maximum_string_length); assert(actual_max_strlen <= stats_max_strlen); } #endif } void ExpressionStatistics::SetFromValue(Value value) { has_stats = true; can_have_null = value.is_null; maximum_string_length = value.type == TypeId::VARCHAR ? value.str_value.size() : 0; if (TypeIsIntegral(value.type) && value.type != TypeId::BIGINT) { // upcast to biggest integral type max = min = value.CastAs(TypeId::BIGINT); } else { max = min = value; } } ExpressionStatistics &ExpressionStatistics::operator=(const ExpressionStatistics &other) { this->has_stats = other.has_stats; this->can_have_null = other.can_have_null; this->min = other.min; this->max = other.max; this->maximum_string_length = other.maximum_string_length; return *this; } string ExpressionStatistics::ToString() const { if (!has_stats) { return "[NO STATS]"; } return "[" + min.ToString() + ", " + max.ToString() + "]"; } void ExpressionStatistics::Reset() { has_stats = false; can_have_null = false; min = Value(); max = Value(); maximum_string_length = 0; } bool ExpressionStatistics::FitsInType(TypeId type) { if (!TypeIsIntegral(type)) { return true; } if (!has_stats || min.is_null || max.is_null) { return true; } auto min_value = MinimumValue(type); auto max_value = MaximumValue(type); return min_value <= min.GetNumericValue() && max_value >= (uint64_t)max.GetNumericValue(); } TypeId ExpressionStatistics::MinimalType() { if (!TypeIsIntegral(min.type) || min.is_null || max.is_null) { return min.type; } assert(TypeIsIntegral(min.type) && TypeIsIntegral(max.type)); return std::max(duckdb::MinimalType(min.GetNumericValue()), duckdb::MinimalType(max.GetNumericValue())); } void ExpressionStatistics::Print() { Printer::Print(ToString()); }
28.291667
105
0.726804
xhochy
6986813ff0789e8d9032fa6ecfba6411feee985c
965
cpp
C++
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
5
2019-04-07T05:39:11.000Z
2020-07-23T01:43:02.000Z
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; const int maxn = 1e5+10; #define dbg(x) cout<<#x<<" = "<<x<<endl #define ok cout<<"OK"<<endl int a[maxn]; int main() { int t; scanf("%d",&t); while(t--) { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); int pos; for(int i=1;i<=n;i++) { if(a[i]!=-1) { pos=i; break; } } for(int i=pos-1;i>=1;i--) { if(a[i]==-1) a[i]=((a[i+1]-1)+m)%m; else continue; } for(int i=pos;i<=n;i++) { if(a[i]==-1) a[i]=(a[i-1]+1)%m; else continue; } for(int i=1;i<=n;i++) { printf("%d",a[i]); if(i!=n) printf(" "); } printf("\n"); } return 0; }
20.978261
49
0.344041
lajiyuan
698b5b2f8461d4565c4b7c9329ab4671aec59b3e
944
hpp
C++
SDK/include/NDK/Widgets/BoxLayout.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
SDK/include/NDK/Widgets/BoxLayout.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
SDK/include/NDK/Widgets/BoxLayout.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequisites.hpp #pragma once #ifndef NDK_WIDGETS_BOXLAYOUT_HPP #define NDK_WIDGETS_BOXLAYOUT_HPP #include <NDK/Prerequisites.hpp> #include <NDK/BaseWidget.hpp> #include <NDK/Widgets/Enums.hpp> #include <memory> namespace Ndk { class NDK_API BoxLayout : public BaseWidget { public: BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation); BoxLayout(const BoxLayout&) = delete; BoxLayout(BoxLayout&&) = delete; ~BoxLayout(); void Layout() override; BoxLayout& operator=(const BoxLayout&) = delete; BoxLayout& operator=(BoxLayout&&) = delete; private: struct State; std::unique_ptr<State> m_state; BoxLayoutOrientation m_orientation; float m_spacing; }; } #include <NDK/Widgets/BoxLayout.inl> #endif // NDK_WIDGETS_BOXLAYOUT_HPP
22.47619
84
0.745763
AntoineJT
698c5a84910801cc8b5f76fef3de78143080b527
1,004
cpp
C++
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int len = nums.size(), num1, num2, count1 = 0, count2 = 0; vector<int> res; for (int i = 0; i < len; i ++) { if (num1 == nums[i]) count1 ++; else if (num2 == nums[i]) count2 ++; else if (count1 == 0) { count1 ++; num1 = nums[i]; } else if (count2 == 0) { count2 ++; num2 = nums[i]; } else { count1 --; count2 --; } } count1 = 0; count2 = 0; for (int i = 0; i < len; i ++) { if (num1 == nums[i]) count1 ++; if (num2 == nums[i]) count2 ++; } if (count1 > len/3) res.push_back(num1); if (count2 > len/3) res.push_back(num2); return res; } };
25.1
66
0.351594
zszyellow
698d98ae147a4a384153896fe6aa3a1a7a3a4467
5,154
cpp
C++
Data Structures/Graphs/Boruvka_algorithm_for_finding_MST.cpp
siddhi-244/CompetitiveProgrammingQuestionBank
4c265d41b82a7d4370c14d367f78effa9ed95d3c
[ "MIT" ]
931
2020-04-18T11:57:30.000Z
2022-03-31T15:15:39.000Z
Data Structures/Graphs/Boruvka_algorithm_for_finding_MST.cpp
siddhi-244/CompetitiveProgrammingQuestionBank
4c265d41b82a7d4370c14d367f78effa9ed95d3c
[ "MIT" ]
661
2020-12-13T04:31:48.000Z
2022-03-15T19:11:54.000Z
Data Structures/Graphs/Boruvka_algorithm_for_finding_MST.cpp
siddhi-244/CompetitiveProgrammingQuestionBank
4c265d41b82a7d4370c14d367f78effa9ed95d3c
[ "MIT" ]
351
2020-08-10T06:49:21.000Z
2022-03-25T04:02:12.000Z
/* Boruvka’s Algorithm is a greedy algorithm used for finding Minimum Spanning Tree (MST) for a connected, weighted, and undirected graph. The goal of the algorithm is to connect “components” using the shortest or cheapest edge between the components. It begins with all of the vertices considered as separate components. Boruvka’s algorithm is parallel in nature. It operates in phases. In each phase, it selects the cheapest edge from each component, adds all of these to the MST at once, and then contracts each connected component into a single component. We make use of a Union-Find data structure to keep track of the components. This program takes a connected, weighted, and undirected graph as input and prints the total weight of edges in MST. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; const int N = (int)1e5 + 7; //a structure which represents a weighted graph edge struct edge { int v, u, cost; }; //global declaration of number of nodes int n; //global declaration of number of edges int m; //global declaration of parent array int p[N]; //Array to store the minimum or cheapest outgoing edge for each component of graph int min_edge[N]; //Array to store all edges edge g[N]; // Function to find root of a certain component for union find algorithm int root(int v) { if (p[v] == v) return v; return (p[v] = root(p[v])); } // Function to perform union two components bool merge(int v, int u) { v = root(v), u = root(u); if (v == u) return 0; p[v] = u; return 1; } // Function to initialize DSU // Initially, all vertices are their own parents void init_div() { for (int i = 1; i <= n; i++) { p[i] = i; } } //Main function to find MST using Boruvka's algorithm void boruvkaAlgorithm() { //Function call to initialize DSU init_div(); // No. of components int cnt_cmp = n; //Weight of MST ll MSTweight = 0; // Keep combining components until all components are not combined into a single MST. while (cnt_cmp > 1) { // Everytime initialize cheapest array to -1 as initially there is no cheapest edge for (int i = 1; i <= n; i++) min_edge[i] = -1; //Traverses through all edges to find the cheapest edge for each component for (int i = 1; i <= m; i++) { //If the nodes are in the same component then continue if (root(g[i].v) == root(g[i].u)) continue; //Else take roots of 1st and 2nd components and check if current edge is cheapest edge int r_v = root(g[i].v); if (min_edge[r_v] == -1 || g[i].cost < g[min_edge[r_v]].cost) { min_edge[r_v] = i; } int r_u = root(g[i].u); if (min_edge[r_u] == -1 || g[i].cost < g[min_edge[r_v]].cost) { min_edge[r_u] = i; } } // Consider the above picked cheapest edges and add them // to MST for (int i = 1; i <= n; i++) { if (min_edge[i] != -1) { //If the two vertices that are connected with this edge //can be merged then add its weight to the answer,i.e MSTweight //and decrease the number of components by one if (merge(g[min_edge[i]].v, g[min_edge[i]].u)) { MSTweight += g[min_edge[i]].cost; cnt_cmp--; } } } } cout << "Total weight of Minimum Spanning Tree for the given graph: " << MSTweight << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << "Input number of nodes and edges" << endl; cin >> n >> m; cout << "Input source vertex, target vertex and weight for each edge" << endl; for (int i = 1; i <= m; i++) { cin >> g[i].v >> g[i].u >> g[i].cost; } boruvkaAlgorithm(); return 0; } /* INPUT: Input number of nodes and edges 4 5 Input source vertex, target vertex and weight for each edge 1 2 10 2 3 15 1 3 5 4 2 2 4 3 40 OUTPUT: Total weight of Minimum Spanning Tree for the given graph: 17 Time Complexity: O(E log V) E = Number of edges V = Number of vertices Space Complexity: O(N) */
32.828025
144
0.504269
siddhi-244
7e3453f96836fef78100e4b37d2e90bf05b4f6b5
1,202
hpp
C++
src/FileReader.hpp
TravisWheelerLab/ULTRA
a8f05424903b68cea630d7ef5102fb1b3cc9395c
[ "BSD-3-Clause" ]
8
2019-10-06T14:46:29.000Z
2022-03-27T14:09:50.000Z
src/FileReader.hpp
TravisWheelerLab/ULTRA
a8f05424903b68cea630d7ef5102fb1b3cc9395c
[ "BSD-3-Clause" ]
6
2019-08-08T22:24:04.000Z
2021-11-12T18:24:22.000Z
src/FileReader.hpp
TravisWheelerLab/ULTRA
a8f05424903b68cea630d7ef5102fb1b3cc9395c
[ "BSD-3-Clause" ]
1
2019-11-28T00:47:59.000Z
2019-11-28T00:47:59.000Z
// // FileReader.hpp // ultrax // // Created by Daniel Olson on 10/16/19. // Copyright © 2019 Daniel Olson. All rights reserved. // #ifndef FileReader_hpp #define FileReader_hpp #include "FASTAReader.hpp" #include "JSONReader.hpp" #include <stdio.h> typedef enum { UNKNOWN, FASTA, JSON } file_type; class FileReader { public: unsigned long maxWindows; unsigned long maxSeqLength; unsigned long maxOverlapLength; bool multithread = true; file_type format = UNKNOWN; FASTAReader *fastaReader = NULL; JSONReader *jsonReader = NULL; SequenceWindow *GetReadyWindow(); bool AddReadyWindow(SequenceWindow *window); SequenceWindow *GetWaitingWindow(); bool AddWaitingWindow(SequenceWindow *window); bool FillWindows(); bool IsReading(); bool DoneReadingFile(); unsigned long ReadyWindowsSize(); void SetIsReading(bool value); FileReader(std::string FASTAFilePath, unsigned long maxWindows, unsigned long maxSeqLength, unsigned long maxOverlapLength, bool multithread); FileReader(std::string JSONFilePath, unsigned long maxSeqLength, unsigned long maxOverlapLength, bool multithread); }; #endif /* FileReader_hpp */
22.259259
72
0.730449
TravisWheelerLab
7e36458397b0c141e4c22925d02cd9f818d67f96
460
cpp
C++
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
4
2019-01-27T01:00:44.000Z
2019-01-29T02:09:55.000Z
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
null
null
null
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
1
2019-02-04T11:34:40.000Z
2019-02-04T11:34:40.000Z
#include <stdio.h> int main() { int* pc, c; c = 22; printf("Address of c: %u\n", &c); printf("Value of c: %d\n\n", c); pc = &c; printf("Address of pointer pc: %u\n", pc); printf("Content of pointer pc: %d\n\n", *pc); c = 11; printf("Address of pointer pc: %u\n", pc); printf("Content of pointer pc: %d\n\n", *pc); *pc = 2; printf("Address of c: %u\n", &c); printf("Value of c: %d\n\n", c); return 0; }
20
48
0.506522
dealbisac
7e3942e471817d240aeab7dfb612550a44ea6f42
1,300
cpp
C++
src/analysis/linpred/autocorr.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
src/analysis/linpred/autocorr.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
src/analysis/linpred/autocorr.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
#include "linpred.h" using namespace Analysis::LP; std::vector<double> Autocorr::solve(const double *x, int length, int lpcOrder, double *pGain) { const int n = length; const int m = lpcOrder; double gain; r.resize(m + 2, 0.0); a.resize(m + 2, 0.0); rc.resize(m + 1, 0.0); int i = 1; for (i = 1; i <= m + 1; ++i) { for (int j = 1; j <= n - i + 1; ++j) { r[i] += x[j - 1] * x[j + i - 2]; } } if (r[1] == 0.0) { i = 1; goto end; } a[1] = 1.0; a[2] = rc[1] = -r[2] / r[1]; gain = r[1] + r[2] * rc[1]; for (i = 2; i <= m; ++i) { double s = 0.0; for (int j = 1; j <= i; ++j) { s += r[i - j + 2] * a[j]; } rc[i] = -s / gain; for (int j = 2; j <= i / 2 + 1; ++j) { double at = a[j] + rc[i] * a[i - j + 2]; a[i - j + 2] += rc[i] * a[j]; a[j] = at; } a[i + 1] = rc[i]; gain += rc[i] * s; if (gain <= 0) { goto end; } } end: std::vector<double> lpc(m); i--; for (int j = 1; j <= i; ++j) { lpc[j - 1] = a[j + 1]; } for (int j = i; j < m; ++j) { lpc[j] = 0.0f; } *pGain = gain; return lpc; }
18.84058
93
0.348462
dequis
7e396efbcf5ec6137688f111ce93013d80bdd822
232
cpp
C++
tests/operations/flow_global/RegulatorAdj.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
tests/operations/flow_global/RegulatorAdj.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
tests/operations/flow_global/RegulatorAdj.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "Catch/single_include/catch2/catch.hpp" #include "sgpl/operations/flow_global/RegulatorAdj.hpp" TEST_CASE("Test RegulatorAdj") { // TODO flesh out stub test sgpl::global::RegulatorAdj{}; }
19.333333
55
0.762931
amlalejini
7e3d2df6ca477f2f89dca6b6487b8f6ba9d71e03
4,710
cpp
C++
src/simulation/architecture/asio/visMessageInterface/boost_communication.cpp
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
null
null
null
src/simulation/architecture/asio/visMessageInterface/boost_communication.cpp
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
1
2019-03-13T20:52:22.000Z
2019-03-13T20:52:22.000Z
src/simulation/architecture/asio/visMessageInterface/boost_communication.cpp
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
null
null
null
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder 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. */ // // boost_communication.cpp // // #include "boost_communication.h" #include <string> OpenGLIO::OpenGLIO() : ipAddress("127.0.0.1") { this->scSim = SpacecraftSim(); } OpenGLIO::~OpenGLIO() { shutdown(); } void OpenGLIO::setOutputSpacecraft(SpacecraftSim scSim) { this->scSim = scSim; } bool OpenGLIO::initialize() { std::stringstream ss; ss << IP_BASE_PORT; if(!this->server.acceptConnections(this->ipAddress, ss.str())) { return false; } return true; } bool OpenGLIO::shutdown() { if(!this->server.close()) { return false; } return true; } bool OpenGLIO::send() { this->server.setOutboundData(&this->scSim); return true; } bool OpenGLIO::receive(SpacecraftSim *scSim) { SpacecraftSim visualizationData = this->server.getInboundData(); // if(visualizationData.adcsState != temp.adcsState) { // sc->stateRequest = visualizationData.adcsState; // } // if(visualizationData.perturbRates) { // for(size_t i = 0; i < 3; i++) { // scSim->omega[i] = scSim->perturb.initialOmegaDisp * (2.0 * prn_uniform() - 1.0); // } // } // if(visualizationData.controlState != temp.controlState) { // scSim->ctrlState = visualizationData.controlState; // } if(visualizationData.realTimeSpeedUpFactor != scSim->realTimeSpeedUpFactor) { scSim->realTimeSpeedUpFactor = visualizationData.realTimeSpeedUpFactor; } return true; } void OpenGLIO::setIpAddress(std::string ipAddress) { // Maybe check for an excisting connection before allowing ipAddress to be set // or just ensure a graceful transition between connections. this->ipAddress = ipAddress; } BoostCommunication::BoostCommunication() { } BoostCommunication::~BoostCommunication() { } bool BoostCommunication::initializeAll(std::string tmpDataVariable) { // if(scSim->useOpenGLVisualization && scSim->codeBehavior != CODE_FSW) { // if(!m_openGLIO.initialize(scSim)) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // } // switch(scSim->codeBehavior) { // case CODE_REALITY: // case CODE_REALITY_ON_DEMAND: // printf("codeBehavior: REALITY"); // if(scSim->codeBehavior == CODE_REALITY_ON_DEMAND) { // printf("_ON_DEMAND"); // } // printf("\nWaiting to connect to FSW or Flatsat Module.\n"); // if(!m_realityCommIO.initialize(scSim)) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // break; // // case CODE_FSW: // printf("codeBehavior: FSW\n"); // if(!m_fswCommIO.initialize(scSim)) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // break; // // case CODE_STANDALONE: // printf("codeBehavior: STAND_ALONE\n"); // break; // // default: // break; // } return true; } bool BoostCommunication::shutdownAll(std::string tmpDataVariable) { // if(scSim->codeBehavior == CODE_REALITY || scSim->codeBehavior == CODE_REALITY_ON_DEMAND) { // if(!m_realityCommIO.shutdown()) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // } // if(scSim->codeBehavior == CODE_FSW) { // if(!m_fswCommIO.shutdown()) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // } // if(scSim->useOpenGLVisualization && scSim->codeBehavior != CODE_FSW) { // if(!m_openGLIO.shutdown()) { // std::cout << "called by " << __FUNCTION__ << std::endl; // return false; // } // } return true; }
27.869822
96
0.616561
ian-cooke
7e3fcda429c2b500a22fb361bfcdbd774bc2878c
2,152
cxx
C++
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/**********************************************************************************************/ /* */ /* Abstract class for matrix used for */ /* millepede2 operation. */ /* Works for expandable square matrices */ /* of arbitrary dimension */ /* Author: ruben.shahoyan@cern.ch */ /* */ /* */ /**********************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> // #include "TClass.h" #include "TMath.h" #include "AliMatrixSq.h" // ClassImp(AliMatrixSq) AliMatrixSq & AliMatrixSq::operator=(const AliMatrixSq &src) { // = operator if (this == &src) return *this; TMatrixDBase::operator=(src); fSymmetric = src.fSymmetric; return *this; } //___________________________________________________________ void AliMatrixSq::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const { // fill vecOut by matrix*vecIn // vector should be of the same size as the matrix for (int i=GetSize();i--;) { vecOut[i] = 0.0; for (int j=GetSize();j--;) vecOut[i] += vecIn[j]*(*this)(i,j); } // } //___________________________________________________________ void AliMatrixSq::PrintCOO() const { // print matrix in COO sparse format // // get number of non-zero elements int nnz = 0; int sz = GetSize(); for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if (Query(ir,ic)!=0) nnz++; // printf("%d %d %d\n",sz,sz,nnz); double vl; for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if ((vl=Query(ir,ic))!=0) printf("%d %d %f\n",ir,ic,vl); // }
36.474576
110
0.416822
AllaMaevskaya
7e40272a65b220d2f28ce34196ff3a7edd152cd9
84
hpp
C++
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
1
2019-09-28T09:40:08.000Z
2019-09-28T09:40:08.000Z
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
null
null
null
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
null
null
null
#ifndef SQRTCONSTEXPR_HPP #define SQRTCONSTEXPR_HPP #endif // SQRTCONSTEXPR_HPP
12
27
0.809524
colorhistory
7e449e6721530dfa8add56ead774ea0bc2368cb7
709
hpp
C++
core/es/system/string/internal/Cpp11StringConverter.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
null
null
null
core/es/system/string/internal/Cpp11StringConverter.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
1
2016-10-25T02:09:00.000Z
2016-11-10T02:07:59.000Z
core/es/system/string/internal/Cpp11StringConverter.hpp
eaglesakura/protoground
2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6
[ "MIT" ]
null
null
null
#pragma once #include "es/system/string/IStringConverter.h" #if defined(BUILD_MacOSX) #include <codecvt> #include <locale> namespace es { namespace internal { class Cpp11StringConverter : public IStringConverter { public: Cpp11StringConverter() = default; virtual ~Cpp11StringConverter() = default; /** * UTF8文字列をワイド文字列に変換する */ virtual wide_string toWideString(const std::string &utf8) override { return conversion.from_bytes(utf8); } virtual string toUtf8String(const wide_string &wide) override { return conversion.to_bytes(wide); } private: std::wstring_convert<std::codecvt_utf8_utf16<wide_char>, wide_char> conversion; }; } } #endif
18.179487
83
0.70945
eaglesakura
7e47159978a9d855cd0a1073c96d95261b08f5d0
4,830
cpp
C++
software/src/unball/strategy/strategy_node.cpp
unball/ieee-very-small
972758e03be24c5d7c9276e269e3f145e68c8dd1
[ "MIT" ]
5
2015-04-05T01:25:45.000Z
2021-07-22T20:08:05.000Z
software/src/unball/strategy/strategy_node.cpp
unball/ieee-very-small
972758e03be24c5d7c9276e269e3f145e68c8dd1
[ "MIT" ]
50
2015-02-27T13:21:05.000Z
2016-01-11T01:03:42.000Z
software/src/unball/strategy/strategy_node.cpp
unball/ieee-very-small
972758e03be24c5d7c9276e269e3f145e68c8dd1
[ "MIT" ]
4
2015-10-26T21:11:21.000Z
2016-08-29T02:43:35.000Z
/** * @file strategy_node.cpp * @author Matheus Vieira Portela * @date 21/03/2014 * * @attention Copyright (C) 2014 UnBall Robot Soccer Team * * @brief Run strategy for robots * * This node subscribes to the vision topic, applies strategy to decide robots linear and angular velocities, and * publishes to the strategy topic. */ #include <vector> #include <ros/ros.h> #include <unball/MeasurementSystemMessage.h> #include <unball/StrategyMessage.h> #include <unball/KeyboardMessage.h> #include <unball/strategy/strategy.hpp> // Strategy strategy; #include <unball/strategy/robot.hpp> // Robot robot[6]; #include <unball/strategy/ball.hpp> // Ball ball; #include <unball/strategy/goals.hpp> // Goals goals; void initRobotsPoses(); void publishRobotsVelocities(ros::Publisher &publisher); void receiveMeasurementSystemMessage(const unball::MeasurementSystemMessage::ConstPtr &msg); void receiveKeyboardMessage(const unball::KeyboardMessage::ConstPtr &msg); int main(int argc, char **argv) { ros::init(argc, argv, "strategy_node"); ros::NodeHandle n; ros::Rate loop_rate(30); // Hz ros::Subscriber sub = n.subscribe("measurement_system_topic", 1, receiveMeasurementSystemMessage); ros::Subscriber sub2 = n.subscribe("keyboard_topic", 1, receiveKeyboardMessage); ros::Publisher publisher = n.advertise<unball::StrategyMessage>("strategy_topic", 1); initRobotsPoses(); while (ros::ok()) { strategy.run(); publishRobotsVelocities(publisher); ros::spinOnce(); loop_rate.sleep(); } return 0; } /** * Initialize robots poses with the simulation hardcoded poses. * * This is done in order to prevent errors in the first evaluated action, which may calculate travelled distance from * the last iteration. * * For example: if a robot is set to move for 0.20 m, its initial position is (0, 0) and it is spawn at (0.3, 0), the * method will calculate a travelled distance of 0.30 m and return, even though its real travelled distance so far is 0! */ void initRobotsPoses() { float x[6] = {0.37, 0.37, 0.60, -0.37, -0.37, -0.60}; float y[6] = {0.40, -0.40, 0.0, 0.40, -0.40, 0.0}; for (int i = 0; i < 6; ++i) robot[i].setPose(x[i], y[i], 0.0); // Initial theta is 0 } /** * Publishes the robots velocities to the strategy topic. * @param publisher a ROS node publisher. */ void publishRobotsVelocities(ros::Publisher &publisher) { unball::StrategyMessage msg; ROS_DEBUG("Publishing strategy message"); for (int i = 0; i < 6; i++) { msg.lin_vel[i] = robot[i].getLinVel(); //msg.ang_vel[i] = robot[i].getAngVel(); msg.ang_vel[i] = robot[i].getAngVel(); ROS_DEBUG("lin_vel: %f\t ang_vel: %f", msg.lin_vel[i], msg.ang_vel[i]); } publisher.publish(msg); } float getAngularVel(int i) { float K = 1; float distance_x = Ball::getInstance().getX() - robot[i].getX(); float distance_y = Ball::getInstance().getY() - robot[i].getY(); float angle_to_ball = atan2(distance_y,distance_x); return K*(robot[i].getTh() - angle_to_ball); } /** * Receives the robots locations from the vision topic. * @param msg an UnBall vision message pointer. */ void receiveMeasurementSystemMessage(const unball::MeasurementSystemMessage::ConstPtr &msg) { //ROS_INF)O("\n\n[StrategyNode]:ReceiveMeasuermentSystemMessage - Receiving measurement system message"); for (int i = 0; i < 6; i++) { //ROS_INFO("Robots: %d x: %f\t y: %f\t th: %f", i, msg->x[i], msg->y[i], msg->th[i]); robot[i].setPose(msg->x[i], msg->y[i], msg->th[i]); } //ROS_INFO("Ball: x: %f, y: %f", msg->ball_x, msg->ball_y); if (msg->y[2] < -0.75 or msg->y[2] > 0.75 or msg->x[2] < -0.65 or msg->x[2] > 0.65) { //HACK: in case we do not find our goakeeper, we set our goal by: //finding the opponent goalkeeper //sending the negative of its x position to the function setGoalkeeperSide //this way we find which is our goal, and therefore which goal we should target //only meant to happen on a penalty int opponent_goalkeeper_number = Goals::getInstance().findOpponentGoalkeeper(); Goals::getInstance().setGoalkeeperSide(-robot[opponent_goalkeeper_number].getY()); } else { Goals::getInstance().setGoalkeeperSide(robot[2].getY()); } Ball::getInstance().update(msg->ball_y, -msg->ball_x); } /** * Receives a key from the keyboard topic. * @param msg a keyboard message pointer. */ void receiveKeyboardMessage(const unball::KeyboardMessage::ConstPtr &msg) { ROS_ERROR("Received key: %c", msg->key); Strategy::getInstance().receiveKeyboardInput(msg->key); strategy.receiveKeyboardInput(msg->key); }
33.082192
120
0.662112
unball
7e474d87bc3a52224ba71480f276ad923a2f697e
7,686
hxx
C++
main/sw/inc/anchoreddrawobject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/inc/anchoreddrawobject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/inc/anchoreddrawobject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ #ifndef _ANCHOREDDRAWOBJECT_HXX #define _ANCHOREDDRAWOBJECT_HXX #include <anchoredobject.hxx> #include <tools/gen.hxx> /** class for the positioning of drawing objects OD 2004-03-25 #i26791# @author OD */ class SW_DLLPUBLIC SwAnchoredDrawObject : public SwAnchoredObject { private: // boolean, indicating that the object position has been invalidated // and that a positioning has to be performed. bool mbValidPos; // rectangle, keeping the last object rectangle after the postioning // --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer Rectangle* mpLastObjRect; // boolean, indicating that anchored drawing object hasn't been attached // to a anchor frame yet. Once, it is attached to a anchor frame the // boolean changes its state. bool mbNotYetAttachedToAnchorFrame; // --> OD 2004-08-09 #i28749# - boolean, indicating that anchored // drawing object hasn't been positioned yet. Once, it's positioned the // boolean changes its state. bool mbNotYetPositioned; // --> OD 2006-03-17 #i62875# // boolean, indicating that after change of layout direction the // anchored drawing object has to be captured on the page, if it exceeds // the left or right page margin. // Needed for compatibility option <DoNotCaptureDrawObjsOnPage> bool mbCaptureAfterLayoutDirChange; // <-- /** method for the intrinsic positioning of a at-paragraph|at-character anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtPara(); /** method for the intrinsic positioning of a at-page|at-frame anchored drawing object OD 2004-08-12 #i32795# - helper method for method <MakeObjPos> @author OD */ void _MakeObjPosAnchoredAtLayout(); /** method to set positioning attributes (not for as-character anchored) OD 2004-10-20 #i35798# During load the positioning attributes aren't set. Thus, the positioning attributes are set by the current object geometry. This method is also used for the conversion for drawing objects (not anchored as-character) imported from OpenOffice.org file format once and directly before the first positioning. @author OD */ void _SetPositioningAttr(); /** method to set internal anchor position of <SdrObject> instance of the drawing object For drawing objects the internal anchor position of the <SdrObject> instance has to be set. Note: This adjustment is not be done for as-character anchored drawing object - the positioning code takes care of this. OD 2004-07-29 #i31698# - API for drawing objects in Writer has been adjusted. Thus, this method will only set the internal anchor position of the <SdrObject> instance to the anchor position given by its anchor frame. @author OD */ void _SetDrawObjAnchor(); /** method to invalidate the given page frame OD 2004-07-02 #i28701# @author OD */ void _InvalidatePage( SwPageFrm* _pPageFrm ); protected: virtual void ObjectAttachedToAnchorFrame(); /** method to assure that anchored object is registered at the correct page frame OD 2004-07-02 #i28701# @author OD */ virtual void RegisterAtCorrectPage(); // --> OD 2006-08-10 #i68520# virtual bool _SetObjTop( const SwTwips _nTop); virtual bool _SetObjLeft( const SwTwips _nLeft); // <-- // --> OD 2006-10-05 #i70122# virtual const SwRect GetObjBoundRect() const; // <-- public: TYPEINFO(); SwAnchoredDrawObject(); virtual ~SwAnchoredDrawObject(); // declaration of pure virtual methods of base class <SwAnchoredObject> virtual void MakeObjPos(); virtual void InvalidateObjPos(); inline bool IsValidPos() const { return mbValidPos; } // accessors to the format virtual SwFrmFmt& GetFrmFmt(); virtual const SwFrmFmt& GetFrmFmt() const; // accessors to the object area and its position virtual const SwRect GetObjRect() const; // --> OD 2004-09-29 #i34748# - change return type to a pointer. // Return value can be NULL. const Rectangle* GetLastObjRect() const; // <-- // --> OD 2004-09-29 #i34748# - change method void SetLastObjRect( const Rectangle& _rNewObjRect ); // <-- /** adjust positioning and alignment attributes for new anchor frame OD 2004-04-21 Set horizontal and vertical position/alignment to manual position relative to anchor frame area using the anchor position of the new anchor frame and the current absolute drawing object position. Note: For correct Undo/Redo method should only be called inside a Undo-/Redo-action. OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect> @author OD @param <_pNewAnchorFrm> input parameter - new anchor frame for the anchored object. @param <_pNewObjRect> optional input parameter - proposed new object rectangle. If not provided the current object rectangle is taken. */ void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm, const SwRect* _pNewObjRect = 0L ); /** method to notify background of drawing object OD 2004-06-30 #i28701# @author OD */ virtual void NotifyBackground( SwPageFrm* _pPageFrm, const SwRect& _rRect, PrepareHint _eHint ); // --> OD 2005-08-16 #i53320# inline bool NotYetPositioned() const { return mbNotYetPositioned; } // <-- // --> OD 2006-03-17 #i62875# // change of layout direction needs to be tracked // for setting <mbCaptureAfterLayoutDirChange>. virtual void UpdateLayoutDir(); // <-- // --> OD 2006-03-17 #i62875# bool IsOutsidePage() const; // <-- // new Loop control void ValidateThis() { mbValidPos = true; } }; #endif
34.936364
84
0.60981
Grosskopf
7e4cf839ec626c68ac4dcd037d21183a2e16d7b1
573
cpp
C++
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
#include <toy_compiler/munster/ast/stmt/compound_stmt.hpp> #include <toy_compiler/munster/ast/utility.hpp> namespace munster::ast { compound_stmt::compound_stmt(std::vector<node_ptr>&& statements) { make_family<stmt>(std::move(statements)); } void compound_stmt::accept(visitor_variant& visitor) const { for (const auto& child : children()) { child->accept(visitor); } visit_node(visitor, *this); } auto compound_stmt::to_string() const -> std::string { return "compound_stmt"; } } // namespace munster::ast
23.875
83
0.670157
Wmbat
7e5a18f46883b774602c845cb7b711df0457a7d7
42,777
hpp
C++
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* ScaFES * Copyright (c) 2011-2015, ZIH, TU Dresden, Federal Republic of Germany. * For details, see the files COPYING and LICENSE in the base directory * of the package. */ /** * @file ScaFES_Grid.hpp * @brief Contains the class template Grid. */ #ifndef SCAFES_GRID_HPP_ #define SCAFES_GRID_HPP_ #include "ScaFES_Config.hpp" #include <iterator> #include <vector> #ifdef SCAFES_HAVE_BOOST #include <boost/version.hpp> #endif #ifdef SCAFES_HAVE_BOOST_SERIALIZATION // Forward declaration. namespace boost { namespace serialization { class access; } } #include <boost/serialization/version.hpp> #if BOOST_VERSION < 105900 #include <boost/serialization/pfto.hpp> #endif #include <boost/serialization/vector.hpp> #include <boost/config/suffix.hpp> #endif #include "ScaFES_Ntuple.hpp" #include "ScaFES_Ntuple_FreeFunctions.hpp" namespace ScaFES { /******************************************************************************* ******************************************************************************/ /** * \class Grid * @brief The class template \c Grid represents a structured grid * of dimension \c DIM, where \c DIM is the template parameter of the class * template. A grid is a \c DIM - dimensional hypercuboid. * * The grid nodes are numbered in two different ways: * <ul> * <li> globally, i.e. all grid nodes of the WHOLE MPI domain are numbered * lexicographically, </li> * <li> locally, i.e. all grid nodes of ONE MPI partition are numbered * lexicographically. </li> * </ul> * * As the nodes of the grid are lexicographically numbered, the first and * the last node number of the grid together with its corresponding coordinates * have to be stored, only. * * Due to the lexicographical node numbering, the coordinates of all nodes * can be easily computed. For this purpose, the method \c coordinates() was * provided. * * Furthermore, the class contains an iterator class. As the iterator is * designed like an STL iterator, it can be applied completely analogously. * The most important components of the inner class \c Iterator are the member * methods \c idxNode() and \c idxScalarNode(). The first one returns * the current node number in tuple notation, the second on returns * the current node number as a scalar number. * * Numbering of grid nodes for DIM = 3 of a grid with n^3 nodes: * Gap in y-direction: n (1, n+1, 2*n+1, 3*n+1,...) * Gap in z-direction: n^2 (n^2, 2*n^2, 3*n^2,....) * *-----------------* n^3 * / /| * / / | * / / | * / (n-1)*n^2+n / | * *----------------* | * | | * n^2 * | | / * | | / * | | / * | |/ * 1 *----------------* n * * \n Numbering of grid faces for DIM = 3: * ^ ^ * | / Back = 3 * | Top = 4/ * / * *-----------------* * / /| * / / | * / / | * / / | * *-----------------* | * | | * * <------ | | / -------> * Left=1 | | / Right = 0 * | | / * | |/ * *-----------------* * Right: direction = 0 * Left: direction = 1 | Bottom = 5 * Top: direction = 2 | * Bottom: direction = 3 | * Front: direction = 4 v * Back: direction = 5 */ template <std::size_t DIM = 3> class Grid { public: /*---------------------------------------------------------------------- | INTERNAL CLASSES. ----------------------------------------------------------------------*/ /** Class for iterating through the grid.*/ class Iterator : public std::iterator<std::random_access_iterator_tag, ScaFES::Ntuple<int, DIM>> { public: /*-------------------------------------------------------------- | LIFE CYCLE METHODS. --------------------------------------------------------------*/ /** Creates own constructor. * \param gridIter Given grid over which will be iterated. * \param idxNode Iteration will start from this node. */ Iterator(const Grid<DIM>* gridIter, const ScaFES::Ntuple<int, DIM>& idxNode); /*-------------------------------------------------------------- | GETTER METHODS. --------------------------------------------------------------*/ /** Returns the index of the current node. */ const ScaFES::Ntuple<int, DIM>& idxNode() const; /** Returns the scalar index of the current node. */ const unsigned long int& idxScalarNode() const; /*-------------------------------------------------------------- | COMPARISON METHODS. --------------------------------------------------------------*/ /** Checks if the local node number of this iterator is unequal * to the one of the given iterator. */ bool operator!=(const Iterator& other) const; /** Checks if the local node number of this iterator is smaller * than the one of the given iterator. */ bool operator<(const Iterator& other) const; /*-------------------------------------------------------------- | WORK METHODS. --------------------------------------------------------------*/ /** Returns the index of the current node. */ const ScaFES::Ntuple<int, DIM>& operator*(); /** Increases the current local and the current global * node number. * \remarks Prefix variant. */ Iterator& operator++(); /** Increases the current local and the current global * node number. * \remarks Postfix variant. */ Iterator operator++(int /*incr*/); private: /*-------------------------------------------------------------- | MEMBER VARIABLES. --------------------------------------------------------------*/ /** Grid over which should be iterated. */ const Grid<DIM>* mGridIter; /** Index of current node. */ ScaFES::Ntuple<int, DIM> mIdxNode; /** Scalar index of current node. */ unsigned long int mIdxScalarNode; /*-------------------------------------------------------------- | INTERNAL WORK METHODS. --------------------------------------------------------------*/ /** Increases the current local and the current global node * number iterating "columnwise" through the grid. */ Iterator& nextStyleC(); /** Increases the current local and the current global node * number iterating "rowwise" through the grid. */ Iterator& nextStyleFortran(); /*-------------------------------------------------------------- | FRIEND CLASSES. --------------------------------------------------------------*/ friend class Grid<DIM>; }; /*---------------------------------------------------------------------- | TYPE DEFINITIONS. ----------------------------------------------------------------------*/ /** Type definition for iterator class analogously to STL class. */ typedef Iterator iterator; /** Type definition for iterator class analogously to STL class. */ typedef const Iterator const_iterator; /** Type definition for iterator class analogously to STL class. */ typedef ScaFES::Ntuple<int, DIM>& reference_type; /*---------------------------------------------------------------------- | FRIEND CLASSES. ----------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION friend class boost::serialization::access; #endif /*---------------------------------------------------------------------- | LIFE CYCLE METHODS. ----------------------------------------------------------------------*/ /** Creates the default constructor. */ Grid(); /** Creates a new grid with given first global node number and * given last global node together with its corresponding coordinates. * TODO: Reason for pass-by-value of coordinates?! [KF], 2015-11-17 * \param idxNodeFirst Index of first node. * \param idxNodeLast Index of last node. * \param coordNodeFirst Coordinates of first node. * \param coordNodeLast Coordinates of last node. */ Grid(const ScaFES::Ntuple<int, DIM>& idxNodeFirst, const ScaFES::Ntuple<int, DIM>& idxNodeLast, ScaFES::Ntuple<double, DIM> coordNodeFirst, ScaFES::Ntuple<double, DIM> coordNodeLast); /** Creates own copy constructor. */ Grid(const Grid<DIM>& rhs); /** Creates own assignment operator using the copy-and-swap idiom. */ Grid& operator=(Grid<DIM> rhs); /** Creates own destructor. */ ~Grid(); /*---------------------------------------------------------------------- | GETTER METHODS. ----------------------------------------------------------------------*/ /** Returns the dimension of the grid. */ std::size_t dimGrid() const; /** Returns the index of the first node. */ const ScaFES::Ntuple<int, DIM>& idxNodeFirst() const; /** Returns the component \c idx of the index of the first node. */ const int& idxNodeFirst(const int& idx) const; /** Returns the index of the last node. */ const ScaFES::Ntuple<int, DIM>& idxNodeLast() const; /** Returns the component \c idx of the index of the last node. */ const int& idxNodeLast(const int& idx) const; /** Returns the number of nodes of the grid in each direction. */ const ScaFES::Ntuple<int, DIM>& nNodes() const; /** Returns the number of nodes of the grid in one given direction. */ const int& nNodes(const int& idx) const; /** Returns the total number of nodes of the grid. */ int nNodesTotal() const; /** Returns the coordinates of the first node. */ const ScaFES::Ntuple<double, DIM>& coordNodeFirst() const; /** Returns the coordinates of the last node. */ const ScaFES::Ntuple<double, DIM>& coordNodeLast() const; /** Returns the grid size in all directions. */ const ScaFES::Ntuple<double, DIM>& gridsize() const; /** Returns the grid size in one given direction. */ const double& gridsize(const int& idx) const; /** Returns if the grid is numbered in C style notation. */ const bool& isNumberedStyleC() const; /*---------------------------------------------------------------------- | COMPARISON METHODS. ----------------------------------------------------------------------*/ /** Tests if two grids are equal. */ bool operator==(const Grid<DIM>& rhs) const; /** Tests if two grids are not equal. */ bool operator!=(const Grid<DIM>& rhs) const; /*---------------------------------------------------------------------- | WORK METHODS. ----------------------------------------------------------------------*/ /** Returns an iterator which will start with the first node of the * underlying grid. */ iterator begin() const; /** Returns an iterator which will start with the last node of the * underlying grid. */ iterator end() const; /** Computes the corresponding scalar node number of a given node number * of the grid. * \param idxNode ScaFES::Ntuple<int,DIM> of a given node. */ unsigned long int idxNodeTuple2Scalar(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given node number * of the grid. * \param idxNodeScalar Scalar index of a given node. * \param idxNode ScaFES::Ntuple<int,DIM> of a given node. */ void idxNodeTuple2Scalar(unsigned long int& idxNodeScalar, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding node number from a given scalar * node number. * \param idxScalarNode Scalar index of a given node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2Tuple(const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number from a given scalar * node number. * \param idxNode ScaFES::Ntuple<int,DIM> tuple of a given node. * \param idxScalarNode Scalar index of a given node number. */ void idxNodeScalar2Tuple(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; /** Computes the coordinates of a given node number of the grid. * \param idxNode Given node number */ ScaFES::Ntuple<double, DIM> coordinates(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Returns true if the first node number is equal or smaller the * the last node number, i.e. if the grid consists of at * least one node. */ bool valid() const; /** Returns true if a given node number is inside the grid. */ bool inside(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Extends the underlying grid by a given border width into a * given direction and returns the new modified grid. * The coordinates of the extended grid will remain the same as before, * whereas the number of nodes within the same physical domain will * increases. * \param dir Direction to expand. * \param nLayers Number of layers to expand into the given dir. * \remarks The ordering of the direction is as given in the * description of this class. */ Grid<DIM> extend(const int& dir, const int& nLayers); /** Returns the union of this grid and another given grid. * It will be assumed that both grids have the same grid sizes! * \return Grid gg(min(mIdxNodeFirst, rhs.idxNodeFirst), * max(mIdxNodeLast, rhs.idxNodeLast)) */ Grid<DIM> unionWith(const Grid<DIM>& rhs) const; /** Returns the intersection of this grid and another given grid. * It will be assumed that both grids have the same grid sizes! * \return Grid gg(max(mIdxNodeFirst, rhs.idxNodeFirst), * min(mIdxNodeLast, rhs.idxNodeLast)) */ Grid<DIM> intersectWith(const Grid<DIM>& rhs) const; #ifdef SCAFES_HAVE_BOOST_SERIALIZATION /** Serializes the class. */ template <class Archive> void serialize(Archive& ar, const unsigned int version); #endif /** Returns all direct neighboured LOCAL node numbers * of a given node number. */ Ntuple<unsigned long int, 2 * DIM> connect(const ScaFES::Ntuple<int, DIM>& idxNode); /** Determines the neighbour global node into a given direction * of a global node number. */ ScaFES::Ntuple<int, DIM> neigh(const ScaFES::Ntuple<int, DIM>& idxNode, const int& dir) const; /*---------------------------------------------------------------------- | FREE METHODS. ----------------------------------------------------------------------*/ /** Swaps the members of two grids. */ template <std::size_t SS> friend void swap(ScaFES::Grid<SS>& first, ScaFES::Grid<SS>& second); /** Overloads the output operator. */ template <std::size_t SS> friend std::ostream& operator<<(std::ostream& output, const ScaFES::Grid<SS>& rhs); protected: /*---------------------------------------------------------------------- | MEMBER VARIABLES. ----------------------------------------------------------------------*/ /** First node number of the grid. */ ScaFES::Ntuple<int, DIM> mIdxNodeFirst; /** Last node number of the grid. */ ScaFES::Ntuple<int, DIM> mIdxNodeLast; /** Number of nodes of the grid in all directions. */ ScaFES::Ntuple<int, DIM> mNnodes; /** Coordinate of the first node number. */ ScaFES::Ntuple<double, DIM> mCoordNodeFirst; /** Coordinate of the last node number. */ ScaFES::Ntuple<double, DIM> mCoordNodeLast; /** Grid size in all directions. */ ScaFES::Ntuple<double, DIM> mGridsize; /** Is grid numbered in C style notation (alternative: FORTRAN style).*/ bool mIsNumberedStyleC; private: /*---------------------------------------------------------------------- | INTERNAL METHODS. ----------------------------------------------------------------------*/ /** Computes the corresponding scalar node number of a given * node number of the grid using the C style. * \param idxNode Given node number */ unsigned long int idxNodeTuple2ScalarStyleC(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the C style. * \param idxScalarNode Corresponding scalar node number (return value). * \param idxNode Given node number. */ void idxNodeTuple2ScalarStyleC(unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the FORTRAN style. * \param idxNode Given node number. * \return Corresponding scalar node number. */ unsigned long int idxNodeTuple2ScalarStyleFortran( const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the FORTRAN style. * \param idxScalarNode Corresponding scalar node number (return value). * \param idxNode Given node number. */ void idxNodeTuple2ScalarStyleFortran( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the C style. * \param idxScalarNode Given scalar node number * \return Corresponding node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2TupleStyleC(const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the C style. * \param idxNode Corresponding node number (return value). * \param idxScalarNode Given scalar node number */ void idxNodeScalar2TupleStyleC(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the Fortran style. * \param idxScalarNode Given scalar node number. * \return Corresponding node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2TupleStyleFortran( const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the Fortran style. * \param idxNode Corresponding node number (return value). * \param idxScalarNode Given scalar node number. */ void idxNodeScalar2TupleStyleFortran(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; }; // End of class. // /******************************************************************************* * FREE METHODS. ******************************************************************************/ /** Swaps two objects of the class \c Grid. */ template <std::size_t DIM> void swap(ScaFES::Grid<DIM>& first, ScaFES::Grid<DIM>& second); /*----------------------------------------------------------------------------*/ /** Preprares writing an object of the class \c Grid to output. */ template <std::size_t DIM> std::ostream& operator<<(std::ostream& output, const ScaFES::Grid<DIM>& gg); /******************************************************************************* * LIFE CYCLE METHODS. ******************************************************************************/ template <std::size_t DIM> inline Grid<DIM>::Grid() : mIdxNodeFirst(0), mIdxNodeLast(1), mNnodes(2), mCoordNodeFirst(0.0), mCoordNodeLast(1.0), mGridsize(1.0), mIsNumberedStyleC(false) { } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::Grid(const ScaFES::Ntuple<int, DIM>& idxNodeFirst, const ScaFES::Ntuple<int, DIM>& idxNodeLast, ScaFES::Ntuple<double, DIM> coordNodeFirst, ScaFES::Ntuple<double, DIM> coordNodeLast) : mIdxNodeFirst(idxNodeFirst), mIdxNodeLast(idxNodeLast), mNnodes(idxNodeLast - idxNodeFirst + ScaFES::Ntuple<int, DIM>(1)), mCoordNodeFirst(coordNodeFirst), mCoordNodeLast(coordNodeLast), mGridsize(), mIsNumberedStyleC(false) { if (0 < this->nNodes().size()) { for (std::size_t ii = 0; ii < DIM; ++ii) { this->mGridsize[ii] = (coordNodeLast.elem(ii) - coordNodeFirst.elem(ii)) / (this->nNodes().elem(ii) - 1); } } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::Grid(const Grid<DIM>& from) : mIdxNodeFirst(from.idxNodeFirst()), mIdxNodeLast(from.idxNodeLast()), mNnodes(from.nNodes()), mCoordNodeFirst(from.coordNodeFirst()), mCoordNodeLast(from.coordNodeLast()), mGridsize(from.gridsize()), mIsNumberedStyleC(from.isNumberedStyleC()) { } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>& Grid<DIM>::operator=(Grid<DIM> rhs) { ScaFES::swap(*this, rhs); return *this; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::~Grid() { } /******************************************************************************* * GETTER METHODS. ******************************************************************************/ template <std::size_t DIM> inline std::size_t Grid<DIM>::dimGrid() const { return DIM; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::idxNodeFirst() const { return this->mIdxNodeFirst; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::idxNodeFirst(const int& idx) const { return this->mIdxNodeFirst.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::idxNodeLast() const { return this->mIdxNodeLast; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::idxNodeLast(const int& idx) const { return this->mIdxNodeLast.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::nNodes() const { return this->mNnodes; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::nNodes(const int& idx) const { return this->mNnodes.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline int Grid<DIM>::nNodesTotal() const { return this->mNnodes.size(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::coordNodeFirst() const { return this->mCoordNodeFirst; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::coordNodeLast() const { return this->mCoordNodeLast; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::gridsize() const { return this->mGridsize; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const double& Grid<DIM>::gridsize(const int& ii) const { return this->mGridsize.elem(ii); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const bool& Grid<DIM>::isNumberedStyleC() const { return this->mIsNumberedStyleC; } /******************************************************************************* * WORK METHODS. ******************************************************************************/ template <std::size_t DIM> inline typename Grid<DIM>::iterator Grid<DIM>::begin() const { return iterator(this, this->mIdxNodeFirst); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::iterator Grid<DIM>::end() const { return iterator(this, this->mIdxNodeLast); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2Scalar(const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2Scalar(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2Scalar(unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { if (this->mIsNumberedStyleC) { this->idxNodeTuple2ScalarStyleC(idxScalarNode, idxNode); } else { this->idxNodeTuple2ScalarStyleFortran(idxScalarNode, idxNode); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2Tuple(const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2Tuple(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2Tuple(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { if (this->mIsNumberedStyleC) { this->idxNodeScalar2TupleStyleC(idxNode, idxScalarNode); } else { this->idxNodeScalar2TupleStyleFortran(idxNode, idxScalarNode); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<double, DIM> Grid<DIM>::coordinates(const ScaFES::Ntuple<int, DIM>& idxNode) const { ScaFES::Ntuple<double, DIM> coord(0.0); for (std::size_t ii = 0; ii < DIM; ++ii) { coord[ii] = this->coordNodeFirst().elem(ii) + this->gridsize(ii) * (idxNode.elem(ii) - this->idxNodeFirst().elem(ii)); } return coord; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::valid() const { return (this->mIdxNodeFirst <= this->mIdxNodeLast); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::inside(const ScaFES::Ntuple<int, DIM>& idxNode) const { return ((this->mIdxNodeFirst <= idxNode) && (idxNode <= this->mIdxNodeLast)); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::extend(const int& dir, const int& nLayers) { ScaFES::Ntuple<int, DIM> idxNodeFirst(this->mIdxNodeFirst); ScaFES::Ntuple<int, DIM> idxNodeLast(this->mIdxNodeLast); int idx = dir / 2; if (0 == (dir % 2)) { idxNodeLast[idx] += nLayers; } else { idxNodeFirst[idx] -= nLayers; } return Grid<DIM>(idxNodeFirst, idxNodeLast, this->coordNodeFirst(), this->coordNodeLast()); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::unionWith(const Grid<DIM>& rhs) const { ScaFES::Ntuple<double, DIM> coordNodeFirstNew; ScaFES::Ntuple<double, DIM> coordNodeLastNew; ScaFES::Ntuple<int, DIM> idxNodeFirstNew = ScaFES::min(idxNodeFirst(), rhs.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeLastNew = ScaFES::max(idxNodeLast(), rhs.idxNodeLast()); if (idxNodeFirstNew == this->idxNodeFirst()) { coordNodeFirstNew = this->coordNodeFirst(); } else { coordNodeFirstNew = rhs.coordNodeFirst(); } if (idxNodeLastNew == this->idxNodeLast()) { coordNodeLastNew = this->coordNodeLast(); } else { coordNodeLastNew = rhs.coordNodeLast(); } return ScaFES::Grid<DIM>(idxNodeFirstNew, idxNodeLastNew, coordNodeFirstNew, coordNodeLastNew); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::intersectWith(const Grid<DIM>& rhs) const { ScaFES::Ntuple<double, DIM> coordNodeFirstNew; ScaFES::Ntuple<double, DIM> coordNodeLastNew; ScaFES::Ntuple<int, DIM> idxNodeFirstNew = ScaFES::max(this->idxNodeFirst(), rhs.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeLastNew = ScaFES::min(this->idxNodeLast(), rhs.idxNodeLast()); if (idxNodeFirstNew == this->idxNodeFirst()) { coordNodeFirstNew = this->coordNodeFirst(); } else { coordNodeFirstNew = rhs.coordNodeFirst(); } if (idxNodeLastNew == this->idxNodeLast()) { coordNodeLastNew = this->coordNodeLast(); } else { coordNodeLastNew = rhs.coordNodeLast(); } return ScaFES::Grid<DIM>(idxNodeFirstNew, idxNodeLastNew, coordNodeFirstNew, coordNodeLastNew); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::operator==(const Grid<DIM>& rhs) const { return (this->idxNodeFirst() == rhs.idxNodeFirst() && this->idxNodeLast() == rhs.idxNodeLast()); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::operator!=(const Grid<DIM>& rhs) const { return !(*this == rhs); } /*----------------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION template <std::size_t DIM> template <class Archive> inline void Grid<DIM>::serialize(Archive& ar, const unsigned int version) { if (1 <= version) { ar&(this->mIdxNodeFirst); ar&(this->mIdxNodeLast); ar&(this->mNnodes); ar&(this->mCoordNodeFirst); ar&(this->mCoordNodeLast); ar&(this->mGridsize); ar&(this->mIsNumberedStyleC); } } #endif /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Ntuple<unsigned long int, 2 * DIM> Grid<DIM>::connect(const ScaFES::Ntuple<int, DIM>& idxNode) { // First, set up connectivity for ALL nodes (also for the boundary nodes). // Then, correct the connectivity entries at the boundary nodes. unsigned long int gap; unsigned long int idxScalarNode; ScaFES::Ntuple<unsigned long int, 2 * DIM> neighIdxNode; idxScalarNode = this->idxNodeTuple2Scalar(idxNode); gap = 1; for (std::size_t kk = 0; kk < DIM; ++kk) { neighIdxNode[2 * kk] = idxScalarNode - gap; neighIdxNode[2 * kk + 1] = idxScalarNode + gap; // Adapt boundary of hypercube. if (idxNode.elem(kk) == this->idxNodeFirst(kk)) { neighIdxNode[2 * kk] = -(2 * kk + 1); } else if (idxNode.elem(kk) == this->idxNodeLast(kk)) { neighIdxNode[2 * kk + 1] = -(2 * kk + 2); } gap *= this->nNodes(kk); } return neighIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::neigh(const ScaFES::Ntuple<int, DIM>& idxNode, const int& dir) const { // Adapt boundary of hypercube. ScaFES::Ntuple<int, DIM> neighIdxNode(idxNode); int idx = dir / 2; if (0 == (dir % 2)) { if (idxNode.elem(idx) == this->idxNodeFirst(idx)) { for (std::size_t ii = 0; ii < DIM; ++ii) { neighIdxNode[ii] = -(dir + 1); } } else { --(neighIdxNode[idx]); } } else { if (idxNode.elem(idx) == this->idxNodeLast(idx)) { for (std::size_t ii = 0; ii < DIM; ++ii) { neighIdxNode[ii] = -(dir + 1); } } else { ++(neighIdxNode[idx]); } } return neighIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2ScalarStyleC( const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2ScalarStyleC(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2ScalarStyleC( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { idxScalarNode = idxNode.elem(0) - this->idxNodeFirst(0); for (std::size_t ii = 1; ii < DIM; ++ii) { idxScalarNode = idxScalarNode * this->nNodes(ii) + idxNode.elem(ii) - this->idxNodeFirst(ii); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2ScalarStyleFortran( const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2ScalarStyleFortran(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2ScalarStyleFortran( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { idxScalarNode = idxNode.elem(DIM - 1) - this->idxNodeFirst(DIM - 1); const int dimLocal = DIM; for (int ii = dimLocal - 2; ii >= 0; --ii) { idxScalarNode = idxScalarNode * this->nNodes(ii) + idxNode.elem(ii) - this->idxNodeFirst(ii); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2TupleStyleC( const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2TupleStyleC(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2TupleStyleC( ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { int tmp = idxScalarNode; for (std::size_t ii = DIM - 1; ii > 0; --ii) { idxNode[ii] = (tmp % this->nNodes(ii)) + this->idxNodeFirst(ii); tmp /= (this->nNodes(ii)); } idxNode[0] = tmp; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2TupleStyleFortran( const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2TupleStyleFortran(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2TupleStyleFortran( ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { int tmp = idxScalarNode; for (std::size_t ii = 0; ii < DIM; ++ii) { idxNode[ii] = (tmp % this->nNodes(ii)) + this->idxNodeFirst(ii); tmp /= (this->nNodes(ii)); } } /******************************************************************************* * INLINED OPERATORS (FREE FUNCTIONS) ******************************************************************************/ template <std::size_t DIM> inline void swap(Grid<DIM>& first, Grid<DIM>& second) { ScaFES::swap(first.mIdxNodeFirst, second.mIdxNodeFirst); ScaFES::swap(first.mIdxNodeLast, second.mIdxNodeLast); ScaFES::swap(first.mNnodes, second.mNnodes); ScaFES::swap(first.mCoordNodeFirst, second.mCoordNodeFirst); ScaFES::swap(first.mCoordNodeLast, second.mCoordNodeLast); ScaFES::swap(first.mGridsize, second.mGridsize); std::swap(first.mIsNumberedStyleC, second.mIsNumberedStyleC); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline std::ostream& operator<<(std::ostream& output, const Grid<DIM>& gg) { output << "* GRID:" << std::endl << " -Node First:" << gg.idxNodeFirst() << std::endl << " -Node Last: " << gg.idxNodeLast() << std::endl << " -Coordinates(Node First): " << gg.coordNodeFirst() << std::endl << " -Coordinates(Node Last): " << gg.coordNodeLast() << std::endl; return output; } /******************************************************************************* * INTERNAL CLASS ITERATOR: LIFE CYCLE METHODS. ******************************************************************************/ template <std::size_t DIM> inline Grid<DIM>::Iterator::Iterator(const Grid<DIM>* gridIter, const ScaFES::Ntuple<int, DIM>& idxNode) : mGridIter(gridIter), mIdxNode(idxNode), mIdxScalarNode(gridIter->idxNodeTuple2Scalar(idxNode)) { // TODO: Check if \c idxNode is inside underlying grid. } /******************************************************************************* * INTERNAL CLASS ITERATOR: GETTER METHODS. ******************************************************************************/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::Iterator::idxNode() const { return this->mIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const unsigned long int& Grid<DIM>::Iterator::idxScalarNode() const { return this->mIdxScalarNode; } /******************************************************************************* * INTERNAL CLASS ITERATOR: COMPARISON METHODS. ******************************************************************************/ template <std::size_t DIM> inline bool Grid<DIM>::Iterator::operator!=(const Iterator& other) const { return (*this < other) || (other < *this); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::Iterator::operator<(const Iterator& it) const { return (this->idxScalarNode() <= it.idxScalarNode()); } /******************************************************************************* * INTERNAL CLASS ITERATOR: WORK METHODS. ******************************************************************************/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::Iterator::operator*() { return this->idxNode(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::operator++() { if (this->mGridIter->isNumberedStyleC()) { return this->nextStyleC(); } return this->nextStyleFortran(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator Grid<DIM>::Iterator::operator++(int /*incr*/) { Iterator tmp = *this; ++(*this); return tmp; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::nextStyleC() { ++(this->mIdxScalarNode); ++(this->mIdxNode[DIM - 1]); const int DIM_MINUS_ONE = DIM - 1; for (int ii = DIM_MINUS_ONE; ii > 0; --ii) { if (this->mIdxNode.elem(ii) > this->mGridIter->idxNodeLast(ii)) { this->mIdxNode[ii] = this->mGridIter->idxNodeFirst(ii); ++(this->mIdxNode[ii - 1]); } } return *this; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::nextStyleFortran() { ++(this->mIdxScalarNode); ++(this->mIdxNode[0]); const int DIM_MINUS_ONE = DIM - 1; for (int ii = 0; ii < DIM_MINUS_ONE; ++ii) { if (this->mIdxNode.elem(ii) > this->mGridIter->idxNodeLast(ii)) { this->mIdxNode[ii] = this->mGridIter->idxNodeFirst(ii); ++(this->mIdxNode[ii + 1]); } } return *this; } } // End of namespace. // /******************************************************************************* ******************************************************************************/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION namespace boost { namespace serialization { /** Designed to set the boost serialization version of a class template. */ template <std::size_t DIM> struct version<ScaFES::Grid<DIM>> { /** Sets the version number for serialization. */ BOOST_STATIC_CONSTANT(unsigned long int, value = 2); }; } // namespace serialization } // namespace boost #endif #endif
36.718455
81
0.510648
nih23
7e5a72a3d6d86de773f989ec2c12c786b26f414e
5,312
cc
C++
src/la/mat_dec.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
src/la/mat_dec.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
src/la/mat_dec.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
#include "la/mat_dec.hh" #include "la/functions.hh" Vector solve_lower(const Matrix& m, const Vector& b) { assert(m.rows() == m.cols()); assert(m.rows() == b.size()); std::size_t n = m.rows(); Vector x(n); for (std::size_t k = 0; k < n; ++k) { num_t val = b[k]; for (std::size_t i = 0; i < k; ++i) val -= m(k, i) * x[i]; x[k] = val / m(k, k); } return x; } Vector solve_upper(const Matrix& m, const Vector& b) { assert(m.rows() == m.cols()); assert(m.rows() == b.size()); std::size_t n = m.rows(); Vector x(n); for (std::size_t k = n - 1; k < n; --k) { num_t val = b[k]; for (std::size_t i = k + 1; i < n; ++i) val -= m(k, i) * x[i]; x[k] = val / m(k, k); } return x; } Matrix transpose(const Matrix& m) { Matrix res(m.cols(), m.rows()); for (std::size_t i = 0; i < m.cols(); ++i) for (std::size_t j = 0; j < m.rows(); ++j) res(i, j) = m(j, i); return res; } Matrix inverse(const Matrix& m) { return plu_inverse(m); } bool plu_decomposition(const Matrix& m, Matrix& p, Matrix& l, Matrix& u, std::vector<std::size_t>& pv, bool& even_permuts) { assert(m.rows() == m.cols()); Matrix res = m.copy(); std::size_t n = m.rows(); std::size_t nb_permuts = 0; std::vector<num_t> inv_largest(n); std::vector<std::size_t> permuts(n); for (std::size_t i = 0; i < n; ++i) permuts[i] = i; //Find max element in each row //If max is 0 => rows of 0 => can't decompose for (std::size_t i = 0; i < n; ++i) { num_t max = 0; for (std::size_t j = 0; j < n; ++j) { if (std::abs(res(i, j)) > max) max = std::abs(res(i, j)); } if (max == 0) return false; inv_largest[i] = 1.0 / max; } // decompose collumn b collumn for (std::size_t k = 0; k < n; ++k) { //find max element among of the collumn at or below current collumn //if max is 0 => no pivot => can't decompose num_t max_val = 0; std::size_t max_i = k; for (std::size_t i = k; i < n; ++i) { num_t val = inv_largest[i] * std::abs(res(i, k)); if (val > max_val) { max_val = val; max_i = i; } } if (max_val == 0) { return false; } //Swqp current row with the pivot if (max_i != k) { for (std::size_t j = 0; j < n; ++j) std::swap(res(max_i, j), res(k, j)); std::swap(inv_largest[max_i], inv_largest[k]); std::swap(permuts[max_i], permuts[k]); ++nb_permuts; } for (std::size_t i = k + 1; i < n; ++i) { //Divide all elements in column below the diagonal by the pivot value res(i, k) /= res(k, k); //Apply Gaussian elimination for (std::size_t j = k + 1; j < n; ++j) res(i, j) -= res(i, k) * res(k, j); } } Matrix pout = Matrix::with(n, n, 0); for (std::size_t i = 0; i < n; ++i) pout(i, permuts[i]) = 1; Matrix lout = Matrix::id(n); for (std::size_t i = 0; i < n; ++i) for (std::size_t j = 0; j < i; ++j) lout(i, j) = res(i, j); Matrix uout = Matrix::with(n, n, 0); for (std::size_t i = 0; i < n; ++i) for (std::size_t j = i; j < n; ++j) uout(i, j) = res(i, j); p = pout; l = lout; u = uout; pv = permuts; even_permuts = nb_permuts % 2 == 0; return true; } Vector plu_solve(const Matrix& m, const Vector& b) { assert(m.rows() == m.cols()); assert(m.rows() == b.size()); std::size_t n = m.rows(); Matrix p; Matrix l; Matrix u; std::vector<std::size_t> pv; bool permuts; bool ok = plu_decomposition(m, p, l, u, pv, permuts); if (!ok) return Vector{}; Vector b2(n); for (std::size_t i = 0; i < n; ++i) b2[pv[i]] = b[i]; Vector y = solve_lower(l, b2); Vector x = solve_upper(u, y); return x; } Matrix plu_solve(const Matrix& m, const Matrix& b) { assert(m.rows() == m.cols()); assert(b.rows() == b.cols()); assert(m.rows() == b.rows()); std::size_t n = m.rows(); Matrix p; Matrix l; Matrix u; std::vector<std::size_t> pv; bool permuts; bool ok = plu_decomposition(m, p, l, u, pv, permuts); if (!ok) return Matrix{}; Matrix res(n, n); for (std::size_t k = 0; k < n; ++k) { Vector b2(n); for (std::size_t i = 0; i < n; ++i) b2[pv[i]] = b(i, k); Vector y = solve_lower(l, b2); Vector x = solve_upper(u, y); for (std::size_t i = 0; i < n; ++i) res(i, k) = x[i]; } return res; } Matrix plu_inverse(const Matrix& m) { assert(m.rows() == m.cols()); return plu_solve(m, Matrix::id(m.rows())); }
24.479263
82
0.445971
obs145628
7e5d1dedcd0ae12c2a1c8a9eacf5e0ecd79c8ded
5,998
cpp
C++
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2019 3MF Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. Abstract: NMR_ExportStream_GCC_Win32.cpp implements the CExportStream_GCC_Win32 Class. This is an abstract base stream class for exporting with GCC under Windows. --*/ #include "Common/Platform/NMR_ExportStream_GCC_Win32.h" #include "Common/NMR_Exception.h" #ifdef __GCC_WIN32 #include "Common/NMR_Exception_Windows.h" #endif // __GCC_WIN32 namespace NMR { #ifdef __GCC_WIN32 CExportStream_GCC_Win32::CExportStream_GCC_Win32(_In_ const nfWChar * pwszFileName) { if (pwszFileName == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); // Create handle m_hHandle = CreateFileW (pwszFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (m_hHandle == INVALID_HANDLE_VALUE) throw CNMRException_Windows(NMR_ERROR_COULDNOTCREATESTREAM, GetLastError()); } CExportStream_GCC_Win32::~CExportStream_GCC_Win32() { if (m_hHandle != INVALID_HANDLE_VALUE) { CloseHandle(m_hHandle); m_hHandle = 0; } } nfBool CExportStream_GCC_Win32::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = position; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_BEGIN); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfBool CExportStream_GCC_Win32::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = bytes; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_CURRENT); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfBool CExportStream_GCC_Win32::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = bytes; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_END); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfUint64 CExportStream_GCC_Win32::getPosition() { HRESULT hResult = S_OK; LARGE_INTEGER nPosition; nPosition.QuadPart = 0; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_CURRENT); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) throw CNMRException_Windows(NMR_ERROR_COULDNOTGETSTREAMPOSITION, hResult); } return nPosition.QuadPart; } nfUint64 CExportStream_GCC_Win32::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) { if (pBuffer == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); const nfByte * pBufP = (const nfByte *) pBuffer; nfUint64 cbBytesLeft = cbTotalBytesToWrite; nfUint64 cbTotalBytesWritten = 0; while (cbBytesLeft > 0) { nfUint32 cbBytesToWrite; long unsigned int cbWrittenBytes = 0; if (cbBytesLeft > NMR_EXPORTSTREAM_WRITEBUFFERSIZE) { cbBytesToWrite = NMR_EXPORTSTREAM_WRITEBUFFERSIZE; } else { cbBytesToWrite = (nfUint32) cbBytesLeft; } if (!WriteFile(m_hHandle, pBufP, cbBytesToWrite, &cbWrittenBytes, nullptr)) { throw CNMRException_Windows(NMR_ERROR_COULDNOTWRITESTREAM, GetLastError()); } if (cbWrittenBytes != cbBytesToWrite) throw CNMRException(NMR_ERROR_COULDNOTWRITEFULLDATA); pBufP += cbWrittenBytes; cbTotalBytesWritten += cbWrittenBytes; cbBytesLeft -= cbWrittenBytes; } return cbTotalBytesWritten; } #endif // __GCC_WIN32 }
32.247312
109
0.702568
geaz
7e5f898ee06344f571798d3c6d9564a146bd2e6e
10,645
hpp
C++
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: majermou <majermou@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/08 17:07:39 by majermou #+# #+# */ /* Updated: 2021/10/28 14:55:05 by majermou ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MAP_HPP #define MAP_HPP #include "avl_tree.hpp" #include "reverse_iterator.hpp" #include "vector.hpp" template<typename T> struct Iterator; template<typename T> struct ConstIterator; namespace ft { template < typename Key, typename T, typename Compare = std::less<Key>, typename Alloc = std::allocator<pair<const Key,T> > > class map { public: typedef Key key_type; typedef T mapped_type; typedef pair<const key_type,mapped_type> value_type; typedef Compare key_compare; typedef Alloc allocator_type; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference const_refernce; typedef typename allocator_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef typename allocator_type::difference_type difference_type; typedef typename allocator_type::size_type size_type; typedef Iterator<value_type> iterator; typedef ConstIterator<value_type> const_iterator; typedef ReverseIterator<iterator> reverse_iterator; typedef ReverseIterator<const_iterator> const_reverse_iterator; class value_compare : public std::binary_function<value_type, value_type, bool> { friend class map; protected: key_compare comp; value_compare(key_compare c) : comp(c) {} public: bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first); } }; private: value_compare m_comp; allocator_type m_allocator; Avl_tree<value_type,value_compare> m_Avl_tree; typedef typename Avl_tree<value_type,value_compare>::AvlNode AvlNode; public: explicit map(const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) : m_comp(comp), m_allocator(alloc), m_Avl_tree(value_compare(m_comp)) { } template <class InputIterator> map(InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) : m_comp(comp), m_allocator(alloc), m_Avl_tree(value_compare(comp)) { insert(first, last); } map (const map& x): m_comp(x.m_comp), m_allocator(x.m_allocator), m_Avl_tree(value_compare(m_comp)) { insert(x.begin(), x.end()); } ~map() { } map& operator=(const map& x) { if (this != &x) { clear(); insert(x.begin(), x.end()); } return *this; } iterator begin() { if (!m_Avl_tree.getMinValNode()) return iterator(m_Avl_tree.getEndNode()); return iterator(m_Avl_tree.getMinValNode()); } const_iterator begin() const { if (!m_Avl_tree.getMinValNode()) return const_iterator(m_Avl_tree.getEndNode()); return const_iterator(m_Avl_tree.getMinValNode()); } iterator end() { return iterator(m_Avl_tree.getEndNode()); } const_iterator end() const { return const_iterator(m_Avl_tree.getEndNode()); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_Avl_tree.isEmpty(); } size_type size() const { return m_Avl_tree.getSize(); } size_type max_size() const { return m_Avl_tree.getMaxSize(); } mapped_type& operator[](const key_type& k) { return (*((insert(ft::make_pair(k,mapped_type()))).first)).second; } pair<iterator,bool> insert(const value_type& val) { AvlNode node = m_Avl_tree.search(val); if (node == m_Avl_tree.getEndNode()) { m_Avl_tree.insert(val); return ft::make_pair(iterator(m_Avl_tree.search(val)), true); } return ft::make_pair(iterator(node), false); } iterator insert(iterator position, const value_type& val) { AvlNode node = m_Avl_tree.search(val); if (node == m_Avl_tree.getEndNode()) { insert(val); return iterator(m_Avl_tree.search(val)); } return iterator(node); position++; } template <class InputIterator> void insert(InputIterator first, InputIterator last) { while (first != last) { insert(ft::make_pair(first->first,first->second)); first++; } } void erase(iterator position) { if (position != iterator(NULL)) { m_Avl_tree.remove(ft::make_pair(position->first,position->second)); } } size_type erase(const key_type& k) { if (m_Avl_tree.search(ft::make_pair(k,mapped_type())) == m_Avl_tree.getEndNode()) { return 0; } m_Avl_tree.remove(ft::make_pair(k,mapped_type())); return 1; } void erase(iterator first, iterator last) { while (first != last) { erase(first++); } } void swap(map& x) { m_Avl_tree.swap(x.m_Avl_tree); } void clear() { m_Avl_tree.clear(); } key_compare key_comp() const { return key_compare(); } value_compare value_comp() const { return value_compare(m_comp); } iterator find(const key_type& k) { return iterator(m_Avl_tree.search(ft::make_pair(k,mapped_type()))); } const_iterator find(const key_type& k) const { return const_iterator(m_Avl_tree.search(ft::make_pair(k,mapped_type()))); } size_type count(const key_type& k) const { return (m_Avl_tree.search(ft::make_pair(k,mapped_type())) == m_Avl_tree.getEndNode()) ? 0 : 1; } iterator lower_bound(const key_type& k) { return iterator(m_Avl_tree.lower_bound(ft::make_pair(k,mapped_type()))); } const_iterator lower_bound(const key_type& k) const { return const_iterator(m_Avl_tree.lower_bound(ft::make_pair(k,mapped_type()))); } iterator upper_bound(const key_type& k) { return iterator(m_Avl_tree.upper_bound(ft::make_pair(k,mapped_type()))); } const_iterator upper_bound(const key_type& k) const { return const_iterator(m_Avl_tree.upper_bound(ft::make_pair(k,mapped_type()))); } ft::pair<const_iterator,const_iterator> equal_range(const key_type& k) const { return ft::make_pair(lower_bound(k), upper_bound(k)); } ft::pair<iterator,iterator> equal_range(const key_type& k) { return ft::make_pair(lower_bound(k), upper_bound(k)); } allocator_type get_allocator() const { return allocator_type(); } }; } template<typename T> struct Iterator{ typedef T value_type; typedef T* pointer; typedef T& reference; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef Iterator<T> Self; typedef typename Node<T>::NodePtr NodePtr; Iterator(): m_node() {} explicit Iterator(NodePtr x): m_node(x) {} reference operator*() const { return (m_node)->data; } pointer operator->() const { return &(m_node)->data; } Self operator++() { m_node = Avl_tree_increment<NodePtr>(m_node); return *this; } Self operator++(int) { Self tmp = *this; m_node = Avl_tree_increment<NodePtr>(m_node); return tmp; } Self operator--() { m_node = Avl_tree_decrement<NodePtr>(m_node); return *this; } Self operator--(int) { Self tmp = *this; m_node = Avl_tree_decrement<NodePtr>(m_node); return tmp; } bool operator==(const Self& x) const { return m_node == x.m_node; } bool operator!=(const Self& x) const { return m_node != x.m_node; } NodePtr m_node; }; template<typename T> struct ConstIterator { typedef T value_type; typedef const T* pointer; typedef const T& reference; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef Iterator<T> iterator; typedef ConstIterator<T> Self; typedef typename Node<T>::Const_NodePtr NodePtr; ConstIterator(): m_node() { } explicit ConstIterator(NodePtr x): m_node(x) { } ConstIterator(const iterator& it): m_node(it.m_node) { } reference operator*() const { return (m_node)->data; } pointer operator->() const { return &(m_node)->data; } Self& operator++() { m_node = Avl_tree_increment<NodePtr>(m_node); return *this; } Self operator++(int) { Self tmp = *this; m_node = Avl_tree_increment<NodePtr>(m_node); return tmp; } Self& operator--() { m_node = Avl_tree_decrement<NodePtr>(m_node); return *this; } Self operator--(int) { Self tmp = *this; m_node = Avl_tree_decrement<NodePtr>(m_node); return tmp; } bool operator==(const Self& x) const { return m_node == x.m_node; } bool operator!=(const Self& x) const { return m_node != x.m_node; } NodePtr m_node; }; template<typename NodePtr> bool operator==(const Iterator<NodePtr>& x, const ConstIterator<NodePtr>& y) { return x.m_node == y.m_node; } template<typename NodePtr> bool operator!=(const Iterator<NodePtr>& x, const ConstIterator<NodePtr>& y) { return x.m_node != y.m_node; } #endif // MAP_HPP
32.063253
98
0.584688
majermou
7e603cf8afddda3aae365332949d97c11f9264a2
1,866
cpp
C++
training/GCJ/2017/QR-A.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/GCJ/2017/QR-A.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/GCJ/2017/QR-A.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 16:53 on 8 Apr 2017 #include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "A-large" #define setfile() freopen(filename".in.txt", "r", stdin); freopen(filename".ans.txt", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans.txt"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_N = 1e3 + 10; int t, n, dir[MAX_N], f[MAX_N], k; string s; int cal(int k) { memset(f, 0, sizeof f); int sum = 0, res = 0; for (int i = 0; i + k <= n; ++i) { if ((dir[i] + sum) % 2 != 0) { ++res; f[i] = 1; } sum += f[i]; if (i - k + 1 >= 0) sum -= f[i - k + 1]; } for (int i = n - k + 1; i < n; ++i) { if ((dir[i] + sum) % 2 != 0) { return -1; } if (i - k + 1 >= 0) sum -= f[i - k + 1]; } return res; } int main() { setfile(); cin >> t; for (int _ = 0; _ < t; _++) { cin >> s >> k; n = s.length(); for (int i = 0; i < n; i++) if (s[i] == '-') dir[i] = 1; else dir[i] = 0; printf("Case #%d: ", _ + 1); int ans = cal(k); if (ans == -1) printf("IMPOSSIBLE\n"); else printf("%d\n", ans); } resetfile(); }
24.88
122
0.489282
voleking
7e63c8f5b6f87a61e6895cabbfb49dbf1c0053e8
1,605
cpp
C++
Libraries/RobsJuceModules/rosic/modulators/rosic_DecayEnvelope.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/modulators/rosic_DecayEnvelope.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/modulators/rosic_DecayEnvelope.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//#include "rosic_DecayEnvelope.h" //using namespace rosic; //------------------------------------------------------------------------------------------------- // construction/destruction: DecayEnvelope::DecayEnvelope() { c = 1.0; y = 1.0; yInit = 1.0; tau = 200.0; fs = 44100.0; normalizeSum = false; calculateCoefficient(); } DecayEnvelope::~DecayEnvelope() { } //------------------------------------------------------------------------------------------------- // parameter settings: void DecayEnvelope::setSampleRate(double newSampleRate) { if( newSampleRate > 0.0 ) { fs = newSampleRate; calculateCoefficient(); } } void DecayEnvelope::setDecayTimeConstant(double newTimeConstant) { if( newTimeConstant > 0.001 ) // at least 0.001 ms decay { tau = newTimeConstant; calculateCoefficient(); } } void DecayEnvelope::setNormalizeSum(bool shouldNormalizeSum) { normalizeSum = shouldNormalizeSum; calculateCoefficient(); } //------------------------------------------------------------------------------------------------- // others: void DecayEnvelope::trigger() { y = yInit; } bool DecayEnvelope::endIsReached(double threshold) { if( y < threshold ) return true; else return false; } //------------------------------------------------------------------------------------------------- // internal functions: void DecayEnvelope::calculateCoefficient() { c = exp( -1.0 / (0.001*tau*fs) ); if( normalizeSum == true ) yInit = (1.0-c)/c; else yInit = 1.0/c; }
20.576923
99
0.478505
RobinSchmidt
7e6595418fc17ae2f1b95b61f9e2afe099948280
5,683
cpp
C++
src/dialogs/options_dialog.cpp
johannphilippe/Tracker4
e2eb6700bb8827dc8181aba889a78760f21a98f8
[ "MIT" ]
null
null
null
src/dialogs/options_dialog.cpp
johannphilippe/Tracker4
e2eb6700bb8827dc8181aba889a78760f21a98f8
[ "MIT" ]
1
2021-12-28T10:47:47.000Z
2021-12-28T18:54:46.000Z
src/dialogs/options_dialog.cpp
johannphilippe/Tracker4
e2eb6700bb8827dc8181aba889a78760f21a98f8
[ "MIT" ]
null
null
null
#include<dialogs/options_dialog.h> auto option_item::make_view() { auto tog_enable = plain_toggle_icon_button( icons::cancel, icons::ok, 1.0); tog_enable.value(enabled); tog_enable.on_click = [&](bool b) { enabled = b; }; auto tb = input_box("Write a Csound option"); tb.second->set_text(option); tb.second->on_text = [&](std::string_view v) { option = v; }; return htile( (tb.first), (tog_enable) ); } option_item::option_item(std::string name, bool enable) : options_dialog_click_callback(), audio_cs_option(name, enable), array_composite<2, htile_element>(make_view()) {} void cs_option_list::add_item(std::string s, bool enabled) { auto item = std::make_shared<option_item>(s, enabled); auto full_item = share(basic_menu_item( right_margin(15, hold(item) ))); full_item->on_click = [&, item](){ for(size_t i = 0; i < items.size(); i++) { if(item.get() == items[i].get()) { _selected = i; break; } } }; items.push_back(item); this->push_back(full_item); } void cs_option_list::add_item() {add_item("", true);} void cs_option_list::remove_selected() { if(_selected == -1) return; items.erase(items.begin() + _selected); erase(begin() + _selected); _selected = -1; } void cs_option_list::pop() { if(size() == 0) return; if(_selected != -1 && _selected == static_cast<int>(items.size()) - 1) _selected = -1; items.pop_back(); vtile_composite::pop_back(); } auto audio_options_view::make_view() { auto plus_but = plain_icon_button(icons::plus, 1.0); auto minus_but = plain_icon_button(icons::minus, 1.0); auto rem_but = plain_icon_button(icons::cancel, 1.0); plus_but.on_click = [&](bool) { options_list.add_item(); jtracker::get_app()->_view.layout(); jtracker::get_app()->_view.refresh(); }; minus_but.on_click = [&](bool) { if(options_list.size() == 0) return; options_list.pop(); jtracker::get_app()->_view.layout(); jtracker::get_app()->_view.refresh(); }; rem_but.on_click = [&](bool) { if(options_list.size() == 0 ) return; options_list.remove_selected(); jtracker::get_app()->_view.layout(); jtracker::get_app()->_view.refresh(); }; return (margin({15, 10, 15, 10}, vtile( simple_heading(link(sample_rate_spin), "Sample rate"), vspacer(5), simple_heading(link(ksmps_spin), "Ksmps - audio vector size"), vspacer(5), simple_heading(link(dbfs_spin), "0dbfs"), vspacer(5), htile( simple_heading(link(inchnls_spin), "Input channels"), vspacer(5), simple_heading(link(nchnls_spin), "Output channels") ), vspacer(5), simple_heading( vtile( align_center( htile( align_left(rem_but), align_middle(minus_but), align_right(plus_but) )), layer( limit({{60, 150},{full_extent, full_extent}}, vscroller( link(options_list) )), rbox(jtracker::theme.app_background_color.level(0.65), 6) ) ), "Csound options") ))) ; } options_dialog* options_dialog::instance = nullptr; options_dialog* options_dialog::get_instance() { if(instance != nullptr) delete instance; instance = new options_dialog(); return instance; } auto options_dialog::make_options_tab() { // first construct object audio_options = std::make_shared<audio_options_view>(); auto tabs = hnotebook( jtracker::get_app()->_view, deck( layer(align_center_middle(audio_options->make_view())), layer(align_center_middle(label("Options2").font_size(100)), frame{}), layer(align_center_middle(label("Options3").font_size(100)), frame{}) ), tab("Audio Options"), tab("Options2"), tab("Options3") ); return tabs; } void options_dialog::update_config() { // audio actualize jtracker::data.audio_config.sample_rate = audio_options->sample_rate_spin.get_value(); jtracker::data.audio_config.ksmps = audio_options->ksmps_spin.get_value(); jtracker::data.audio_config.dbfs = audio_options->dbfs_spin.get_value(); jtracker::data.audio_config.i_nchnls = audio_options->inchnls_spin.get_value(); jtracker::data.audio_config.nchnls = audio_options->nchnls_spin.get_value(); jtracker::data.audio_config.additional_options.clear(); for(auto & it : audio_options->options_list.items) { jtracker::data.audio_config.additional_options.push_back( audio_cs_option(it->option, it->enabled) ); } } void options_dialog::make_content() { _name = "Options"; auto close_but = button("Close"); close_but.on_click = [&](bool) { close(); }; auto ok_button = button("Validate"); ok_button.on_click = [&](bool) { // save before jtracker::save_audio_config(); update_config(); close(); }; content_ptr = share( margin({10, 10, 10, 10}, vtile( make_options_tab(), htile(ok_button,close_but) ) )); }
28.557789
109
0.56801
johannphilippe
7e67c467e00420adcfb2b3de598b24025f715d71
6,863
cpp
C++
addons/ofxGuido/lib/guidolib-code/src/lib/GUIDOEngineJava.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
addons/ofxGuido/lib/guidolib-code/src/lib/GUIDOEngineJava.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
2
2015-08-04T00:07:46.000Z
2017-05-10T15:53:51.000Z
addons/ofxGuido/lib/guidolib-code/src/lib/GUIDOEngineJava.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
// Following code was previously in GUIDOEngine.cpp #ifdef JAVADLL #include "creategif.h" #include <jni.h> JNIEXPORT jint JNICALL Java_NotationRenderer_parse__Ljava_lang_String_2 (JNIEnv *env, jclass obj, jstring filename) { const char * str = env->GetStringUTFChars(filename,0); int i = GuidoParse2(str,0); env->ReleaseStringUTFChars(filename,str); return i; } JNIEXPORT void JNICALL Java_NotationRenderer_free__I ( JNIEnv *env, jclass obj, jint id) { GuidoFreeHandle((int) id); } JNIEXPORT int JNICALL Java_NotationRenderer_GuidoGetNumPages__I (JNIEnv *env, jclass obj, jint id) { return GuidoGetNumPages((int) id); } JNIEXPORT jbyteArray JNICALL Java_NotationRenderer_getGIF__IFII (JNIEnv *env, jclass obj, jint id, jfloat zoom, jint pagenum, jint adjustpagesize) { // now we need to call the equivalent GMN2GIF-Function ... // create a temporary filename ... -> date + random ... char *name=tmpnam(NULL); FILE *mylog = fopen("mylog","a"); fprintf(mylog,"Tempname : %s\n",name); fflush(mylog); if (name == NULL) { return NULL; } int ret = CreateGIFPicture(id, (double) zoom,0,0,adjustpagesize, pagenum,0,NULL, name); // now we read in the file that was // just created and save it in the byte-Array ... FILE *myfile = fopen(name,"rb"); // read binary ... if (!myfile) { fprintf(mylog,"File %s could not be opened\n",name); fflush(mylog); return NULL; } fseek(myfile,0,SEEK_END); long length = ftell(myfile); fseek(myfile,0,SEEK_SET); fprintf(mylog,"length %ld\n",length); fflush(mylog); // how to we declare a new byteArray ? jbyteArray mybytearray = env->NewByteArray(length); if (mybytearray == NULL) { fprintf(mylog,"Array could not be constructed\n"); fflush(mylog); return NULL; } // now we set the elements ... jbyte *mybytes = env->GetByteArrayElements(mybytearray,NULL); if (mybytes == NULL) { fprintf(mylog,"Could not get a contiguos memory ...\n"); fflush(mylog); return NULL; } fprintf(mylog,"Now reading %ld bytes\n",length); fflush(mylog); fread(mybytes,length,1,myfile); fclose(myfile); remove(name); // copy back changes ... env->ReleaseByteArrayElements(mybytearray,mybytes,0); return mybytearray; } jmethodID ggsoswrite = NULL; JNIEnv *jnienv = NULL; jclass ggsos; // This routine is being called from the // GuidoGraphicStreamOutput-routines of the classlibrary // it justs writes the information on // the given Stream ... void AddGGSOutput(const char *s) { // this routine is called by the classes // when they have to produce GGS-Output ... if (jnienv == NULL || ggsoswrite == NULL || ggsos == NULL) return; jstring mystring = jnienv->NewStringUTF(s); jnienv->CallVoidMethod(ggsos,ggsoswrite,mystring); } JNIEXPORT void JNICALL Java_NotationRenderer_GuidoGetGuidoGraphicStream__IILjava_io_PrintStream_2 (JNIEnv *env, jclass obj, jint id, jint numpage, jclass os) { // this is called to get the GuidoGraphicStream ... // it gets an outputstream that can be written ... jnienv = env; ggsos = os; jclass myclass = env->GetObjectClass(os); // ggsoswrite = // env->GetMethodID(myclass,"write","([B)V"); ggsoswrite = env->GetMethodID(myclass,"print","(Ljava/lang/String;)V"); if (ggsoswrite == NULL) { FILE *mylog = fopen("mylog","a"); fprintf(mylog,"Could not find method ID\n"); fflush(mylog); return; } // now we call the function to retrieve the // data ... GuidoGraphicStreamOutput(id,numpage); // AddGGSOutput("done\n"); jnienv = NULL; ggsos = NULL; ggsoswrite = NULL; } jmethodID guidooswrite = NULL; jclass guidoos; // This routine is being called from the // Guido-output-routine of the classlibrary // it justs writes the information on // the given Stream ... void AddGuidoOutput(const char *s) { // this routine is called by the classes // when they have to produce Guido-Output ... if (jnienv == NULL || guidooswrite == NULL || guidoos == NULL) return; // change this .... to the // new NEWUTF-String thing ... jstring mystring = jnienv->NewStringUTF(s); jnienv->CallVoidMethod(guidoos,guidooswrite,mystring); } JNIEXPORT void JNICALL Java_NotationRenderer_GuidoGetGuido__ILjava_io_PrintStream_2 (JNIEnv *env, jclass obj, jint id, jclass os) { // this is called to get the GuidoGraphicStream ... // it gets an outputstream that can be written ... jnienv = env; guidoos = os; jclass myclass = env->GetObjectClass(os); // guidooswrite = // env->GetMethodID(myclass,"write","([B)V"); guidooswrite = env->GetMethodID(myclass,"print","(Ljava/lang/String;)V"); if (guidooswrite == NULL) { FILE *mylog = fopen("mylog","a"); fprintf(mylog,"Could not find method ID\n"); fflush(mylog); return; } // now we call the function to retrieve the // data ... GuidoGetGuido(id); jnienv = NULL; guidoos = NULL; guidooswrite = NULL; } JNIEXPORT jint JNICALL Java_NotationRenderer_putGuidoGraphicStream__IILjava_lang_String_2 (JNIEnv *env, jclass obj, jint id, jint page, jstring ggsstring) { // this is called to get the GuidoGraphicStream ... // it gets an outputstream that can be written ... const char * str = env->GetStringUTFChars(ggsstring,0); // now we need to do something with this string... // get it to the GRMusic ... or what? int ret = GuidoGraphicStreamInput(id,page,str); // last step: we release the JAVA string. env->ReleaseStringUTFChars(ggsstring,str); return ret; } JNIEXPORT jint JNICALL Java_NotationRenderer_getTestGID__I (JNIEnv *env, jclass obj, jint id) { return (jint) GuidoGraphicStreamTest(id); } // this routine returns info about // a graphics-object ... JNIEXPORT jstring JNICALL Java_NotationRenderer_getGraphicInfo__III (JNIEnv *env, jclass obj, jint id, jint gid, jint manipulation) { if (gid == 0) return NULL; // gid points directly into memory ... GObject * o = dynamic_cast<GObject *>((GObject *) gid); if (!o) return NULL; char *buf = o->getGGSInfo(manipulation); if (buf) { jstring mystr = env->NewStringUTF(buf); delete [] buf; return mystr; } else return NULL; //const type_info &tinfo = typeid(*o); // const char *name = tinfo.name(); // jstring mystr = env->NewStringUTF(name); // return mystr; } #else // JAVADLL // This routine is being called from the // GuidoGraphicStreamOutput-routines of the classlibrary // it justs writes the information on // the given Stream ... void AddGGSOutput(const char *s) { // we do nothing .... } void AddGuidoOutput(const char *s) { } #endif // JAVADLL
20.1261
76
0.668367
k4rm
7e6913bf00ad1968b5095d0623ba0f228991ba57
5,426
cpp
C++
imp_bridge_ros/src/ros_bridge.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
30
2016-09-27T07:41:28.000Z
2021-12-03T20:44:28.000Z
imp_bridge_ros/src/ros_bridge.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
1
2018-12-18T15:53:06.000Z
2018-12-21T03:10:06.000Z
imp_bridge_ros/src/ros_bridge.cpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
12
2016-11-05T07:51:29.000Z
2020-07-13T02:26:08.000Z
// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye // 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 <imp/bridge/ros/ros_bridge.hpp> #include <sensor_msgs/image_encodings.h> #include <imp/core/image_raw.hpp> #include <ze/common/logging.hpp> #include <ze/common/types.hpp> namespace ze { namespace imgenc = sensor_msgs::image_encodings; //------------------------------------------------------------------------------ std::pair<PixelType, PixelOrder> getPixelTypeFromRosImageEncoding( const std::string& encoding) { //! @todo (MWE) we do not support bayer or YUV images yet. if (encoding == imgenc::BGR8) { return std::make_pair(PixelType::i8uC3, PixelOrder::bgr); } else if (encoding == imgenc::MONO8) { return std::make_pair(PixelType::i8uC1, PixelOrder::gray); } else if (encoding == imgenc::RGB8) { return std::make_pair(PixelType::i8uC3, PixelOrder::rgb); } else if (encoding == imgenc::MONO16) { return std::make_pair(PixelType::i16uC1, PixelOrder::gray); } else if (encoding == imgenc::BGR16) { return std::make_pair(PixelType::i16uC3, PixelOrder::bgr); } else if (encoding == imgenc::RGB16) { return std::make_pair(PixelType::i16uC3, PixelOrder::rgb); } else if (encoding == imgenc::BGRA8) { return std::make_pair(PixelType::i8uC4, PixelOrder::bgra); } else if (encoding == imgenc::RGBA8) { return std::make_pair(PixelType::i8uC4, PixelOrder::rgba); } else if (encoding == imgenc::BGRA16) { return std::make_pair(PixelType::i16uC4, PixelOrder::bgra); } else if (encoding == imgenc::RGBA16) { return std::make_pair(PixelType::i16uC4, PixelOrder::rgba); } LOG(FATAL) << "Unsupported image encoding " + encoding + "."; return std::make_pair(PixelType::undefined, PixelOrder::undefined); } //------------------------------------------------------------------------------ ImageBase::Ptr toImageCpu( const sensor_msgs::Image& src, PixelOrder /*pixel_order*/) { PixelType src_pixel_type; PixelOrder src_pixel_order; std::tie(src_pixel_type, src_pixel_order) = getPixelTypeFromRosImageEncoding(src.encoding); int bit_depth = imgenc::bitDepth(src.encoding); int num_channels = imgenc::numChannels(src.encoding); uint32_t width = src.width; uint32_t height = src.height; uint32_t pitch = src.step; // sanity check CHECK_GE(pitch, width * num_channels * bit_depth/8) << "Input image seem to wrongly formatted"; switch (src_pixel_type) { case PixelType::i8uC1: { ImageRaw8uC1 src_wrapped( reinterpret_cast<Pixel8uC1*>(const_cast<uint8_t*>(&src.data[0])), width, height, pitch, true, PixelOrder::gray); ImageRaw8uC1::Ptr dst = std::make_shared<ImageRaw8uC1>(src_wrapped); // Deep copy of the image data. return dst; } // case imp::PixelType::i8uC2: // { } break; // case imp::PixelType::i8uC3: // { } break; // case imp::PixelType::i8uC4: // { } break; // case imp::PixelType::i16uC1: // { } break; // case imp::PixelType::i16uC2: // { } break; // case imp::PixelType::i16uC3: // { } break; // case imp::PixelType::i16uC4: // { } break; // case imp::PixelType::i32uC1: // { } break; // case imp::PixelType::i32uC2: // { } break; // case imp::PixelType::i32uC3: // { } break; // case imp::PixelType::i32uC4: // { } break; // case imp::PixelType::i32sC1: // { } break; // case imp::PixelType::i32sC2: // { } break; // case imp::PixelType::i32sC3: // { } break; // case imp::PixelType::i32sC4: // { } break; // case imp::PixelType::i32fC1: // { } break; // case imp::PixelType::i32fC2: // { } break; // case imp::PixelType::i32fC3: // { } break; // case imp::PixelType::i32fC4: // { } break; default: { LOG(FATAL) << "Unsupported pixel type" + src.encoding + "."; break; } } return nullptr; } } // namespace ze
33.085366
97
0.661629
rockenbf
7e69362c87c64e6c8089a62c817bdaf0067ced2c
2,489
cpp
C++
Source/Samples/99_Benchmark/Benchmark03_MoleculeLogic.cpp
pat2nav/Urho3D
cc0346f39bd365782d825e2e337a1f33bb225308
[ "MIT" ]
null
null
null
Source/Samples/99_Benchmark/Benchmark03_MoleculeLogic.cpp
pat2nav/Urho3D
cc0346f39bd365782d825e2e337a1f33bb225308
[ "MIT" ]
null
null
null
Source/Samples/99_Benchmark/Benchmark03_MoleculeLogic.cpp
pat2nav/Urho3D
cc0346f39bd365782d825e2e337a1f33bb225308
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include "Benchmark03_MoleculeLogic.h" #include <Urho3D/Scene/Scene.h> #include <Urho3D/DebugNew.h> using namespace Urho3D; Benchmark03_MoleculeLogic::Benchmark03_MoleculeLogic(Context* context) : LogicComponent(context) , moleculeType_(0) { SetUpdateEventMask(USE_UPDATE | USE_POSTUPDATE); } void Benchmark03_MoleculeLogic::SetParameters(i32 type) { moleculeType_ = type; } static constexpr float MOLECULE_RADIUS = 1.f; static constexpr float INTERACTION_RANGE = MOLECULE_RADIUS * 4.f; static constexpr float CONTAINER_RADIUS = 9.f; void Benchmark03_MoleculeLogic::Update(float timeStep) { PODVector<Node*> moleculeNodes; GetScene()->GetChildrenWithComponent<Benchmark03_MoleculeLogic>(moleculeNodes); Vector2 moleculePos = node_->GetPosition2D(); for (Node* anotherMoleculeNode : moleculeNodes) { if (anotherMoleculeNode == node_) continue; Vector2 anotherMoleculePos = anotherMoleculeNode->GetPosition2D(); i32 anotherMoleculeType = anotherMoleculeNode->GetComponent<Benchmark03_MoleculeLogic>()->GetMoleculeType(); float distance = (anotherMoleculePos - moleculePos).Length(); if (Equals(distance, 0.f)) { // Molecules are at the same point velocity_ = Vector2(Random(-2.f, 2.f), Random(-2.f, 2.f)); continue; } // Molecules are too far away and don't interact if (distance >= INTERACTION_RANGE) continue; Vector2 direction = (anotherMoleculePos - moleculePos).Normalized(); float forceModulus = 1.f - distance / INTERACTION_RANGE; forceModulus = forceModulus * forceModulus * forceModulus; forceModulus = forceModulus * 25.f; if (moleculeType_ != anotherMoleculeType) forceModulus *= 1.5f; force_ -= forceModulus * direction; } if (moleculePos.Length() > CONTAINER_RADIUS - MOLECULE_RADIUS) { Vector2 backDirection = -moleculePos.Normalized(); float backModulus = (moleculePos.Length() - CONTAINER_RADIUS + MOLECULE_RADIUS) * 50.0f; force_ = force_ + backDirection * backModulus; } velocity_ = velocity_ + force_ * timeStep; velocity_ = velocity_.Lerp(Vector2::ZERO, timeStep * 0.5f); } void Benchmark03_MoleculeLogic::PostUpdate(float timeStep) { node_->Translate2D(velocity_ * timeStep); force_ = Vector2::ZERO; }
29.630952
116
0.688228
pat2nav
7e69c58fe619dda520c796e42f83119eae54948b
1,409
cpp
C++
safe_drive/src/safe_drive_node.cpp
RafalStaszak/autonomous-real
e45214ed323d9627de2c5f1f4188e330d65dd202
[ "MIT" ]
null
null
null
safe_drive/src/safe_drive_node.cpp
RafalStaszak/autonomous-real
e45214ed323d9627de2c5f1f4188e330d65dd202
[ "MIT" ]
null
null
null
safe_drive/src/safe_drive_node.cpp
RafalStaszak/autonomous-real
e45214ed323d9627de2c5f1f4188e330d65dd202
[ "MIT" ]
1
2018-06-05T18:08:29.000Z
2018-06-05T18:08:29.000Z
#include <ros/ros.h> #include <geometry_msgs/Twist.h> class Safety { public: Safety(); private: void Callback(const geometry_msgs::Twist::ConstPtr& move); ros::NodeHandle n; ros::Publisher stop_pub; ros::Subscriber twist_sub; ros::Time current_time, last_time; float czas; }; Safety::Safety() { stop_pub = n.advertise<geometry_msgs::Twist>("Twist", 1); //declaration of publisher on topic Twist geometry_msgs::Twist stop; czas=0; //variable czas (eng. time) current_time = ros::Time::now(); last_time = ros::Time::now(); ros::Rate r(10); //loop is rated at 10Hz while(n.ok()) { ros::spinOnce(); current_time = ros::Time::now(); czas+=(current_time - last_time).toSec(); //czas is counting the time as the program run, it is valued in seconds twist_sub = n.subscribe<geometry_msgs::Twist>("Twist", 1, &Safety::Callback, this); //declaration of subscribing the Twist topic if(czas>5) //if there were no messages from Twist in last five seconds { stop_pub.publish(stop); //send a message to stop } last_time = ros::Time::now(); r.sleep(); } } void Safety::Callback(const geometry_msgs::Twist::ConstPtr& move) { czas=0; //when a massege received czas is set to zero, and time is counted again } int main(int argc, char** argv) { ros::init(argc, argv, "safe_drive_node"); Safety safety; }
24.719298
133
0.660043
RafalStaszak
7e69f826c471f129bcffa9d0d121ec25b7803a03
22,550
cpp
C++
zinew/extremephysics-2-2/extremephysics-2-2/c++/ExtremePhysics 2.2 DLL/gm_shape.cpp
Bitl/Game-Maker-Projects
99f3eabcae8ef624f39f11715ebba327631dd78c
[ "MIT" ]
null
null
null
zinew/extremephysics-2-2/extremephysics-2-2/c++/ExtremePhysics 2.2 DLL/gm_shape.cpp
Bitl/Game-Maker-Projects
99f3eabcae8ef624f39f11715ebba327631dd78c
[ "MIT" ]
null
null
null
zinew/extremephysics-2-2/extremephysics-2-2/c++/ExtremePhysics 2.2 DLL/gm_shape.cpp
Bitl/Game-Maker-Projects
99f3eabcae8ef624f39f11715ebba327631dd78c
[ "MIT" ]
null
null
null
/* * Copyright 2009-2011 Maarten Baert * maarten-baert@hotmail.com * http://www.maartenbaert.be/ * * This file is part of ExtremePhysics. * * ExtremePhysics is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ExtremePhysics 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 ExtremePhysics. If not, see <http://www.gnu.org/licenses/>. * * File: gm_shape.cpp * Wrapper for ep_Shape. */ #include "gm.h" gmexport double ep_shape_create_box(double world_id, double body_id, double w, double h, double x, double y, double rot, double density) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_box: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_box: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->CreateBoxShape(w, h, x, y, rot, density))==NULL) { return 0; } ((gmuserdata*)(shape->GetUserData()))->Clear(); shape->CacheID(); return shape->GetID(); } gmexport double ep_shape_create_line(double world_id, double body_id, double x1, double y1, double x2, double y2, double density) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_box: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_box: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->CreateLineShape(x1, y1, x2, y2, density))==NULL) { return 0; } ((gmuserdata*)(shape->GetUserData()))->Clear(); shape->CacheID(); return shape->GetID(); } gmexport double ep_shape_create_circle(double world_id, double body_id, double r, double x, double y, double rot, double density) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_circle: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_circle: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->CreateCircleShape(r, x, y, rot, density))==NULL) { return 0; } ((gmuserdata*)(shape->GetUserData()))->Clear(); shape->CacheID(); return shape->GetID(); } gmexport double ep_shape_create_polygon(double world_id, double body_id, double polygon_id, double x, double y, double rot, double density) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_polygon: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_polygon: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Polygon *polygon; if((polygon = world->FindPolygon(gm_cast<unsigned long>(polygon_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_create_polygon: Polygon %lu doesn't exist in world %lu.", gm_cast<unsigned long>(polygon_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->CreatePolygonShape(polygon, x, y, rot, density))==NULL) { return 0; } ((gmuserdata*)(shape->GetUserData()))->Clear(); shape->CacheID(); return shape->GetID(); } gmexport double ep_shape_destroy(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_destroy: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_destroy: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_destroy: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } body->DestroyShape(shape); return 1; } gmexport double ep_shape_exists(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_exists: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_exists: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } return (body->FindShape(gm_cast<unsigned long>(shape_id))!=NULL)? 1 : 0; } gmexport double ep_shape_get_first_contact(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_first_contact: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_first_contact: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_first_contact: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } ep_Contact *contact = shape->GetFirstContact(); if(contact==NULL) { return 0; } contact->CacheID(); return contact->GetID(); } gmexport double ep_shape_get_last_contact(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_last_contact: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_last_contact: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_last_contact: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } ep_Contact *contact = shape->GetLastContact(); if(contact==NULL) { return 0; } contact->CacheID(); return contact->GetID(); } gmexport double ep_shape_get_previous_contact(double world_id, double body_id, double shape_id, double contact_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_previous_contact: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_previous_contact: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_previous_contact: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } ep_Contact *contact; if((contact = world->FindContact(gm_cast<unsigned long>(contact_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_previous_contact: Contact %lu doesn't exist in world %lu.", gm_cast<unsigned long>(contact_id), world->GetID()); return 0; } contact = shape->GetPreviousContact(contact); if(contact==NULL) { return 0; } contact->CacheID(); return contact->GetID(); } gmexport double ep_shape_get_next_contact(double world_id, double body_id, double shape_id, double contact_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_next_contact: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_next_contact: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_next_contact: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } ep_Contact *contact; if((contact = world->FindContact(gm_cast<unsigned long>(contact_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_next_contact: Contact %lu doesn't exist in world %lu.", gm_cast<unsigned long>(contact_id), world->GetID()); return 0; } contact = shape->GetNextContact(contact); if(contact==NULL) { return 0; } contact->CacheID(); return contact->GetID(); } gmexport double ep_shape_set_material(double world_id, double body_id, double shape_id, double restitution, double friction, double normalvelocity, double tangentvelocity) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_material: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_material: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_material: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } shape->SetMaterial(gm_cast<float>(restitution), gm_cast<float>(friction), normalvelocity, tangentvelocity); return 1; } gmexport double ep_shape_set_collision(double world_id, double body_id, double shape_id, double collidemask1, double collidemask2, double group) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_collision: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_collision: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_collision: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } shape->SetCollision(gm_cast<unsigned long>(collidemask1), gm_cast<unsigned long>(collidemask2), gm_cast<unsigned long>(group)); return 1; } gmexport double ep_shape_collision_test_box(double world_id, double body_id, double shape_id, double w, double h, double x, double y, double rot, double contact_threshold) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_box: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_box: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_box: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } return (shape->CollisionTestBox(w, h, x, y, rot, contact_threshold))? 1 : 0; } gmexport double ep_shape_collision_test_line(double world_id, double body_id, double shape_id, double x1, double y1, double x2, double y2, double contact_threshold) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_line: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_line: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_line: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } return (shape->CollisionTestLine(x1, y1, x2, y2, contact_threshold))? 1 : 0; } gmexport double ep_shape_collision_test_circle(double world_id, double body_id, double shape_id, double r, double x, double y, double contact_threshold) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_circle: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_circle: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_circle: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } return (shape->CollisionTestCircle(r, x, y, contact_threshold))? 1 : 0; } gmexport double ep_shape_collision_test_polygon(double world_id, double body_id, double shape_id, double polygon_id, double x, double y, double rot, double contact_threshold) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_polygon: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_polygon: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_polygon: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } ep_Polygon *polygon; if((polygon = world->FindPolygon(gm_cast<unsigned long>(polygon_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_collision_test_polygon: Polygon %lu doesn't exist in world %lu.", gm_cast<unsigned long>(polygon_id), world->GetID()); return 0; } return (shape->CollisionTestPolygon(polygon, x, y, rot, contact_threshold))? 1 : 0; } gmexport double ep_shape_ray_cast(double world_id, double body_id, double shape_id, double x, double y, double vx, double vy) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_ray_cast: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_ray_cast: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_ray_cast: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } return shape->RayCast(x, y, vx, vy); } gmexport double ep_shape_previous(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_previous: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_previous: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_previous: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } if(shape->GetPrevious()==NULL) { return 0; } shape->GetPrevious()->CacheID(); return shape->GetPrevious()->GetID(); } gmexport double ep_shape_next(double world_id, double body_id, double shape_id) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_next: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_next: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_next: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } if(shape->GetNext()==NULL) { return 0; } shape->GetNext()->CacheID(); return shape->GetNext()->GetID(); } gmexport double ep_shape_set_uservar(double world_id, double body_id, double shape_id, double index, double value) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_uservar: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_uservar: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_set_uservar: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } int i = gm_cast<int>(index); if(i<0 || i>=GM_USERVARS) { epmain.Message(EP_MESSAGELEVEL_ERROR, "Can't set user variable of shape %lu of body %lu in world %lu, index is out of range.", shape->GetID(), body->GetID(), world->GetID()); return 0; } ((gmuserdata*)(shape->GetUserData()))->var[i] = value; return 1; } gmexport double ep_shape_get_uservar(double world_id, double body_id, double shape_id, double index) { ep_World *world; if((world = epmain.FindWorld(gm_cast<unsigned long>(world_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_uservar: World %lu doesn't exist.", gm_cast<unsigned long>(world_id)); return 0; } ep_Body *body; if((body = world->FindBody(gm_cast<unsigned long>(body_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_uservar: Body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(body_id), world->GetID()); return 0; } ep_Shape *shape; if((shape = body->FindShape(gm_cast<unsigned long>(shape_id)))==NULL) { epmain.Message(EP_MESSAGELEVEL_ERROR, "ep_shape_get_uservar: Shape %lu of body %lu doesn't exist in world %lu.", gm_cast<unsigned long>(shape_id), body->GetID(), world->GetID()); return 0; } int i = gm_cast<int>(index); if(i<0 || i>=GM_USERVARS) { epmain.Message(EP_MESSAGELEVEL_ERROR, "Can't get user variable of shape %lu of body %lu in world %lu, index is out of range.", shape->GetID(), body->GetID(), world->GetID()); return 0; } return ((gmuserdata*)(shape->GetUserData()))->var[i]; }
46.303901
191
0.732639
Bitl
7e6b737f169213de47acc271c58179e41354516f
1,806
cpp
C++
Homework/Homework 2/Code/Updated Version/hw02Professor.cpp
MorganBergen/Learning-CPP
a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b
[ "Unlicense" ]
null
null
null
Homework/Homework 2/Code/Updated Version/hw02Professor.cpp
MorganBergen/Learning-CPP
a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b
[ "Unlicense" ]
null
null
null
Homework/Homework 2/Code/Updated Version/hw02Professor.cpp
MorganBergen/Learning-CPP
a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <random> int main(){ const int PAPER = 1; const int SCISSOR = 2; const int ROCK = 3; std::random_devie rd; std::mt19937 prng(rd()); std::uniform_int_distribution<int> pcOption(1, 3); int playerChoice; int playerScore = 0; int totalPlays = 0; std::cout << "*** Rock, Paper, Scissors ***\n"; do { // clange-format off std::cout << "Choose your fate:\n" << "\t1. Paper\n" << "\t2. Scissor\n" << "\t3. Rock\n" << "\t#. Quit (any other number)\n\n" << "Enter the number of your choice: "; std::cin >> playerChoice; switch (<#expression#>) { case <#constant#>: <#statements#> break; default: break; } int pcChoice = pcOption(prng); bool playerWon = false; bool tieGame = false; std::cout << "Your opponent chose "; switch (pcChoice) { case PAPER: std::cout << "PAPER.\n"; break; case SCISSOR: std::cout << "SCISSOR.\n"; break; case ROCK: std::cout << "ROCK. \n"; break; default: break; } if (playerChoice == pcChoice) { tieGame = true; } else if ((playerChoice == PAPER && pcChoice == ROCK) || (playerChoice == SCISSOR && pcChoice == PAPER) playerChoice == ROCK && pcChoice == SCISSOR)){ } } }
26.558824
65
0.40144
MorganBergen
7e6c8ed8e094bb61ec48fc9783e786a6d6674b49
1,620
cpp
C++
85_traversals.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-02-07T19:50:36.000Z
2021-02-07T19:50:36.000Z
85_traversals.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
null
null
null
85_traversals.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-05-06T15:30:47.000Z
2021-05-06T15:30:47.000Z
// https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1 #include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left, *right; Node(int new_data) { data = new_data; left = right = NULL; } }; void print_inorder(struct Node *root) { if (root == NULL) return; print_inorder(root -> left); cout << root -> data << " "; print_inorder(root -> right); } void print_preorder(struct Node *root) { if (root == NULL) return; cout << root -> data << " "; print_preorder(root -> left); print_preorder(root -> right); } void print_postorder(struct Node *root) { if (root == NULL) return; print_postorder(root -> left); print_postorder(root -> right); cout << root -> data << " "; } int get_size(struct Node *root) { if (root == NULL) return 0; return 1 + get_size(root -> left) + get_size(root -> right); } int get_height(struct Node *root) { if (root == NULL) return 0; return 1 + max(get_height(root -> left), get_height(root -> right)); } int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct Node *root = new Node(1); root -> left = new Node(2); root -> right = new Node(3); root -> left -> left = new Node(4); root -> left -> right = new Node(5); cout << "Inorder: "; print_inorder(root); cout << endl; cout << "Preorder: "; print_preorder(root); cout << endl; cout << "Postorder: "; print_postorder(root); cout << endl; cout << "Size of tree: " << get_size(root) << endl; cout << "Height of tree: " << get_height(root) << endl; return 0; }
17.052632
88
0.603704
swapmali
7e6fc41ce5a29f91f9dbed457bc49f66d346d4b9
635
hpp
C++
requester/test/mock_request.hpp
amboar/pldm
d0405c3555427c03b231c8d52958f8689b3fa114
[ "Apache-2.0" ]
null
null
null
requester/test/mock_request.hpp
amboar/pldm
d0405c3555427c03b231c8d52958f8689b3fa114
[ "Apache-2.0" ]
null
null
null
requester/test/mock_request.hpp
amboar/pldm
d0405c3555427c03b231c8d52958f8689b3fa114
[ "Apache-2.0" ]
null
null
null
#pragma once #include "requester/request.hpp" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace pldm { namespace requester { class MockRequest : public RequestRetryTimer { public: MockRequest(int /*fd*/, mctp_eid_t /*eid*/, sdeventplus::Event& event, pldm::Request&& /*requestMsg*/, uint8_t numRetries, std::chrono::milliseconds responseTimeOut, int /*currentSendbuffSize*/, bool /*verbose*/) : RequestRetryTimer(event, numRetries, responseTimeOut) {} MOCK_METHOD(int, send, (), (const, override)); }; } // namespace requester } // namespace pldm
21.166667
74
0.651969
amboar
7e73cf8dc991dd09a15f4e679121438ec0cb76aa
33,335
cpp
C++
TAO/CIAO/tests/CIF/Receptacle/client.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/CIAO/tests/CIF/Receptacle/client.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/CIAO/tests/CIF/Receptacle/client.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: client.cpp 93359 2011-02-11 11:33:12Z mcorino $ #include "Common/CIF_Common.h" #include <vector> //============================================================ // connect //============================================================ ::Components::Cookie * connect (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet, bool multiple = false) { ::Components::Cookie_var ck; try { if (multiple) { ck = rec->connect ("use_multiple_foo", facet); } else { ck = rec->connect ("use_cif_foo", facet); } } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: InvalidName " "exception during connect\n")); } catch (const ::Components::InvalidConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: InvalidConnection " "exception during connect\n")); } catch (const ::Components::AlreadyConnected &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: AlreadyConnected " "exception during connect\n")); } catch (const ::Components::ExceededConnectionLimit &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: ExceededConnectionLimit " "exception during connect\n")); } return ck._retn (); } //============================================================ // disconnect //============================================================ ::CORBA::Object_ptr disconnect (::Components::Receptacles_ptr rec, ::Components::Cookie * ck, bool multiple = false) { ::CORBA::Object_var obj; try { if (multiple) { obj = rec->disconnect ("use_multiple_foo", ck); } else { obj = rec->disconnect ("use_cif_foo", ck); } } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: InvalidName " "exception during disconnect\n")); } catch (const ::Components::InvalidConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: InvalidConnection " "exception during disconnect\n")); } catch (const ::Components::CookieRequired &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: CookieRequired " "exception during disconnect\n")); } catch (const ::Components::NoConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: NoConnection " "exception during disconnect\n")); } return obj._retn (); } //============================================================ // test_connect_disconnect //============================================================ int test_connect_disconnect (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_connect_disconnect - " "Start test\n")); ::Components::Cookie_var ck = connect (rec, facet); ::CORBA::Object_var obj = disconnect (rec, ck.in ()); if (!::CORBA::is_nil (obj.in ())) { ACE_DEBUG ((LM_DEBUG, "Receptacle run_test - " "disconnect test passed !\n")); return 0; } return 1; } //============================================================ // test_connect_disconnect //============================================================ int test_cookie_required_exception (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_cookie_required_exception - " "Start test\n")); int ret = 0; ::Components::Cookie_var ck1 = connect (rec, facet, true); ::Components::Cookie_var ck2 = connect (rec, facet, true); ::CORBA::Object_var obj; try { obj = rec->disconnect ("use_multiple_foo", 0); ACE_ERROR ((LM_ERROR, "Receptacle test_cookie_required_exception - " "Error: No exception during disconnect\n")); ++ret; } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_cookie_required_exception - " "Error: InvalidName " "exception during disconnect\n")); ++ret; } catch (const ::Components::InvalidConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle test_cookie_required_exception - " "Error: InvalidConnection " "exception during disconnect\n")); ++ret; } catch (const ::Components::CookieRequired &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_cookie_required_exception - " "Received expected CookieRequired " "exception during disconnect\n")); } catch (const ::Components::NoConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle test_cookie_required_exception - " "Error: NoConnection " "exception during disconnect\n")); ++ret; } //need to disconnect properly obj = disconnect (rec, ck1.in (), true); obj = disconnect (rec, ck2.in (), true); return ret; } //============================================================ // test_invalid_name_exception //============================================================ int test_invalid_name_exception (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_invalid_name_exception - " "Start test\n")); ::Components::Cookie_var ck; try { ck = rec->connect ("use_cif_foo_invalid_name", facet); } catch (const ::Components::InvalidName &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_invalid_name_exception - " "Received expected InvalidName " "exception during connect\n")); } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_name_exception - " "Error: exception during connect\n")); return 1; } //connect an excisting receptacle ck = connect (rec, facet); //disconnect a wrong receptacle ::CORBA::Object_var obj; try { obj = rec->disconnect ("use_cif_foo_invalid_name", ck); } catch (const ::Components::InvalidName &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_invalid_name_exception - " "Received expected InvalidName " "exception during disconnect\n")); } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_name_exception - " "Error: exception during disconnect\n")); return 1; } return 0; } int test_invalid_connection_exception (::Components::Receptacles_ptr rec) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_invalid_connection_exception - " "Start test\n")); ::Components::Cookie_var ck; try { ck = rec->connect ("use_cif_foo", ::CORBA::Object::_nil ()); } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_connection_exception - " "Error: InvalidName " "exception during connect\n")); return 1; } catch (const ::Components::InvalidConnection &) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_connection_exception - " "Expected InvalidConnection " "exception received\n")); } catch (const ::Components::AlreadyConnected &) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_connection_exception - " "Error: AlreadyConnected " "exception during connect\n")); return 1; } catch (const ::Components::ExceededConnectionLimit &) { ACE_ERROR ((LM_ERROR, "Receptacle test_invalid_connection_exception - " "Error: ExceededConnectionLimit " "exception during connect\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_invalid_connection_exception - " "Test passed!\n")); return 0; } //============================================================ // test_already_connected_exception //============================================================ int test_already_connected_exception (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_already_connected_exception - " "Start test\n")); ::Components::Cookie_var ck; try { ck = rec->connect ("use_cif_foo", facet); } catch (const ::Components::AlreadyConnected &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_already_connected_exception - " "Received expected AlreadyConnected " "exception during connect\n")); } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_already_connected_exception - " "Error: exception during connect\n")); return 1; } return 0; } //============================================================ // test_get_connections //============================================================ #if !defined (CCM_LW) int test_get_connections (::Components::Receptacles_ptr rec) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_connections - " "Start test\n")); ::Components::ConnectionDescriptions_var descriptions; try { descriptions = rec->get_connections ("use_cif_foo"); } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_connections - " "Error: Received InvalidName " "exception during invocation of " "get_connections.\n")); return 1; } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_connections"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_connections - " "Error: exception during invocation of " "get_connections.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_connections - " "Test passed!\n")); // test invalid name exception during invocation of get_connections try { descriptions = rec->get_connections ("use_cif_foo_invalid_name"); } catch (const ::Components::InvalidName &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_connections - " "Received expected InvalidName " "exception during connect\n")); } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_connections - invalid name"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_connections - " "Error: exception during invocation of " "get_connections.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_connections - " "Invalid name test passed!\n")); return 0; } #endif //============================================================ // test_get_all_receptacles //============================================================ #if !defined (CCM_LW) int test_get_all_receptacles (::Components::Receptacles_ptr rec) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_receptacles - " "Start test\n")); ::Components::ReceptacleDescriptions_var descriptions; try { descriptions = rec->get_all_receptacles (); } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_all_receptacles"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_receptacles - " "Error: exception during invocation of " "get_all_receptacles.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_receptacles - " "Test passed!\n")); return 0; } #endif #if !defined (CCM_LW) int test_get_named_receptacles (::Components::Receptacles_ptr rec) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_receptacles - " "Start test\n")); ::Components::ReceptacleDescriptions_var descriptions; ::Components::NameList_var one_name; ACE_NEW_THROW_EX (one_name, ::Components::NameList, ::CORBA::NO_MEMORY ()); one_name->length (1); (*one_name)[0] = ::CORBA::string_dup ("use_cif_derived_foo"); try { descriptions = rec->get_named_receptacles (one_name); if (descriptions->length () != 1) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle test_get_named_receptacles one name - " "Error: Unexpected length recieived.\n"), 1); } } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles one name - " "Error: Received InvalidName " "exception during invocation of " "get_named_receptacles.\n")); return 1; } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_named_receptacles one name"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles one name - " "Error: exception during invocation of " "get_named_receptacles.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_receptacles - " "Test with one name passed!\n")); ::Components::NameList_var two_names; ACE_NEW_THROW_EX (two_names, ::Components::NameList, ::CORBA::NO_MEMORY ()); two_names->length (2); (*two_names)[0] = ::CORBA::string_dup ("use_cif_foo"); (*two_names)[1] = ::CORBA::string_dup ("use_cif_derived_foo"); try { descriptions = rec->get_named_receptacles (two_names); if (descriptions->length () != 2) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle test_get_named_receptacles two names - " "Error: Unexpected length recieived.\n"), 1); } } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles two names - " "Error: Received InvalidName " "exception during invocation of " "test_get_named_receptacles.\n")); return 1; } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_named_receptacles two names"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles two names - " "Error: exception during invocation of " "test_get_named_receptacles.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_receptacles - " "Test with two names passed!\n")); // test invalid name exception during invocation of get_named_receptacles ::Components::NameList_var invalid_names; ACE_NEW_THROW_EX (invalid_names, ::Components::NameList, ::CORBA::NO_MEMORY ()); invalid_names->length (2); (*invalid_names)[0] = ::CORBA::string_dup ("use_cif_foo"); (*invalid_names)[1] = ::CORBA::string_dup ("use_cif_foo_invalid_name"); try { descriptions = rec->get_named_receptacles (invalid_names); ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles - " "Error: didn't receive expected InvalidName " "exception.\n")); return 1; } catch (const ::Components::InvalidName &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_receptacles - " "Received expected InvalidName " "exception during connect\n")); } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_get_named_receptacles"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_receptacles - " "Error: exception during invocation of " "test_get_named_receptacles.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_receptacles - " "InvalidName test passed!\n")); return 0; } #endif int test_multiple_facets (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { std::vector < ::Components::Cookie_var > cookies; try { for (CORBA::ULong i = 0UL; i < 5; ++i) { ::Components::Cookie_var tmp = rec->connect ("use_multiple_foo", facet); cookies.push_back (tmp._retn ()); ACE_DEBUG ((LM_DEBUG, "Receptacle test_multiple_facets - " "%d receptacle(s) connected\n", i + 1)); } for (CORBA::ULong i = 0UL; i < 5; ++i) { CORBA::Object_var objref = disconnect (rec, cookies[i].in (), true); ACE_DEBUG ((LM_DEBUG, "Receptacle test_multiple_facets - " "Disconnected receptacle %d\n", i + 1)); } } catch (const ::Components::ExceededConnectionLimit &) { ACE_ERROR ((LM_ERROR, "Receptacle test_multiple_facets - " "Error: ExceededConnectionLimit " "exception caught\n")); return 1; } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("test_multiple_facets"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_multiple_facets - " "Error: exception during invocation of " "test_multiple_facets.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_multiple_facets - " "Test passed!\n")); return 0; } #if !defined (CCM_LW) int test_get_all_ports (::Components::CCMObject_ptr cmp) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Start test\n")); int ret = 0; try { ::Components::ComponentPortDescription_var cpd; cpd = cmp->get_all_ports (); //only the facets are available. ::Components::FacetDescriptions fds; fds = cpd->facets (); if (fds.length () != 0) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Did not receive the expected " "number of facets: " "expected <0> - received <%d>\n", fds.length ())); ++ret; } else { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Expected number of Facets found\n")); } #if !defined (CCM_NOEVENT) ::Components::ReceptacleDescriptions rds; rds = cpd->receptacles (); if (rds.length () != 3) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Did not receive the expected " "number of receptacles: " "expected <3> - received <%d>\n", rds.length ())); ++ret; } for (::CORBA::ULong i = 0UL; i < rds.length (); ++i) { if (::ACE_OS::strcmp (rds[i]->name (), "use_cif_foo") == 0 || ::ACE_OS::strcmp (rds[i]->name (), "use_multiple_foo") == 0 || ::ACE_OS::strcmp (rds[i]->name (), "use_cif_derived_foo") == 0) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Correct receptacledescription found <%C>\n", rds[i]->name ())); } else { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error Incorrect receptacledescription found <%C>\n", rds[i]->name ())); ++ret; } } ::Components::ConsumerDescriptions cds; cds = cpd->consumers (); if (cds.length () != 2) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Unexpected number of consumers found: " "expected <2> - received <%d>\n", cds.length ())); ++ret; } else { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Expected number of Consumers found\n")); } ::Components::EmitterDescriptions eds; eds = cpd->emitters (); if (eds.length () != 0) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Found Emitters while not " "configured\n")); ++ret; } else { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Expected number of Emitters found\n")); } ::Components::PublisherDescriptions pds; pds = cpd->publishers (); if (pds.length () != 0) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Found Publishers while not " "configured\n")); ++ret; } else { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Expected number of Publishers found\n")); } #endif } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Receptacle test_get_all_ports"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_ports - " "Error: Unexpected exception caught.\n")); return 1; } if (ret == 0) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_ports - " "Test passed\n")); } return ret; } #endif #if !defined (CCM_LW) int test_get_ccm_home (::Components::CCMObject_ptr cmp) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_ccm_home - " "Start test\n")); try { ::Components::CCMHome_var cif_home; cif_home = cmp->get_ccm_home (); if (::CORBA::is_nil (cif_home.in ())) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_ccm_home - " "Error: get_ccm_home returned a " "NIL pointer\n")); return 1; } } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Receptacle test_get_ccm_home"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_ccm_home - " "Error: Unexpected exception caught.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_ccm_home - " "Test passed\n")); return 0; } #endif #if !defined (CCM_LW) && !defined (CCM_NOEVENT) int test_get_all_consumers (::Components::CCMObject_ptr cmp) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_consumers - " "Start test\n")); try { ::Components::ConsumerDescriptions_var cds; cds = cmp->get_all_consumers (); if (cds->length () != 2) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle test_get_all_consumers - " "Error: get_all_consumers returned an " "unexpected number of consumers: " "expected <2> - received <%d>\n", cds->length ()), 1); } } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Receptacle test_get_all_consumers"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_all_consumers - " "Error: Unexpected exception caught.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_all_consumers - " "Test passed\n")); return 0; } #endif #if !defined (CCM_LW) && !defined (CCM_NOEVENT) int test_get_named_consumers (::Components::CCMObject_ptr cmp) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_consumers - " "Start test\n")); ::Components::ConsumerDescriptions_var cds; try { ::Components::NameList_var one_name; ACE_NEW_THROW_EX (one_name, ::Components::NameList, ::CORBA::NO_MEMORY ()); one_name->length (1); (*one_name)[0] = ::CORBA::string_dup ("consume_do_something_else"); cds = cmp->get_named_consumers (one_name); if (cds->length () != 1) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle test_get_named_consumers - " "Error: get_named_consumers returned an " "unexpected number of consumers: " "expected <1> - received <%d>\n", cds->length ()), 1); } } catch (const ::Components::InvalidName &) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_consumers - " "Error: InvalidName " "exception during get_named_consumers\n")); return 1; } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Receptacle test_get_named_consumers"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_consumers - " "Error: Unexpected exception caught.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_consumers - " "Test passed\n")); // Test InvalidName exception try { ::Components::NameList_var invalid_names; ACE_NEW_THROW_EX (invalid_names, ::Components::NameList, ::CORBA::NO_MEMORY ()); invalid_names->length (2); (*invalid_names)[0] = ::CORBA::string_dup ("consume_do_something"); (*invalid_names)[1] = ::CORBA::string_dup ("consume_do_something_invalid_name"); cds = cmp->get_named_consumers (invalid_names); ACE_ERROR_RETURN ((LM_ERROR, "Receptacle test_get_named_consumers - " "Error: No InvalidName exception received\n"), 1); } catch (const ::Components::InvalidName &) { ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_consumers - " "Received expected InvalidName " "exception during connect\n")); } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Receptacle test_get_named_consumers"); return 1; } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle test_get_named_consumers - " "Error: Unexpected exception caught.\n")); return 1; } ACE_DEBUG ((LM_DEBUG, "Receptacle test_get_named_consumers - " "InvalidName test passed!\n")); return 0; } #endif int run_test (::Components::Receptacles_ptr rec, ::CORBA::Object_ptr facet) { int ret = 0; try { ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_connect_disconnect (rec, facet); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_cookie_required_exception (rec, facet); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_invalid_name_exception (rec, facet); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_already_connected_exception (rec, facet); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_invalid_connection_exception (rec); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_multiple_facets (rec, facet); #if !defined (CCM_LW) ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_connections (rec); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_all_receptacles (rec); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_named_receptacles (rec); #endif } catch (...) { ACE_ERROR ((LM_ERROR, "Receptacle run_test - " "Error: Unknown " "exception during run_test\n")); ++ret; } return ret; } int ACE_TMAIN (int argc, ACE_TCHAR **argv) { CIF_Common cmd; int ret = 0; try { if (cmd.init (argc, argv) != 0) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle main - " "Error: Unable to initalize\n"), 1); } ::Components::Receptacles_var rec = cmd.get_receptacle_interface (); ::Components::Navigation_var nav = cmd.get_navigation_interface (); if (::CORBA::is_nil (rec.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle main - " "Error: Unable to get receptacles interface\n"), 1); } if (::CORBA::is_nil (nav.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle main - " "Error: Unable to get navigation interface\n"), 1); } ::CORBA::Object_var facet = nav->provide_facet ("provide_cif_foo"); if (::CORBA::is_nil (facet.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle main - " "Error: Unable to get Provide facet 'provide_cif_foo'\n"), 1); } ret = run_test (rec.in (), facet.in ()); #if !defined (CCM_LW) // tests on the component itself ::CORBA::Object_var obj = cmd.get_user_cmp (); if (::CORBA::is_nil (obj.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "Unable to get receptacle component\n"), 1); } ::Components::CCMObject_var cmp = ::Components::CCMObject::_narrow (obj); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_all_ports (cmp); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_ccm_home (cmp); #if !defined (CCM_NOEVENT) ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_all_consumers (cmp); ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ret += test_get_named_consumers (cmp); #endif #endif // one final test. ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); cmd.test_user_component (); cmd.shutdown (); } catch (const ::CORBA::Exception &ex) { ex._tao_print_exception ("Receptacle main - "); return 1; } catch (...) { ACE_ERROR_RETURN ((LM_ERROR, "Receptacle main - " "Error: Caught unknown exception\n"), 1); } ACE_DEBUG ((LM_DEBUG, "\n\n===============================\n")); ACE_DEBUG ((LM_DEBUG, "SUMMARY : ")); if (ret != 0) { ACE_ERROR ((LM_ERROR, "Receptacle main - " " %d error(s) found during tests.\n\n", ret)); } else { ACE_ERROR ((LM_ERROR, "Receptacle main - " " No problems found during tests.\n\n")); } return ret; }
32.713445
89
0.508325
cflowe
7e752c5be62ec32fe6f9b85f1f7e1f8a6add85fb
1,730
cpp
C++
1199 Round #576 (Div.2)/F - Rectangle Painting 1.cpp
Jatin-Nagpal/CF-Complete
2381ab746982676db3610d66ab33d4177f2d555f
[ "MIT" ]
1
2019-08-17T05:35:30.000Z
2019-08-17T05:35:30.000Z
1199 Round #576 (Div.2)/F - Rectangle Painting 1.cpp
Jatin-Nagpal/CF-Complete
2381ab746982676db3610d66ab33d4177f2d555f
[ "MIT" ]
null
null
null
1199 Round #576 (Div.2)/F - Rectangle Painting 1.cpp
Jatin-Nagpal/CF-Complete
2381ab746982676db3610d66ab33d4177f2d555f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ff first #define ss second using namespace std; #define MP make_pair #define PB push_back // #define ll long long #define int long long #define f(i,x,n) for(int i=x;i<n;i++) #define ld long double #define mod 1000000007 int a[51][51]; string s[51]; int n,ans; int dp[51][51][51][51]; int dp2[51][51]; inline int sum(int stx,int sty,int enx,int eny) { return dp2[enx][eny] -dp2[stx-1][eny] -dp2[enx][sty-1] +dp2[stx-1][sty-1]; } int dfs(int stx,int sty,int enx,int eny) { // cout<<stx<<" "<<sty<<" "<<enx<<" "<<eny<<'\n'; int &an=dp[stx][sty][enx][eny]; if(an!=-1) return an; if( dp2[enx][eny] -dp2[stx-1][eny] -dp2[enx][sty-1] +dp2[stx-1][sty-1] ==0) return an=0; if(stx>enx||sty>eny) return an=0; if(stx==enx&&sty==eny) return an=a[stx][sty]; if(sum(stx,sty,stx,eny)==0) return an=dfs(stx+1,sty,enx,eny); if(sum(stx,sty,enx,sty)==0) return an=dfs(stx,sty+1,enx,eny); if(sum(enx,sty,enx,eny)==0) return an=dfs(stx,sty,enx-1,eny); if(sum(stx,eny,enx,eny)==0) return an=dfs(stx,sty,enx,eny-1); int ret=min( max(enx-stx+1,eny-sty+1),sum(stx,sty,enx,eny)); int tmp=0; f(i,stx,enx) { ret=min(ret,dfs(stx,sty,i,eny) +dfs(i+1,sty,enx,eny) ); } f(i,sty,eny) { ret=min(ret,dfs(stx,sty,enx,i) +dfs(stx,i+1,enx,eny) ); } return an=ret; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>n; ans=n; f(i,0,51) f(j,0,51) f(k,0,51) f(l,0,51) dp[i][j][k][l]=-1; f(i,0,n) cin>>s[i]; f(i,1,n+1) { f(j,1,n+1) { if(s[i-1][j-1]=='#') a[i][j]=1; } } f(i,1,n+1) { f(j,1,n+1) { dp2[i][j]=dp2[i-1][j]+dp2[i][j-1]-dp2[i-1][j-1]; if(a[i][j]==1) dp2[i][j]++; } } cout<<dfs(1,1,n,n)<<endl; return 0; }
20.116279
77
0.573988
Jatin-Nagpal
7e7791ace9851d83f2066fe1ffb8462b8af17cb0
1,599
hpp
C++
src/include/cpp_playground/delayed_call.hpp
rxcompile/cpp_playground
63cd54f18e15415f779d9a6d08c5dac8ba33e3be
[ "MIT" ]
null
null
null
src/include/cpp_playground/delayed_call.hpp
rxcompile/cpp_playground
63cd54f18e15415f779d9a6d08c5dac8ba33e3be
[ "MIT" ]
null
null
null
src/include/cpp_playground/delayed_call.hpp
rxcompile/cpp_playground
63cd54f18e15415f779d9a6d08c5dac8ba33e3be
[ "MIT" ]
null
null
null
#pragma once #include "cpp_playground/python_container.hpp" #include "cpp_playground/function_traits.hpp" #include <vector> #include <functional> namespace CppTest { template <typename TRet, typename... TArgs> class DelayedCall { public: DelayedCall(std::function<TRet(TArgs...)> fn, Container &data) : args(parseArgs(data, std::index_sequence_for<TArgs...>())), func(fn) { } auto call() { return callInternal(std::index_sequence_for<TArgs...>()); } private: template <typename TArg, size_t idx> TArg parseArg(Container &data) { //TArg a = std::any_cast<TArg>(data[idx]); TArg a = data[idx]; return a; } template <size_t... S> auto parseArgs(Container &data, std::index_sequence<S...>) { return std::make_tuple(parseArg<typename function_traits<decltype(func)>::template arg<S>::type, S>(data)...); } template <size_t... S> auto callInternal(std::index_sequence<S...>) { return func(std::get<S>(args)...); } private: std::tuple<TArgs...> args; std::function<TRet(TArgs...)> func; }; template <typename TRet, typename... TArgs> TRet delayedCall(std::function<TRet(TArgs...)> func, Container &data) { return DelayedCall<TRet, TArgs...>(func, data).call(); } template <typename M, typename TRet, typename... TArgs> TRet delayedCall(M &ptr, TRet (M::*func)(TArgs...), Container &data) { std::function<TRet(TArgs...)> f = [&ptr, func](TArgs... args) { return (ptr.*func)(args...); }; return DelayedCall<TRet, TArgs...>(f, data).call(); } }
24.984375
118
0.627892
rxcompile
7e7bf634c4566a32456aefbb6d5e6ac06ea721cf
683
cpp
C++
mainwindow.cpp
stweise/rico-cluster-qt
7b712319de1b8feb53172b089867038c977c96d5
[ "BSD-3-Clause" ]
1
2020-07-12T19:33:25.000Z
2020-07-12T19:33:25.000Z
mainwindow.cpp
stweise/rico-qt
7b712319de1b8feb53172b089867038c977c96d5
[ "BSD-3-Clause" ]
1
2020-11-19T15:56:23.000Z
2020-11-29T08:54:29.000Z
mainwindow.cpp
stweise/rico-qt
7b712319de1b8feb53172b089867038c977c96d5
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause #include "mainwindow.h" #include "./ui_mainwindow.h" #include "graphicsscene.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); scene = new GraphicsScene(this); ui->graphicsView->setScene(scene); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionSave_triggered() { scene->save(); } void MainWindow::on_actionLoad_triggered() { scene->load(); } void MainWindow::on_actionPrint_triggered() { scene->print(); } void MainWindow::on_actionSave_as_triggered() { scene->saveAs(); } void MainWindow::on_actionExport_triggered() { scene->exportToDot(); }
27.32
70
0.727672
stweise
7e7c2a02776b994cb11e1ce65f4f15343f1cbfe1
35,191
cpp
C++
src/VAC/View3D.cpp
CELLINKAB/vpaint
83f66645407a1467a450bd42bc3d62038bf7d11a
[ "ECL-2.0", "Apache-2.0" ]
1
2021-09-10T15:10:30.000Z
2021-09-10T15:10:30.000Z
src/VAC/View3D.cpp
CELLINKAB/vpaint
83f66645407a1467a450bd42bc3d62038bf7d11a
[ "ECL-2.0", "Apache-2.0" ]
1
2021-11-24T11:21:05.000Z
2021-11-24T11:21:05.000Z
src/VAC/View3D.cpp
CELLINKAB/vpaint
83f66645407a1467a450bd42bc3d62038bf7d11a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright (C) 2012-2019 The VPaint Developers. // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT // // 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 <math.h> #include <algorithm> #include "View3D.h" #include "Scene.h" #include "Timeline.h" #include <QtDebug> #include "Global.h" #include "View.h" #include "Background/Background.h" #include "Background/BackgroundRenderer.h" #include "VectorAnimationComplex/VAC.h" #include "VectorAnimationComplex/KeyCell.h" #include "VectorAnimationComplex/InbetweenCell.h" #include "VectorAnimationComplex/InbetweenEdge.h" // GLU was removed from Qt in version 4.8 // TODO: remove this dependancy and code it myself #ifdef Q_OS_MAC # include <OpenGL/glu.h> #else # include <GL/glu.h> #endif // define mouse actions #define DRAW_ACTION 10 #define SELECT_ACTION 20 #define ADDSELECT_ACTION 21 #define DESELECT_ACTION 22 #define TOGGLESELECT_ACTION 23 #define DESELECTALL_ACTION 24 View3D::View3D(VPaint::Scene *scene, QWidget *parent) : GLWidget(parent, false), // Difference from View here scene_(scene), displayedTimes_(), pickingImg_(0), //frame_(0), vac_(0) { // Make renderers // XXX Make it work with layers //Background * bg = scene_->background(); //backgroundRenderers_[bg] = new BackgroundRenderer(bg, context(), this); cameraTravellingIsEnabled_ = true; drawingIsEnable_ = false; // behave as a separate window this->setWindowFlags(Qt::Window); resize(600,600); setWindowTitle("3D View [Beta]"); // Redraw when moving the camera //connect(this, SIGNAL(viewIsGoingToChange(int, int)), this, SLOT(updatePicking())); ////connect(this, SIGNAL(viewIsGoingToChange(int, int)), this, SLOT(updateHighlightedObject(int, int))); //connect(this, SIGNAL(viewIsGoingToChange(int, int)), this, SLOT(update())); ////connect(this, SIGNAL(viewIsBeingChanged(int, int)), this, SLOT(updatePicking())); ////connect(this, SIGNAL(viewIsBeingChanged(int, int)), this, SLOT(updateHighlightedObject(int, int))); connect(this, SIGNAL(viewIsBeingChanged(int, int)), this, SLOT(update())); //connect(this, SIGNAL(viewChanged(int, int)), this, SLOT(updatePicking())); //connect(this, SIGNAL(viewChanged(int, int)), this, SLOT(updateHighlightedObject(int, int))); connect(this, SIGNAL(viewChanged(int, int)), this, SLOT(update())); //connect(global(),SIGNAL(keyboardModifiersChanged()),this,SLOT(handleNewKeyboardModifiers())); connect(global()->timeline(), SIGNAL(playingWindowChanged()), this, SLOT(update())); } View3D::~View3D() { deletePicking(); } View3DSettings * View3D::settings() { return &viewSettings_; } void View3D::closeEvent(QCloseEvent * event) { emit closed(); event->accept(); } void View3D::keyPressEvent(QKeyEvent *event) { GLWidget::keyPressEvent(event); // Nothing changed in the scene, but keyboard state can affect // the display settings, hence should redraw the scene. Pass the // event to multiview to do this if(!event->isAccepted()) event->ignore(); } View3D::MouseEvent View3D::mouseEvent() const { MouseEvent me; me.x = mouse_PressEvent_X_; me.y = mouse_PressEvent_Y_; me.left = mouse_LeftButton_; me.mid = mouse_MidButton_; me.right = mouse_RightButton_; me.alt = mouse_AltWasDown_; me.control = mouse_ControlWasDown_; me.shift = mouse_ShiftWasDown_; return me; } void View3D::MoveEvent(double x, double y) { bool hasChanged = updateHighlightedObject(x, y); if(hasChanged) { if(highlightedObject_.isNull()) scene_->setNoHoveredObject(); else scene_->setHoveredObject( //Timeline::time(highlightedObject_.time()), Time(), // ignored by VAC anyway... highlightedObject_.index(), highlightedObject_.id()); } } int View3D::decideClicAction() { if(mouse_LeftButton_) { if(!mouse_AltWasDown_ && !mouse_ControlWasDown_ && !mouse_ShiftWasDown_) { if(highlightedObject_.isNull()) return DESELECTALL_ACTION; else return SELECT_ACTION; } if(!mouse_AltWasDown_ && !mouse_ControlWasDown_ && mouse_ShiftWasDown_) { return ADDSELECT_ACTION; } if(mouse_AltWasDown_ && !mouse_ControlWasDown_ && !mouse_ShiftWasDown_) { return DESELECT_ACTION; } if(mouse_AltWasDown_ && !mouse_ControlWasDown_ && mouse_ShiftWasDown_) { return TOGGLESELECT_ACTION; } } return GLWidget::decideClicAction(); } int View3D::decidePMRAction() { return GLWidget::decidePMRAction(); } void View3D::ClicEvent(int action, double x, double y) { if(action==SELECT_ACTION) { if(!highlightedObject_.isNull()) { scene_->deselectAll(); // deselect at all // times. different from 2D behaviour scene_->select(Time() /*Timeline::time(highlightedObject_.time())*/, highlightedObject_.index(), highlightedObject_.id()); } } else if(action==DESELECTALL_ACTION) { // same here: deselect at all times // different from 2D version scene_->deselectAll(); } else if(action==ADDSELECT_ACTION) { if(!highlightedObject_.isNull()) { scene_->select(Time()/*Timeline::time(highlightedObject_.time())*/, highlightedObject_.index(), highlightedObject_.id()); } } else if(action==DESELECT_ACTION) { if(!highlightedObject_.isNull()) { scene_->deselect(Time()/*Timeline::time(highlightedObject_.time())*/, highlightedObject_.index(), highlightedObject_.id()); } } else if(action==TOGGLESELECT_ACTION) { if(!highlightedObject_.isNull()) { scene_->toggle(Time()/*Timeline::time(highlightedObject_.time())*/, highlightedObject_.index(), highlightedObject_.id()); } } GLWidget::ClicEvent(action, x, y); } void View3D::PMRPressEvent(int action, double x, double y) { GLWidget::PMRPressEvent(action, x, y); } void View3D::PMRMoveEvent(int action, double x, double y) { GLWidget::PMRMoveEvent(action, x, y); } void View3D::PMRReleaseEvent(int action, double x, double y) { GLWidget::PMRReleaseEvent(action, x, y); } /*********************************************************** * DRAWING */ namespace { /* void drawSphere(double r, int lats, int longs) { int i, j; for(i = 0; i <= lats; i++) { double lat0 = M_PI * (-0.5 + (double) (i - 1) / lats); double z0 = sin(lat0); double zr0 = cos(lat0); double lat1 = M_PI * (-0.5 + (double) i / lats); double z1 = sin(lat1); double zr1 = cos(lat1); glBegin(GL_QUAD_STRIP); for(j = 0; j <= longs; j++) { double lng = 2 * M_PI * (double) (j - 1) / longs; double x = cos(lng); double y = sin(lng); glNormal3f(x * zr0, y * zr0, z0); glVertex3f(r * x * zr0, r * y * zr0, r * z0); glNormal3f(x * zr1, y * zr1, z1); glVertex3f(r * x * zr1, r * y * zr1, r * z1); } glEnd(); } } */ } int View3D::activeFrame() const { return std::floor(activeTime().floatTime()); } Time View3D::activeTime() const { return global()->activeTime(); // XXX should refactor this } void View3D::drawBackground_(Background * background, double t) { // Get canvas boundary double x1 = scene_->left(); double y1 = scene_->top(); double w = scene_->width(); double h = scene_->height(); double x2 = x1 + w; double y2 = y1 + h; // Convert to 3D coords x1 = viewSettings_.xFromX2D(x1); x2 = viewSettings_.xFromX2D(x2); y1 = viewSettings_.yFromY2D(y1); y2 = viewSettings_.yFromY2D(y2); // Draw background backgroundRenderers_[background]->draw( Time(t).frame(), true, // = showCanvas x1, y1, w, h, 0, 0, 0, 0); } // XXX Refactor this: move it to a CanvasRenderer class // Right now, this codes duplicates part of Scene::drawCanvas() void View3D::drawCanvas_() { // Get canvas boundary double x1 = scene_->left(); double y1 = scene_->top(); double w = scene_->width(); double h = scene_->height(); double x2 = x1 + w; double y2 = y1 - h; // Convert to 3D coords x1 = viewSettings_.xFromX2D(x1); x2 = viewSettings_.xFromX2D(x2); y1 = viewSettings_.yFromY2D(y1); y2 = viewSettings_.yFromY2D(y2); // Draw quad boundary glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_QUADS); { glColor4f(0.0, 0.0, 0.0, 1.0); glVertex2d(x1, y1); glVertex2d(x2, y1); glVertex2d(x2, y2); glVertex2d(x1, y2); } glEnd(); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); } void View3D::drawScene() { drawSceneDelegate_(global()->activeTime()); } void View3D::drawSceneDelegate_(Time activeTime) { using namespace VectorAnimationComplex; // Get VAC VAC * vac = scene_->activeVAC(); if (!vac) { return; } // Get t-position of camera eye to determine back-to-front order double zEye = camera_.position()[2]; double tEye = - zEye / viewSettings_.timeScale(); if(viewSettings_.cameraFollowActiveTime()) tEye += activeTime.floatTime(); // Collect all items to draw bool drawAllFrames = viewSettings_.drawAllFrames(); bool drawKeyCells = drawAllFrames || viewSettings_.drawKeyCells(); bool drawInbetweenCells = viewSettings_.drawInbetweenCells(); bool drawCurrentFrame = viewSettings_.drawCurrentFrame(); bool drawCurrentFrameAsTopology = viewSettings_.drawCurrentFrameAsTopology(); bool drawOtherFramesAsTopology = viewSettings_.drawFramesAsTopology(); DrawMode currentFrameDrawMode = drawCurrentFrameAsTopology ? DrawMode::DrawTopology : DrawMode::Draw; DrawMode otherFramesDrawMode = drawOtherFramesAsTopology ? DrawMode::DrawTopology : DrawMode::Draw; drawItems_.clear(); if (viewSettings_.drawTimePlane()) { drawItems_.push_back({nullptr, DrawMode::DrawCanvas, activeTime, activeTime}); } const ZOrderedCells & cells = vac->zOrdering(); for(auto it = cells.cbegin(); it != cells.cend(); ++it) { if (KeyCell * kc = (*it)->toKeyCell()) { if (drawCurrentFrame && kc->exists(activeTime)) { drawItems_.push_back({kc, currentFrameDrawMode, activeTime, activeTime}); } else if (drawKeyCells) { drawItems_.push_back({kc, otherFramesDrawMode, kc->time(), kc->time()}); } } else if (InbetweenCell * ic = (*it)->toInbetweenCell()) { Time t1 = ic->beforeTime(); Time t2 = ic->afterTime(); if (drawCurrentFrame && t1 < activeTime && activeTime < t2) { // Note: (t1 < activeTime && activeTime < t2) is equivalent to // ic->exists(activeTime), but avoid computing ic->beforeTime() // and ic->afterTime() again. drawItems_.push_back({ic, currentFrameDrawMode, activeTime, activeTime}); } if (drawAllFrames) { // Note: unlike for key cells, this block is not an "else if" // because ic might exist both at activeTime and other frames. int f1 = std::floor(t1.floatTime()); int f2 = std::ceil(t2.floatTime()); for (int f = f1 + 1; f < f2; ++f) { Time t = f; if (!drawCurrentFrame || t != activeTime) { drawItems_.push_back({ic, otherFramesDrawMode, t, t}); } } } if (drawInbetweenCells) { double t1f = t1.floatTime(); double t2f = t2.floatTime(); int f1 = std::floor(t1f); int f2 = std::ceil(t2f); // Cut the inbetween cell into one-frame-long sections for (int f = f1; f < f2; ++f) { Time t1_ = (f == f1) ? t1 : f; Time t2_ = (f == f2 - 1) ? t2 : f + 1; if (drawCurrentFrame && t1_ < activeTime && activeTime < t2_) { // Cut at current frame drawItems_.push_back({ic, DrawMode::Draw3D, t1_, activeTime}); t1_ = activeTime; } drawItems_.push_back({ic, DrawMode::Draw3D, t1_, t2_}); } } } } // Sort back to front, using stable_sort to preserve z-ordering. // // time: ---------------.-------------------> // tEye // // order: -------------->.<------------------ // (1) (3) (2) // // We draw items in this order: // - First, items completely before tEye (orderCategory = 1) // - Then, items completely after tEye (orderCategory = 2) // - Finally, items whose timespan include tEye (orderCategory = 3) // // For items belonging to the same order category then: // - We define their average time u = (t1+t2)/2 // - If orderCategory = 1, we draw items in order of increasing u // - Otherwise, we draw items in order of decreasing u // std::stable_sort( drawItems_.begin(), drawItems_.end(), [tEye](const DrawItem& i1, const DrawItem& i2) { double t11 = i1.t1.floatTime(); double t12 = i1.t2.floatTime(); double t21 = i2.t1.floatTime(); double t22 = i2.t2.floatTime(); int orderCategory1 = (t12 < tEye) ? 1 : ((tEye < t11) ? 2 : 3); int orderCategory2 = (t22 < tEye) ? 1 : ((tEye < t21) ? 2 : 3); if (orderCategory1 == orderCategory2) { double u1 = 0.5 * (t11 + t12); double u2 = 0.5 * (t21 + t22); return (orderCategory1 == 1) ? (u1 < u2) : (u2 < u1); } else { return orderCategory1 < orderCategory2; } }); // Set 2D settings from 3D settings ViewSettings view2DSettings = global()->activeView()->viewSettings(); view2DSettings.setScreenRelative(false); view2DSettings.setVertexTopologySize(viewSettings_.vertexTopologySize()); view2DSettings.setEdgeTopologyWidth(viewSettings_.edgeTopologyWidth()); view2DSettings.setDrawTopologyFaces(viewSettings_.drawTopologyFaces()); // Disable lighting, depth testing and writing to depth buffer glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDepthMask(false); // Scale and translate view double s = viewSettings_.spaceScale(); glPushMatrix(); glScaled(s,s,s); if(viewSettings_.cameraFollowActiveTime()) glTranslated(0,0,-viewSettings_.zFromT(activeTime)); // Draw all items bool drawAsMesh = viewSettings_.drawAsMesh(); double opacity = viewSettings_.opacity(); for (const DrawItem& item: drawItems_) { if (item.mode == DrawMode::Draw3D) { double t1 = item.t1.floatTime(); double t2 = item.t2.floatTime(); double z1 = viewSettings_.zFromT(t1); double z2 = viewSettings_.zFromT(t2); GLdouble clipEquation1[4] = { 0.0, 0.0, -1.0, z1}; GLdouble clipEquation2[4] = { 0.0, 0.0, 1.0, -z2}; glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); glClipPlane(GL_CLIP_PLANE0, clipEquation1); glClipPlane(GL_CLIP_PLANE1, clipEquation2); if (item.cell->toInbetweenVertex()) { glColor4d(0.0, 0.0, 0.0, opacity); item.cell->draw3D(viewSettings_); } else if (item.cell->toInbetweenEdge()) { glColor4d(1.0, 0.5, 0.5, opacity); if(drawAsMesh) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth(2); // TODO: make this a view settings } item.cell->draw3D(viewSettings_); if(drawAsMesh) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glLineWidth(1); } } glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); } else { double t = item.t1.floatTime(); glPushMatrix(); glScaled(1.0, -1.0, 1.0); glTranslated(0.0, 0.0, viewSettings_.zFromT(t)); if (item.mode == DrawMode::Draw) { item.cell->draw(t, view2DSettings); } else if (item.mode == DrawMode::DrawTopology) { item.cell->drawTopology(t, view2DSettings); } else if (item.mode == DrawMode::DrawCanvas) { drawCanvas_(); // TODO: layer background? } glPopMatrix(); } } // Restore state // // Note: should we also re-enable GL_DEPTH_TEST and/or GL_LIGHTING, or is // enabling these the responsability of any drawing code that need it? // glDepthMask(true); glPopMatrix(); } /*********************************************************** * PICKING */ void View3D::drawPick() { // TODO } bool View3D::updateHighlightedObject(int x, int y) { if(!pickingImg_) return false; // otherwise the scene will keep updating Picking::Object old = highlightedObject_; if(x<0 || x>=pickingWidth_ || y<0 || y>=pickingHeight_) { highlightedObject_ = Picking::Object(); } else { highlightedObject_ = getCloserObject(x, y); } return !(highlightedObject_ == old); } uchar * View3D::pickingImg(int x, int y) { int k = 4*( (pickingHeight_ - y - 1)*pickingWidth_ + x); return &pickingImg_[k]; } Picking::Object View3D::getCloserObject(int x, int y) { Picking::Object noObject; if(!pickingImg_) return noObject; int leftBorderDist = x; int rightBorderDist = pickingWidth_-1-x; int topBorderDist = y; int bottomBorderDist = pickingHeight_-1-y; int borderDist = qMin(qMin(leftBorderDist, rightBorderDist), qMin(topBorderDist, bottomBorderDist)); if(borderDist<0) return noObject; int D = 10; if(borderDist < D) D = borderDist; for(int d=0; d<=D; d++) { if(d==0) { uchar * p = pickingImg(x,y); uchar r=p[0], g=p[1], b=p[2]; if(r!=255 || g!=255 || b!=255) return Picking::objectFromRGB(r,g,b); } else { // top row for(int varX=x-d; varX<=x+d; varX++) { uchar * p = pickingImg(varX,y-d); uchar r=p[0], g=p[1], b=p[2]; if(r!=255 || g!=255 || b!=255) return Picking::objectFromRGB(r,g,b); } // bottom row for(int varX=x-d; varX<=x+d; varX++) { uchar * p = pickingImg(varX,y+d); uchar r=p[0], g=p[1], b=p[2]; if(r!=255 || g!=255 || b!=255) return Picking::objectFromRGB(r,g,b); } // left column for(int varY=y-d; varY<=y+d; varY++) { uchar * p = pickingImg(x-d,varY); uchar r=p[0], g=p[1], b=p[2]; if(r!=255 || g!=255 || b!=255) return Picking::objectFromRGB(r,g,b); } // right column for(int varY=y-d; varY<=y+d; varY++) { uchar * p = pickingImg(x+d,varY); uchar r=p[0], g=p[1], b=p[2]; if(r!=255 || g!=255 || b!=255) return Picking::objectFromRGB(r,g,b); } } } // no object within the range return noObject; } void View3D::deletePicking() { if(pickingImg_) { gl_fbo_->glDeleteFramebuffers(1, &fboId_); gl_fbo_->glDeleteRenderbuffers(1, &rboId_); glDeleteTextures(1, &textureId_); highlightedObject_ = Picking::Object(); delete[] pickingImg_; pickingImg_ = 0; pickingWidth_ = 0; pickingHeight_ = 0; } } void View3D::newPicking() { pickingWidth_ = width(); pickingHeight_ = height(); pickingImg_ = new uchar[4 * pickingWidth_ * pickingHeight_]; // code adapted from http://www.songho.ca/opengl/gl_fbo.html // create a texture object glGenTextures(1, &textureId_); glBindTexture(GL_TEXTURE_2D, textureId_); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, pickingWidth_, pickingHeight_, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); // create a renderbuffer object to store depth info gl_fbo_->glGenRenderbuffers(1, &rboId_); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, rboId_); gl_fbo_->glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, pickingWidth_, pickingHeight_); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, 0); // create a framebuffer object gl_fbo_->glGenFramebuffers(1, &fboId_); gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, fboId_); // attach the texture to FBO color attachment point gl_fbo_->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId_, 0); // attach the renderbuffer to depth attachment point gl_fbo_->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboId_); // check FBO status GLenum status = gl_fbo_->glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) { qDebug() << "ERROR void View::newPicking()" << "FBO status != GL_FRAMEBUFFER_COMPLETE"; return; } // switch back to window-system-provided framebuffer gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject()); } void View3D::updatePicking() { /* Picking (and thus editing) in the 3D View isn't supported. This code is * just an example on how this function would look like. We would have to * implement View3D::drawPick(). * // Make this widget's rendering context the current OpenGL context makeCurrent(); // get the viewport size, allocate memory if necessary if( !(width()>0) || !(height()>0)) { deletePicking(); return; } else if( pickingImg_ && (pickingWidth_ == width()) && (pickingHeight_ == height())) { // necessary objects already created: do nothing } else { deletePicking(); newPicking(); } // set rendering destination to FBO gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, fboId_); // clear buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear buffers glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Should we setup other things? (e.g., disabling antialiasing) // Seems to work as is. If issues, check GLWidget::initilizeGL() // Set viewport GLint oldViewport[4]; glGetIntegerv(GL_VIEWPORT, oldViewport); glViewport(0, 0, pickingWidth_, pickingHeight_); // Setup camera position and orientation setCameraPositionAndOrientation(); // draw the picking drawPick3D(); // Restore viewport glViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); // unbind FBO gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject()); // extract the texture info from GPU to RAM glBindTexture(GL_TEXTURE_2D, textureId_); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pickingImg_); glBindTexture(GL_TEXTURE_2D, 0); */ } QImage View3D::drawToImage(int imgW, int imgH) { return drawToImage(activeTime(), imgW, imgH); } namespace { void imageCleanupHandler(void * info) { uchar * img = reinterpret_cast<uchar*>(info); delete[] img; } } QImage View3D::drawToImage(Time t, int IMG_SIZE_X, int IMG_SIZE_Y) { // TODO: factorize this code with View::drawToImage // Make this widget's rendering context the current OpenGL context makeCurrent(); // ------------ Create multisample FBO -------------------- GLuint ms_fboId; GLuint ms_ColorBufferId; GLuint ms_DepthBufferId; GLint ms_samples; // Maximum supported samples glGetIntegerv(GL_MAX_SAMPLES, &ms_samples); // Create FBO gl_fbo_->glGenFramebuffers(1, &ms_fboId); gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, ms_fboId); // Create multisample color buffer gl_fbo_->glGenRenderbuffers(1, &ms_ColorBufferId); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, ms_ColorBufferId); gl_fbo_->glRenderbufferStorageMultisample(GL_RENDERBUFFER, ms_samples, GL_RGBA8, IMG_SIZE_X, IMG_SIZE_Y); // Create multisample depth buffer gl_fbo_->glGenRenderbuffers(1, &ms_DepthBufferId); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, ms_DepthBufferId); gl_fbo_->glRenderbufferStorageMultisample(GL_RENDERBUFFER, ms_samples, GL_DEPTH_COMPONENT24, IMG_SIZE_X, IMG_SIZE_Y); // Attach render buffers to FBO gl_fbo_->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, ms_ColorBufferId); gl_fbo_->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, ms_DepthBufferId); // Check FBO status GLenum ms_status = gl_fbo_->glCheckFramebufferStatus(GL_FRAMEBUFFER); if(ms_status != GL_FRAMEBUFFER_COMPLETE) { qDebug() << "Error: FBO ms_status != GL_FRAMEBUFFER_COMPLETE"; return QImage(); } // ------------ Create standard FBO -------------------- GLuint fboId; GLuint textureId; GLuint rboId; // Create FBO gl_fbo_->glGenFramebuffers(1, &fboId); gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, fboId); // Create color texture glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, IMG_SIZE_X, IMG_SIZE_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); // Create depth buffer gl_fbo_->glGenRenderbuffers(1, &rboId); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, rboId); gl_fbo_->glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, IMG_SIZE_X, IMG_SIZE_Y); gl_fbo_->glBindRenderbuffer(GL_RENDERBUFFER, 0); // Attach render buffers / textures to FBO gl_fbo_->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0); gl_fbo_->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboId); // Check FBO status GLenum status = gl_fbo_->glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) { qDebug() << "Error: FBO status != GL_FRAMEBUFFER_COMPLETE"; return QImage(); } // ------------ Render scene to multisample FBO -------------------- // Bind FBO gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, ms_fboId); // Set viewport GLint oldViewport[4]; glGetIntegerv(GL_VIEWPORT, oldViewport); glViewport(0, 0, IMG_SIZE_X, IMG_SIZE_Y); // XXX is this necessary? (copied from paintGL) glDepthMask(GL_TRUE); // Clear the window and buffers glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Initialize the view and lighting // This is like setCameraPositionAndOrientation(), but with a slightly // different gluPerspective to account for the new size glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(isOrtho_) { double h = 2 * camera_.r() * tan(camera_.fovy()/2.0); double ratio = h / IMG_SIZE_Y; double w = IMG_SIZE_X * ratio; glOrtho (-0.5*w, 0.5*w, -0.5*h, 0.5*h, 0, 100); } else { gluPerspective(camera_.fovy() * 180 / M_PI, (double) IMG_SIZE_X / (double) IMG_SIZE_Y, 0.1, 100); } glScaled(1, -1, 1); // Invert Y-axis for compatibility with QImage Eigen::Vector3d pos = camera_.position(); Eigen::Vector3d focus = camera_.focusPoint(); Eigen::Vector3d up = camera_.upDirection(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(pos[0], pos[1], pos[2], focus[0], focus[1], focus[2], up[0], up[1], up[2]); setLighting(); setMaterial(material_); glEnable(GL_COLOR_MATERIAL); // Draw scene drawSceneDelegate_(t); // Restore viewport glViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); // Unbind FBO gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject()); // ------ Blit multisample FBO to standard FBO --------- // Bind multisample FBO for reading gl_fbo_->glBindFramebuffer(GL_READ_FRAMEBUFFER, ms_fboId); // Bind standard FBO for drawing gl_fbo_->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); // Blit gl_fbo_->glBlitFramebuffer(0, 0, IMG_SIZE_X, IMG_SIZE_Y, 0, 0, IMG_SIZE_X, IMG_SIZE_Y, GL_COLOR_BUFFER_BIT, GL_NEAREST); // Unbind FBO gl_fbo_->glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebufferObject()); // ------ Read standard FBO to RAM data --------- // Bind standard FBO for reading glBindTexture(GL_TEXTURE_2D, textureId); // Read uchar * img = new uchar[4 * IMG_SIZE_X * IMG_SIZE_Y]; glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img); // Unbind FBO glBindTexture(GL_TEXTURE_2D, 0); // ------ Release allocated GPU memory --------- gl_fbo_->glDeleteFramebuffers(1, &ms_fboId); gl_fbo_->glDeleteRenderbuffers(1, &ms_ColorBufferId); gl_fbo_->glDeleteRenderbuffers(1, &ms_DepthBufferId); gl_fbo_->glDeleteFramebuffers(1, &fboId); gl_fbo_->glDeleteRenderbuffers(1, &rboId); glDeleteTextures(1, &textureId); // ------ un-premultiply alpha --------- // Once can notice that glBlendFuncSeparate(alpha, 1-alpha, 1, 1-alpha) // performs the correct blending function with input: // Frame buffer color as pre-multiplied alpha // Input fragment color as post-multiplied alpha // and output: // New frame buffer color as pre-multiplied alpha // // So by starting with glClearColor(0.0, 0.0, 0.0, 0.0), which is the // correct pre-multiplied representation for fully transparent, then // by specifying glColor() in post-multiplied alpha, we get the correct // blending behaviour and simply have to un-premultiply the value obtained // in the frame buffer at the very end for(int k=0; k<IMG_SIZE_X*IMG_SIZE_Y; ++k) { uchar * pixel = &(img[4*k]); double a = pixel[3]; if( 0 < a && a < 255 ) { double s = 255.0 / a; pixel[0] = (uchar) (std::min(255.0,std::floor(0.5+s*pixel[0]))); pixel[1] = (uchar) (std::min(255.0,std::floor(0.5+s*pixel[1]))); pixel[2] = (uchar) (std::min(255.0,std::floor(0.5+s*pixel[2]))); } } // ------ Convert to Qimage --------- // Create cleanup info to delete[] img when appropriate QImageCleanupFunction cleanupFunction = &imageCleanupHandler; void * cleanupInfo = reinterpret_cast<void*>(img); // Create QImage QImage res(img, IMG_SIZE_X, IMG_SIZE_Y, QImage::Format_RGBA8888, cleanupFunction, cleanupInfo); // Return QImage return res; } bool View3D::exportMesh(QString filename) { using namespace VectorAnimationComplex; QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; // Get VAC VAC * vac = scene_->activeVAC(); if (!vac) { return false; } // Get mesh geometry QList<Eigen::Vector3d> positions; QList<Eigen::Vector3d> normals; QList<int> indices; const ZOrderedCells & cells = vac->zOrdering(); for(auto it = cells.cbegin(); it != cells.cend(); ++it) { if (InbetweenEdge * ie = (*it)->toInbetweenEdge()) { ie->getMesh(viewSettings_, positions, normals, indices); } } // Write to file. double s = viewSettings_.spaceScale(); QTextStream out(&file); out.setLocale(QLocale::c()); out.setRealNumberNotation(QTextStream::FixedNotation); out.setRealNumberPrecision(6); for (Eigen::Vector3d& p : positions) { out << "v " << s * p[0] << " " << s * p[1] << " " << s * p[2] << "\n"; } for (Eigen::Vector3d p : normals) { p.normalize(); out << "vn " << p[0] << " " << p[1] << " " << p[2] << "\n"; } for (int i = 3; i < indices.size(); i += 4) { int k1 = indices[i-3]; int k2 = indices[i-2]; int k3 = indices[i-1]; int k4 = indices[i]; out << "f " << k1 << "//" << k1 << " " << k2 << "//" << k2 << " " << k3 << "//" << k3 << " " << k4 << "//" << k4 << "\n"; } return true; }
32.554117
124
0.600466
CELLINKAB
7e7c5dddb92ae7751e8674adbc992a91043ad3ab
2,905
cc
C++
test/persist_alloc_read.cc
moksha11/nvmalloc
7ea255d09b1aed3acab8344be6904464aab8ba11
[ "BSD-3-Clause" ]
2
2015-06-11T17:50:53.000Z
2015-07-04T08:24:50.000Z
test/persist_alloc_read.cc
moksha11/nvmalloc
7ea255d09b1aed3acab8344be6904464aab8ba11
[ "BSD-3-Clause" ]
null
null
null
test/persist_alloc_read.cc
moksha11/nvmalloc
7ea255d09b1aed3acab8344be6904464aab8ba11
[ "BSD-3-Clause" ]
null
null
null
/* * malloc-test * cel - Thu Jan 7 15:49:16 EST 1999 * * Benchmark libc's malloc, and check how well it * can handle malloc requests from multiple threads. * * Syntax: * malloc-test [ size [ iterations [ thread count ]]] * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include <pthread.h> #include <nv_map.h> #include <c_io.h> #ifdef ENABLE_MPI_RANKS #include "mpi.h" #endif #define USECSPERSEC 1000000 #define pthread_attr_default NULL #define MAX_THREADS 2 #define BASE_PROC_ID 20000 unsigned int procid; void run_test(char a); static unsigned size = 10487657; /* 1MB */ static int total_iterations = 10; int main(int argc, char *argv[]) { if(argc < 2) { fprintf(stdout, "enter read (r) or write(w) mode \n"); exit(0); } nvinit_(BASE_PROC_ID); #ifdef ENABLE_MPI_RANKS MPI_Init (&argc, &argv); #endif printf("Starting test...\n"); if(!strcmp(argv[1], "w")) run_test('w'); else run_test('r'); exit(0); } void run_test(char r) { register int i; register unsigned request_size = size; struct timeval start, end, null, elapsed, adjusted; #ifdef ENABLE_MPI_RANKS int rank; MPI_Comm_rank (MPI_COMM_WORLD, &rank); fprintf(stderr,"rank %d \n",rank); procid = rank + 1; #else procid = 1; #endif /* * Time a null loop. We'll subtract this from the final * malloc loop results to get a more accurate value. */ null.tv_sec = end.tv_sec - start.tv_sec; null.tv_usec = end.tv_usec - start.tv_usec; if (null.tv_usec < 0) { null.tv_sec--; null.tv_usec += USECSPERSEC; } /* * Run the real malloc test */ gettimeofday(&start, NULL); for (i = 0; i < total_iterations; i++) { register char * buf; char varname[100]; bzero(varname,0); sprintf(varname,"%d",i); strcat(varname,"_"); strcat(varname,(char* )"buf"); if(r == 'w') { buf = (char *)nvalloc_(size,varname,BASE_PROC_ID); assert(buf); for(unsigned int j=0; j < size; j++) buf[j]= 'a' + (char)i; }else{ buf = (char *)nvread_(varname,BASE_PROC_ID); assert(buf); fprintf(stdout,"varname %s\n", varname); //TODO: Add verify code //for(unsigned int j=0;j<size;j++) // fprintf(stdout,"%d:%c",j,buf[j]); } fprintf(stdout,"\n"); } gettimeofday(&end, NULL); elapsed.tv_sec = end.tv_sec - start.tv_sec; elapsed.tv_usec = end.tv_usec - start.tv_usec; if (elapsed.tv_usec < 0) { elapsed.tv_sec--; elapsed.tv_usec += USECSPERSEC; } /* * Adjust elapsed time by null loop time */ adjusted.tv_sec = elapsed.tv_sec - null.tv_sec; adjusted.tv_usec = elapsed.tv_usec - null.tv_usec; if (adjusted.tv_usec < 0) { adjusted.tv_sec--; adjusted.tv_usec += USECSPERSEC; } printf("Thread %lu adjusted timing: %lu.%06lu seconds for %d requests" " of %d bytes.\n", pthread_self(), elapsed.tv_sec, elapsed.tv_usec, total_iterations, request_size); pthread_exit(NULL); }
20.75
71
0.655422
moksha11
7e7ca42618375ea4b409f9c82e40da4ee16a6116
14,659
cpp
C++
Libraries/AssetProcessor/ExAPImportTIFF.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
Libraries/AssetProcessor/ExAPImportTIFF.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
Libraries/AssetProcessor/ExAPImportTIFF.cpp
tom-weatherhead/exeter-asset-processor
e19c777427afe66684f308cb7b07448b3481c25e
[ "MIT" ]
null
null
null
/* * ExAPImportTIFF.cpp * Exeter AssetProcessor * * Created by Tom Weatherhead on Mon Jun 30 2003. * Copyright (c) 2003 by Tom Weatherhead. All rights reserved. * */ #ifdef _MSC_VER // TAW 2002/03/11 : ie. if MSVC #ifndef MACINTOSH // TAW 2002/02/23 : ie. if MSVC // Suppress warning C4786: Identifier truncated to 255 chars in the debug info. #pragma warning(disable : 4786) #endif #endif //lint -e1050 : Expected a template argument list '<...>' for template 'std::iterator<<1>,<2>,<3>>' #include <cstring> #include "General\\ExAPMinMax.h" #include "CodecLib\\ExCodecLZW.h" #include "UtilLib\\ExUtilBitByteSourceSinkInterface.h" #include "ExAPImportTIFF.h" #include "ExAPBitmapDocument.h" #include "ExAPBitmapGrey8.h" #include "ExAPBitmapRGB24.h" #include "ExAPBitmapCMYK32.h" //lint +e1050 //#define TAW_TRACE 1 // **** Class ExAPTIFFImageDataBitSource **** class ExAPTIFFImageDataBitSource : public ExUtilBitSourceInterface { private: // The default constructor is never defined; it is declared here in order to satisfy lint. //lint -esym( 1526, ExAPTIFFImageDataBitSource::ExAPTIFFImageDataBitSource ) //lint -e1704 : Constructor has private access specification. ExAPTIFFImageDataBitSource( void ); //lint +e1704 public: ExAPAutoPtr<ExUtilFileReaderBaseInterface> m_file; unsigned int m_buffer; int m_numBitsInBuffer; int m_numBytesLeftToRead; ExAPTIFFImageDataBitSource( ExAPAutoPtr<ExUtilFileReaderBaseInterface> file, int numBytesLeftToRead ); virtual ~ExAPTIFFImageDataBitSource( void ); virtual int ReadBits( int numBits ); // Max of 31 bits. virtual int ReadBits( int numBits, int & bits ); // Max of 31 bits. virtual bool EndOfFile( void ); }; // class ExAPTIFFImageDataBitSource ExAPTIFFImageDataBitSource::ExAPTIFFImageDataBitSource( ExAPAutoPtr<ExUtilFileReaderBaseInterface> file, int numBytesLeftToRead ) : m_file( file ), m_buffer( 0 ), m_numBitsInBuffer( 0 ), m_numBytesLeftToRead( numBytesLeftToRead ) { } // ExAPTIFFImageDataBitSource::ExAPTIFFImageDataBitSource() ExAPTIFFImageDataBitSource::~ExAPTIFFImageDataBitSource( void ) { } // ExAPTIFFImageDataBitSource::~ExAPTIFFImageDataBitSource() int ExAPTIFFImageDataBitSource::ReadBits( int numBits ) { // Accumulate bytes in m_buffer until the requested number of bits are available. while( m_numBitsInBuffer < numBits ) { if( m_numBytesLeftToRead <= 0 ) { #ifdef TAW_TRACE printf( "ExAPTIFFImageDataBitSource::ReadBits: No more bytes.\n" ); #endif return( -1 ); } const int x = m_file->GetByteAsInt(); //fgetc( m_fp ); #if 0 //def TAW_TRACE printf( "ExAPTIFFImageDataBitSource::ReadBits: Read byte %d.\n", x ); #endif --m_numBytesLeftToRead; if( m_file->EndOfFile() /* x == EOF */ ) { #ifdef TAW_TRACE printf( "ExAPTIFFImageDataBitSource::ReadBits: End of File.\n" ); #endif return( -1 ); } m_buffer <<= 8; m_buffer |= (unsigned int)( x & 0xFF ); m_numBitsInBuffer += 8; // 8 bits per byte. } m_numBitsInBuffer -= numBits; const int rtn = int( m_buffer >> m_numBitsInBuffer ); m_buffer &= (unsigned int)( ( 1 << m_numBitsInBuffer ) - 1 ); return( rtn ); } // ExAPTIFFImageDataBitSource::ReadBits() int ExAPTIFFImageDataBitSource::ReadBits( int numBits, int & bits ) // Max of 31 bits. { bits = ReadBits( numBits ); return( numBits ); } bool ExAPTIFFImageDataBitSource::EndOfFile( void ) { return( m_numBytesLeftToRead <= 0 || m_file->EndOfFile() /* feof( m_fp ) != 0 */ ); } // ExAPTIFFImageDataBitSource::EndOfFile() // **** Class ExAPTIFFImageDataByteSink **** class ExAPTIFFImageDataByteSink : public ExUtilByteSinkInterface { private: // The default constructor is never defined; it is declared here in order to satisfy lint. //lint -esym( 1526, ExAPTIFFImageDataByteSink::ExAPTIFFImageDataByteSink ) //lint -e1704 : Constructor has private access specification. ExAPTIFFImageDataByteSink( void ); //lint +e1704 public: //lint -e1725 : Class member is a reference. const ExAPBitmap & m_image; //lint +e1725 unsigned char * m_rowPtr; unsigned char * m_bytePtr; int m_numRowsRemaining; int m_numColsRemainingInRow; ExAPTIFFImageDataByteSink( const ExAPBitmap & image, unsigned char * rowPtr, int numRowsRemaining ); virtual ~ExAPTIFFImageDataByteSink( void ); virtual void WriteByte( unsigned char ch ); virtual void WriteBytes( const std::vector<unsigned char> & bytes ); virtual void AdvanceToNextLine( void ); }; // class ExAPTIFFImageDataByteSink ExAPTIFFImageDataByteSink::ExAPTIFFImageDataByteSink( const ExAPBitmap & image, unsigned char * rowPtr, int numRowsRemaining ) : m_image( image ), m_rowPtr( rowPtr ), m_bytePtr( rowPtr ), m_numRowsRemaining( numRowsRemaining ), m_numColsRemainingInRow( 0 ) { } // ExAPTIFFImageDataByteSink::ExAPTIFFImageDataByteSink() ExAPTIFFImageDataByteSink::~ExAPTIFFImageDataByteSink( void ) { m_rowPtr = 0; // To satisfy lint. m_bytePtr = 0; // To satisfy lint. } // ExAPTIFFImageDataByteSink::~ExAPTIFFImageDataByteSink() void ExAPTIFFImageDataByteSink::WriteByte( unsigned char ch ) { ExAssert( ExAPException::IllegalFunctionCall ) } // ExAPTIFFImageDataByteSink::WriteByte() void ExAPTIFFImageDataByteSink::WriteBytes( const std::vector<unsigned char> & bytes ) { std::vector<unsigned char>::const_iterator it = bytes.begin(); const std::vector<unsigned char>::const_iterator itEnd = bytes.end(); while( it != itEnd ) { if( m_numColsRemainingInRow <= 0 ) { if( m_numRowsRemaining-- <= 0 ) { break; } //m_numColsRemainingInRow = m_image.GetWidth() * m_image.GetBytesPerPixel(); m_numColsRemainingInRow = m_image.getUnalignedBytesPerLine(); m_bytePtr = m_rowPtr; m_rowPtr += m_image.getBytesPerLine(); } *m_bytePtr++ = *it++; --m_numColsRemainingInRow; } } // ExAPTIFFImageDataByteSink::WriteBytes() void ExAPTIFFImageDataByteSink::AdvanceToNextLine( void ) { } // ExAPTIFFImageDataByteSink::AdvanceToNextLine() // **** Class ExAPTIFFReader **** ExAPTIFFReader::ExAPTIFFReader( ExAPAutoPtr<ExUtilFileReaderBaseInterface> file ) throw( ExAPException ) : m_file( file ), m_imageFileDirectoryOffset( 0 ) { unsigned char header[8]; #if 1 const size_t bytesRead = size_t( m_file->GetBytes( header, int( sizeof( header ) ) ) ); #else const size_t bytesRead = fread( header, 1, sizeof( header ), fp ); #endif if( bytesRead != sizeof( header ) ) { #ifdef TAW_TRACE printf( "Error: The header was not fully read.\n" ); #endif // Throw an exception. } const bool littleEndian = ( header[0] == 'I' && header[1] == 'I' ); // "file" is a non-const reference; // "m_file" is a const reference to the same object. file->SetEndianness( littleEndian ); const unsigned short magic42 = m_file->GetWord( header + 2 ); m_imageFileDirectoryOffset = m_file->GetDoubleWord( header + 4 ); #ifdef TAW_TRACE if( header[0] == 'I' && header[1] == 'I' ) { printf( "The file's data is in little-endian format.\n" ); } else if( header[0] == 'M' && header[1] == 'M' ) { printf( "The file's data is in big-endian format.\n" ); } else { printf( "Error: The file's byte ordering is not properly indicated.\n" ); // Throw an exception. } if( magic42 == 42 ) { printf( "The magic 42 was found.\n" ); } else { printf( "Error: The magic 42 was not found.\n" ); } #endif ExAssert( magic42 == 42 ) ExAssert( m_imageFileDirectoryOffset != 0 ) } // ExAPTIFFReader::ExAPTIFFReader() bool ExAPTIFFReader::NextIFDExists( void ) const { return( m_imageFileDirectoryOffset != 0 ); } // ExAPTIFFReader::NextIFDExists() ExAPBitmap * ExAPTIFFReader::ImportImage( void ) throw( ExAPException ) { ExAPBitmap * rtn = 0; ExAPTIFFImageMetadata tiffImageMetadata; #ifdef TAW_TRACE printf( "ImportImage: fseek()ing to offset %u...\n", m_imageFileDirectoryOffset ); #endif m_file->SetOffset( static_cast<long>( m_imageFileDirectoryOffset ) ); // Read all of the tags in this IFD. const int numIFDFields = static_cast<int>( m_file->GetWord() ); #ifdef TAW_TRACE printf( "ImportImage: IFD has %d fields.\n", numIFDFields ); #endif m_IFDFields.clear(); for( int i = 0; i < numIFDFields; ++i ) { const unsigned short tag = m_file->GetWord(); const unsigned short fieldType = m_file->GetWord(); // The type of data that constitute the field. const unsigned int dataCount = m_file->GetDoubleWord(); // The number of data in the field. const unsigned int valueOffset = m_file->GetDoubleWord(); #if 0 //def TAW_TRACE printf( "IFD field %d:\n", i ); printf( " Tag: %hu\n", tag ); printf( " Field data type: %hu\n", fieldType ); printf( " Data count: %u\n", dataCount ); printf( " Value offset in file: %u\n\n", valueOffset ); #endif m_IFDFields.push_back( IFDFieldType( tag, fieldType, dataCount, valueOffset ) ); } // Prepare to point to the next IFD upon the next call. m_imageFileDirectoryOffset = m_file->GetDoubleWord(); std::vector<IFDFieldType>::const_iterator it = m_IFDFields.begin(); const std::vector<IFDFieldType>::const_iterator itEnd = m_IFDFields.end(); while( it != itEnd ) { const IFDFieldType & IFDField = *it; m_tagReaderMaster.ReadTag( m_file, IFDField, tiffImageMetadata ); ++it; } // Use the metadata to create the image. const bool imageIsUncompressed = tiffImageMetadata.m_compressionType == 1; const bool imageIsLZWCompressed = tiffImageMetadata.m_compressionType == 5; const bool imageIsDecompressable = imageIsUncompressed || imageIsLZWCompressed; if( tiffImageMetadata.m_imageLength <= 0 || tiffImageMetadata.m_imageWidth <= 0 || tiffImageMetadata.m_rowsPerStrip <= 0 || tiffImageMetadata.m_stripOffsets.size() == 0 || // Unsigned; can't be less than zero. tiffImageMetadata.m_stripOffsets.size() != tiffImageMetadata.m_stripByteCounts.size() ) { #ifdef TAW_TRACE printf( "ImportImage: Image metadata is invalid.\n" ); #endif } else if( tiffImageMetadata.m_bitsPerSample != 8 || !imageIsDecompressable ) { #ifdef TAW_TRACE printf( "ImportImage: This filter is not yet capable of importing this image.\n" ); #endif } else { const int imageWidth = tiffImageMetadata.m_imageWidth; const int imageHeight = tiffImageMetadata.m_imageLength; const int samplesPerPixel = tiffImageMetadata.m_samplesPerPixel; ExAPBitmap8bpch * image = 0; // We already know that each sample contains 8 bits. switch( tiffImageMetadata.m_photometricInterpretation ) { case 0: // White is zero. case 1: // Black is zero. case 4: // Transparency mask if( samplesPerPixel == 1 ) { image = new ExAPBitmapGrey8( imageWidth, imageHeight ); } break; case 2: // RGB if( samplesPerPixel == 3 ) { image = new ExAPBitmapRGB24( imageWidth, imageHeight ); } break; case 5: // CMYK if( samplesPerPixel == 4 ) { image = new ExAPBitmapCMYK32( imageWidth, imageHeight ); } break; //case 3: // RGB Paletted //case 6: // YCbCr //case 8: // CIELab default: break; } if( image == 0 ) { #ifdef TAW_TRACE printf( "ImportImage: Unsupported colour model or samples per pixel.\n" ); #endif return( 0 ); } #ifdef TAW_TRACE int numStrip = 0; #endif std::vector<long>::const_iterator itStripOffset = tiffImageMetadata.m_stripOffsets.begin(); const std::vector<long>::const_iterator itStripOffsetEnd = tiffImageMetadata.m_stripOffsets.end(); std::vector<int>::const_iterator itStripByteCount = tiffImageMetadata.m_stripByteCounts.begin(); const std::vector<int>::const_iterator itStripByteCountEnd = tiffImageMetadata.m_stripByteCounts.end(); int firstRow = 0; unsigned char * imageRowPtr = image->getBuffer(); const int imageBytesPerRow = image->getBytesPerLine(); const int srcBytesPerRow = imageWidth * image->GetBytesPerPixel(); while( itStripOffset != itStripOffsetEnd && itStripByteCount != itStripByteCountEnd ) { int numRowsInThisStrip = min( tiffImageMetadata.m_imageLength - firstRow, tiffImageMetadata.m_rowsPerStrip ); m_file->SetOffset( *itStripOffset ); if( imageIsUncompressed ) { while( numRowsInThisStrip-- > 0 ) { /* const int bytesRead = */ (void)m_file->GetBytes( imageRowPtr, srcBytesPerRow ); imageRowPtr += imageBytesPerRow; } } else if( imageIsLZWCompressed ) { // **** Begin handling LZW-compressed strip **** ExAPAutoPtr<ExUtilBitSourceInterface> bitSource = new ExAPTIFFImageDataBitSource( m_file, *itStripByteCount ); ExAPAutoPtr<ExUtilByteSinkInterface> byteSink = new ExAPTIFFImageDataByteSink( *image, imageRowPtr, numRowsInThisStrip ); ExAPAutoPtr<ExAPLZWCodec> codec = ExAPLZWCodec::CreateCodec( ExAPLZWCodec::TypeTIFF, 8 ); // Assume 8 bits per pixel for now. //static const int bitsPerChunk = 8; // Start at code 2 + ( 1 << 8 ) == 258. //static const int codeResizingOffset = 1; #if 0 //def TAW_TRACE const int stripByteCount = *itStripByteCount; printf( "Decompressing LZW strip #%d...\n", numStrip++ ); printf( " Strip byte count: %d.\n", stripByteCount ); #endif codec->DecompressData( bitSource, byteSink /*, bitsPerChunk, codeResizingOffset */ ); imageRowPtr += numRowsInThisStrip * imageBytesPerRow; // **** End handling LZW-compressed strip **** } firstRow += tiffImageMetadata.m_rowsPerStrip; ++itStripOffset; ++itStripByteCount; } if( imageIsLZWCompressed && tiffImageMetadata.m_differencingPredictor == 2 ) { // Undo horizontal differencing. #ifdef TAW_TRACE printf( "Undoing horizontal differencing...\n" ); #endif const int bytesPerPixel = image->GetBytesPerPixel(); imageRowPtr = image->getBuffer(); int numRowsLeft = image->GetHeight(); while( numRowsLeft-- > 0 ) { unsigned char * srcPtr = imageRowPtr; unsigned char * dstPtr = srcPtr + bytesPerPixel; int numBytesLeftInRow = ( image->GetWidth() - 1 ) * bytesPerPixel; imageRowPtr += imageBytesPerRow; while( numBytesLeftInRow-- > 0 ) { *dstPtr++ += *srcPtr++; } } } rtn = image; } return( rtn ); } // ExAPTIFFReader::ImportImage() // **** End of File ****
28.408915
130
0.682925
tom-weatherhead
7e7edbfb94cbfde933bbb33f93444919b6348b2f
7,814
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ObjectEcu.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/datablocks/snippets/ObjectEcu.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/datablocks/snippets/ObjectEcu.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file ObjectEcu.hpp * * \copydoc Copyright * \author Mario Brumm (mb) * \date Apr 26, 2012 *///------------------------------------------------------------------- #ifndef IBEOSDK_OBJECTECU_HPP_SEEN #define IBEOSDK_OBJECTECU_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/datablocks/snippets/Point2dFloat.hpp> #include <ibeosdk/Time.hpp> #include <ibeosdk/ObjectBasic.hpp> #include <ibeosdk/datablocks/snippets/Snippet.hpp> #include <ibeosdk/misc/deprecatedwarning.hpp> #include <vector> #include <iostream> //====================================================================== namespace ibeosdk { //====================================================================== class ObjectEcu : public Snippet { public: ObjectEcu(); ObjectEcu(const ObjectEcu& src); public: virtual std::streamsize getSerializedSize() const; virtual bool deserialize(std::istream& is); virtual bool serialize(std::ostream& os) const; // int getSerializedSize() const; public: UINT16 getObjectId() const { return m_id; } UINT16 getReserved() const { return m_reserved; } UINT32 getObjectAge() const { return m_age; } NTPTime getTimestamp() const { return m_timestamp; } UINT16 getHiddenStatusAge() const { return m_hiddenStatusAge; } ObjectClass getClassification() const { return m_class; } UINT8 getClassificationCertainty() const { return m_classCertainty; } UINT32 getClassificationAge() const { return m_classAge; } Point2dFloat getBoundingBoxCenter() { return m_boundingBoxCenter; } const Point2dFloat& getBoundingBoxCenter() const { return m_boundingBoxCenter; } Point2dFloat getBoundingBoxSize() { return m_boundingBoxSize; } const Point2dFloat& getBoundingBoxSize() const { return m_boundingBoxSize; } Point2dFloat getObjectBoxCenter() { return m_objectBoxCenter; } const Point2dFloat& getObjectBoxCenter() const { return m_objectBoxCenter; } Point2dFloat getObjectBoxSigma() { return m_objectBoxSigma; } const Point2dFloat& getObjectBoxSigma() const { return m_objectBoxSigma; } Point2dFloat getObjectBoxSize() { return m_objectBoxSize; } const Point2dFloat& getObjectBoxSize() const { return m_objectBoxSize; } UINT64 getReserved2() const { return m_reserved2; } IBEOSDK_DEPRECATED float getYawAngle() const { return m_objectBoxOrientation; } IBEOSDK_DEPRECATED float getYawAngleSigma() const { return m_objectBoxOrientationSigma; } float getObjectBoxOrientation() const { return m_objectBoxOrientation; } float getObjectBoxOrientationSigma() const { return m_objectBoxOrientationSigma; } Point2dFloat getRelativeVelocity() { return m_relVelocity; } const Point2dFloat& getRelativeVelocity() const { return m_relVelocity; } Point2dFloat getRelativeVelocitySigma() { return m_relVelocitySigma; } const Point2dFloat& getRelativeVelocitySigma() const { return m_relVelocitySigma; } Point2dFloat getAbsoluteVelocity() { return m_absVelocity; } const Point2dFloat& getAbsoluteVelocity() const { return m_absVelocity; } Point2dFloat getAbsoluteVelocitySigma() { return m_absVelocitySigma; } const Point2dFloat& getAbsoluteVelocitySigma() const { return m_absVelocitySigma; } float getOrientation() const { return this->m_orientation; } UINT8 getNumberOfContourPoints() const { return m_numContourPoints; } std::vector<Point2dFloat>& getContourPoints() { return m_contourPoints; } const std::vector<Point2dFloat>& getContourPoints() const { return m_contourPoints; } UINT8 getIndexOfClosestPoint() const { return m_indexOfClosedPoint; } public: void setObjectId(const UINT16 newObjectId) { m_id = newObjectId; } void setReserved( const UINT16 newReserved) { m_reserved = newReserved; } void setObjectAge(const UINT32 newObjectAge) { m_age = newObjectAge; } void setTimestamp(const NTPTime newTimestamp) { m_timestamp = newTimestamp; } void setHiddenStatusAge(const UINT16 newHiddenStatusAge) { m_hiddenStatusAge = newHiddenStatusAge; } void setClassification(const ObjectClass newClassification) { m_class = newClassification; } void setClassificationCertainty(const UINT8 newClassificationCertainty) { m_classCertainty = newClassificationCertainty; } void setClassificationAge(const UINT32 newClassificationAge) { m_classAge = newClassificationAge; } void setBoundingBoxCenter(const Point2dFloat& newBoundingBoxCenter) { m_boundingBoxCenter = newBoundingBoxCenter; } void setBoundingBoxSize(const Point2dFloat& newBoundingBoxSize) { m_boundingBoxSize=newBoundingBoxSize; } void setReserved2(const UINT64& newReserved2) { m_reserved2 = newReserved2; } void setObjectBoxCenter(const Point2dFloat& newObjectBoxCenter) { m_objectBoxCenter=newObjectBoxCenter; } void setObjectBoxSigma(const Point2dFloat& newObjectBoxSigma) { m_objectBoxSigma=newObjectBoxSigma; } void setObjectBoxSize(const Point2dFloat& newObjectBoxSize) { m_objectBoxSize=newObjectBoxSize; } IBEOSDK_DEPRECATED void setYawAngle(const float newObjBoxOrientation) { m_objectBoxOrientation=newObjBoxOrientation; } IBEOSDK_DEPRECATED void setYawAngleSigma(const float newObjBoxOrientationSigma) { m_objectBoxOrientationSigma=newObjBoxOrientationSigma; } void setObjBoxOrientation(const float newObjBoxOrientation) { m_objectBoxOrientation = newObjBoxOrientation; } void setObjBoxOrientationSigma(const float newObjBoxOrientationSigma) { m_objectBoxOrientationSigma = newObjBoxOrientationSigma; } void setRelativeVelocity(const Point2dFloat& newRelativeVelocity) { m_relVelocity=newRelativeVelocity; } void setRelativeVelocitySigma(const Point2dFloat& newRelativeVelocitySigma) { m_relVelocitySigma=newRelativeVelocitySigma; } void setAbsoluteVelocity(const Point2dFloat& newAbsoluteVelocity) { m_absVelocity=newAbsoluteVelocity; } void setAbsoluteVelocitySigma(const Point2dFloat& newAbsoluteVelocitySigma) { m_absVelocitySigma=newAbsoluteVelocitySigma; } void setOrientation(const float newOrientation) { this->m_orientation = newOrientation; } void setNumberOfContourPoints(const UINT8 newNumberOfContourPoints) { m_numContourPoints = newNumberOfContourPoints; } void setContourPoints(const std::vector<Point2dFloat>& newContourPoints) { m_contourPoints = newContourPoints; } void setIndexOfClosestPoint(const UINT8 newIndexOfClosestPoint) { m_indexOfClosedPoint = newIndexOfClosestPoint; } public: bool operator==(const ObjectEcu& other) const; bool operator!=(const ObjectEcu& other) const { return !((*this) == other); } protected: static const int nbOfBytesInReserved3 = 18; protected: UINT16 m_id; UINT16 m_reserved; UINT32 m_age; NTPTime m_timestamp; UINT16 m_hiddenStatusAge; ObjectClass m_class; UINT8 m_classCertainty; UINT32 m_classAge; Point2dFloat m_boundingBoxCenter; Point2dFloat m_boundingBoxSize; Point2dFloat m_objectBoxCenter; Point2dFloat m_objectBoxSigma; Point2dFloat m_objectBoxSize; UINT64 m_reserved2; float m_objectBoxOrientation; float m_objectBoxOrientationSigma; Point2dFloat m_relVelocity; Point2dFloat m_relVelocitySigma; Point2dFloat m_absVelocity; Point2dFloat m_absVelocitySigma; char m_reserved3[nbOfBytesInReserved3]; UINT8 m_numContourPoints; UINT8 m_indexOfClosedPoint; std::vector<Point2dFloat> m_contourPoints; protected: // not serialized data float m_orientation; }; // ObjectEcu //====================================================================== std::ostream& operator<<(std::ostream& os, const ObjectEcu& o); //====================================================================== } // namespace ibeosdk //====================================================================== #endif // IBEOSDK_OBJECTECU_HPP_SEEN //======================================================================
41.343915
139
0.743665
tomcamp0228
7e82f92af4c0ce09f7aed81137ebb8c1029cb47f
11,944
cpp
C++
golg__resources.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2015-12-09T20:37:49.000Z
2021-08-10T08:06:29.000Z
golg__resources.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
13
2021-09-20T16:25:30.000Z
2022-03-17T04:59:40.000Z
golg__resources.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2016-01-04T22:54:22.000Z
2021-09-20T16:09:03.000Z
/********************************************************************** <BR> This file is part of Crack dot Com's free source code release of Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for information about compiling & licensing issues visit this URL</a> <PRE> If that doesn't help, contact Jonathan Clark at golgotha_source@usa.net (Subject should have "GOLG" in it) ***********************************************************************/ #include "pch.h" #include "resources.h" #include "window/cursor.h" #include "memory/malloc.h" #include "string/string.h" #include "network/login.h" #include "string/string.h" #include "loaders/load.h" #include "render/r1_api.h" #include "sound/sound.h" g1_resource_class g1_resources; float f_get(char * rname) { i4_const_str::iterator s=i4gets(rname).begin(); return (float)s.read_float(); } void g1_resource_class::g_float(i4_float &f, char * res_name) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing %s",res_name); } i4_const_str::iterator i=st.begin(); f=(float)i.read_float(); } void g1_resource_class::g_cursor(i4_cursor_class *&c, char * res_name, int big, int color) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing from resource/constants.res %s",res_name); } i4_const_str::iterator i=st.begin(); i4_str * fmt=i.read_string(); w32 tcolor=i.read_number(); int hx=i.read_number(); if (!big) { hx/=2; } int hy=i.read_number(); if (!big) { hy/=2; } i4_str * fn=fmt->sprintf(100,big ? "big" : "small", color ? 16 : 2); delete fmt; i4_image_class * im=i4_load_image(*fn); if (!im) { char buf[100]; i4_os_string(*fn, buf, 100); i4_error("failed to load image for cursor in constants.res : %s",buf); } delete fn; c=new i4_cursor_class(im, tcolor, hx, hy); delete im; } void g1_resource_class::g_w32(w32 &x, char * res_name) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing %s",res_name); } i4_const_str::iterator i=st.begin(); x=i.read_number(); } void g1_resource_class::g_sw32(sw32 &x, char * res_name) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing %s",res_name); } i4_const_str::iterator i=st.begin(); x=i.read_number(); } void g1_resource_class::g_w16(w16 &x, char * res_name) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing %s",res_name); } i4_const_str::iterator i=st.begin(); x=(w16)i.read_number(); } void g1_resource_class::g_sw16(sw16 &x, char * res_name) { i4_const_str st=use->get(res_name); if (st.null()) { i4_error("Constant missing %s",res_name); } i4_const_str::iterator i=st.begin(); x=(short)i.read_number(); } void g1_resource_class::g_point(i4_3d_point_class &p, char * res_name) { i4_const_str * s,* x=use->get_array(res_name); s=x; i4_const_str::iterator i=x->begin(); p.x=(float)i.read_float(); x++; i=x->begin(); p.y=(float)i.read_float(); x++; i=x->begin(); p.z=(float)i.read_float(); i4_free(s); } void g1_resource_class::g_rect(rect &r, char * res_name) { i4_const_str * s,* x=use->get_array(res_name); s=x; i4_const_str::iterator i=x->begin(); r.x1=(short)i.read_number(); x++; i=x->begin(); r.y1=(short)i.read_number(); x++; i=x->begin(); r.x2=(short)i.read_number(); x++; i=x->begin(); r.y2=(short)i.read_number(); i4_free(s); } void g1_resource_class::cleanup() { int i; for (i=0; i<G1_TOTAL_CURSORS; i++) { if (big_cursors[i]) { delete big_cursors[i]; big_cursors[i]=0; } if (small_cursors[i]) { delete small_cursors[i]; small_cursors[i]=0; } } for (i=0; i<t_images; i++) { if (images[i]) { delete images[i]; images[i]=0; } } i4_free(images); i4_free(build_context_help); t_build_context_helps=0; if (username) { delete username; } username=0; } void g1_resource_class::load() { int i; try{ i4_string_manager_class constants; constants.init(); constants.load(i4gets("constants")); paused=i4_F; username=i4_get_user_name(); use=&constants; draw_flags=DRAW_ALL; char * cursors[]={ "default_cursor", "select_cursor", "move_cursor", "target_cursor", "follow_cursor", "x_cursor", "takeover_cursor" }; for (i=0; i<G1_TOTAL_CURSORS; i++) { g_cursor(big_cursors[i], cursors[i], 1, 1); g_cursor(small_cursors[i], cursors[i], 0, 0); } g_float(gravity, "gravity"); g_float(damping_friction, "damping_friction"); damping_fraction = 1.0f/damping_friction; ln_damping_friction = (float)exp(0.1f*damping_friction); g_float(recoil_factor, "recoil_factor"); g_float(recoil_gravity, "recoil_gravity"); g_float(sink_rate, "sink_rate"); g_sw16(water_damage, "water_damage"); g_float(player_turn_speed, "player_turn_speed"); g_float(player_accel, "player_accel"); g_rect(health_window, "health_window"); g_rect(chain_gun_window, "chain_gun_window"); g_rect(main_gun_window, "main_gun_window"); g_rect(missile_window, "missile_window"); g_rect(options_window, "options_window"); g_float(player_max_speed, "player_max_speed"); g_float(player_max_strafe_speed, "player_max_strafe_speed"); g_float(player_stop_friction, "player_stop_friction"); g_float(strafe_turn_speed, "strafe_turn_speed"); g_float(player_roll_speed, "player_roll_speed"); g_float(player_roll_max, "player_roll_max"); g_float(bullet_speed, "bullet_speed"); g_float(player_strafe_accel, "player_strafe_accel"); g_float(camera_dist, "camera_dist"); g_float(camera_angle, "camera_angle"); g_float(startegy_camera_angle, "startegy_camera_angle"); g_float(startegy_camera_dist, "startegy_camera_dist"); g_float(strategy_camera_turn_angle, "strategy_camera_turn_angle"); g_float(follow_camera_height, "follow_camera_height"); g_float(follow_camera_dist, "follow_camera_dist"); g_float(follow_camera_rotation, "follow_camera_rotation"); g_float(player_fire_slop_angle, "player_fire_slop_angle"); g_float(player_turret_radius, "player_turret_radius"); g_point(player_top_attach, "player_top_attach"); g_point(rocket_tank_top_attach, "rocket_tank_top_attach"); g_point(turret_muzzle_attach, "turret_muzzle_attach"); g_point(turret_top_attach, "turret_top_attach"); g_point(supergun_muzzle_attach, "supergun_muzzle_attach"); g_point(repairer_tip_attach, "repairer_tip_attach"); g_float(repairer_boom_offset, "repairer_boom_offset"); g_float(lod_switch_dist, "lod_switch_dist"); g_float(lod_disappear_dist, "lod_disappear_dist"); g_float(lod_nolodmodel_disappear_dist, "lod_nolodmodel_disappear_dist"); g_float(view_radii[0], "visual_radii_low"); g_float(view_radii[1], "visual_radii_med"); g_float(view_radii[2], "visual_radii_high"); g_rect(balance, "balance"); g_rect(build_buttons, "build_buttons"); g_rect(lives, "lives"); g_rect(mouse_scroll, "mouse_scroll"); g_w16(net_hostname_x, "net_hostname_x"); g_w16(net_hostname_y, "net_hostname_y"); g_w16(net_username_x, "net_username_x"); g_w16(net_username_y, "net_username_y"); g_w16(net_found_x1, "net_found_x1"); g_w16(net_found_x2, "net_found_x2"); g_w16(net_found_y, "net_found_y"); g_w16(net_start_x, "net_start_x"); g_w16(net_start_y, "net_start_y"); g_w16(net_find_port, "net_find_port"); g_w16(net_udp_port, "net_udp_port"); g_sw16(compass_x, "compass_x"); g_sw16(compass_y, "compass_y"); g_sw16(stat_pad_start_x, "stat_pad_start_x"); g_sw16(stat_pad_start_y, "stat_pad_start_y"); g_w16(stat_pad_size_x, "stat_pad_size_x"); g_w16(stat_pad_size_y, "stat_pad_size_y"); g_sw16(stat_pad_step_x, "stat_pad_step_x"); g_sw16(stat_pad_step_y, "stat_pad_step_y"); g_w16(small_health_added, "small_health_added"); g_w16(large_health_added, "large_health_added"); g_w16(small_bullets_added, "small_bullets_added"); g_w16(large_bullets_added, "large_bullets_added"); g_w16(small_chain_added, "small_chain_added"); g_w16(large_chain_added, "large_chain_added"); g_w16(small_missiles_added, "small_missiles_added"); g_w16(large_missiles_added, "large_missiles_added"); g_w16(small_money_added, "small_money_added"); g_w16(large_money_added, "large_money_added"); g_w32(supertank_machine_gun_damage, "supertank_machine_gun_damage"); g_w32(supertank_turret_damage, "supertank_turret_damage"); g_w32(supertank_guided_missile_damage, "supertank_guided_missile_damage"); g_w32(action_strategy_ticks_to_switch, "action_strategy_ticks_to_switch"); g_w32(lock_cheat, "lock_cheat"); i4_const_str * im_array=constants.get_array("images"); t_images=0; for (i=0; !im_array[i].null(); i++) { t_images++; } images=(i4_image_class * *)I4_MALLOC(sizeof(i4_image_class **) * t_images, "image array"); for (i=0; i<t_images && !im_array[i].null(); i++) { images[i]=i4_load_image(im_array[i]); if (!images[i]) { char im_name[100]; i4_error("image missing %s", i4_os_string(im_array[i], im_name, sizeof(im_name))); } } i4_free(im_array); use=0; // make sure this isn't used any more constants.uninit(); build_context_help=i4_string_man.get_array("build_context_help"); if (!build_context_help) { i4_error("no build_context_help in resource/g1.res"); } t_build_context_helps=0; for (i4_const_str * str=build_context_help; !str->null(); str++) { t_build_context_helps++; } render_window_expand_mode=R1_COPY_1x1; } catch(...) { i4_error("FATAL: Number format exception reading default resources 'g1.res'."); } }
29.131707
93
0.567565
poikilos