bool symbolExistsInSearchPath(const std::string& symbol, const std::set<std::string>& searchPathObjects) const { return searchPathObjects.count(symbol) != 0; }
unsigned NxsCompressDiscreteMatrix( const NxsCXXDiscreteMatrix & mat, /**< is the data source */ std::set<NxsCharacterPattern> & patternSet, /* matrix that will hold the compressed columns */ std::vector<const NxsCharacterPattern *> * compressedIndexPattern, /** if not 0L, this will be filled to provide a map from an index in `compressedTransposedMatrix` to the original character count */ const NxsUnsignedSet * taxaToInclude, /**< if not 0L, this should be the indices of the taxa in `mat` to include (if 0L all characters will be included). Excluding taxa will result in shorter patterns (the skipped taxa will not be filled with empty codes, instead the taxon indexing will be frameshifted -- the client code must keep track of these frameshifts). */ const NxsUnsignedSet * charactersToInclude) { const unsigned origNumPatterns = (unsigned) patternSet.size(); unsigned ntax = mat.getNTax(); unsigned patternLength = ntax; unsigned nchar = mat.getNChar(); if (compressedIndexPattern) { compressedIndexPattern->resize(nchar); } NxsUnsignedSet allTaxaInds; if (taxaToInclude) { if (taxaToInclude->empty()) return 0; // might want to warn about this! const unsigned lastTaxonIndex = *(taxaToInclude->rbegin()); if (lastTaxonIndex >= ntax) throw NxsException("Taxon index in taxaToInclude argument to NxsCompressDiscreteMatrix is out of range"); patternLength -= taxaToInclude->size(); } else { for (unsigned i = 0; i < ntax; ++i) allTaxaInds.insert(i); taxaToInclude = &allTaxaInds; } if (charactersToInclude) { if (charactersToInclude->empty()) return 0; // might want to warn about this! const unsigned lastColumnIndex = *(charactersToInclude->rbegin()); if (lastColumnIndex >= nchar) throw NxsException("Character index in charactersToInclude argument to NxsCompressDiscreteMatrix is out of range"); } // Create actingWeights vector and copy the integer weights from mat into it // If there are no integer weights in mat, copy the floating point weights instead // if floating point weights have been defined const std::vector<int> & iwts = mat.getIntWeightsConst(); std::vector<double> actingWeights(nchar, 1.0); //bool weightsSpecified = false; //bool weightsAsInts = false; if (!iwts.empty()) { NCL_ASSERT(iwts.size() >= nchar); //weightsSpecified = true; //weightsAsInts = true; for (unsigned j = 0; j < nchar; ++j) actingWeights[j] = (double)iwts.at(j); } else { const std::vector<double> & dwts = mat.getDblWeightsConst(); if (!dwts.empty()) { //weightsSpecified = true; actingWeights = dwts; NCL_ASSERT(actingWeights.size() == nchar); } } // Set corresponding actingWeights elements to zero if any characters have been excluded in mat const NxsUnsignedSet & excl = mat.getExcludedCharIndices(); for (NxsUnsignedSet::const_iterator eIt = excl.begin(); eIt != excl.end(); ++eIt) { NCL_ASSERT(*eIt < nchar); actingWeights[*eIt] = 0.0; } const double * wts = &(actingWeights[0]); NxsCharacterPattern patternTemp; patternTemp.count = 1; for (unsigned j = 0; j < nchar; ++j) { double patternWeight = wts[j]; bool shouldInclude = (charactersToInclude == 0L || (charactersToInclude->find(j) != charactersToInclude->end())); if (patternWeight > 0.0 && shouldInclude) { // Build up a vector representing the pattern of state codes at this site patternTemp.stateCodes.clear(); patternTemp.stateCodes.reserve(patternLength); patternTemp.sumOfPatternWeights = patternWeight; unsigned indexInPattern = 0; for (NxsUnsignedSet::const_iterator taxIndIt = taxaToInclude->begin(); taxIndIt != taxaToInclude->end(); ++taxIndIt, ++indexInPattern) { const unsigned taxonIndex = *taxIndIt; const NxsCDiscreteStateSet * row = mat.getRow(taxonIndex); const NxsCDiscreteStateSet code = row[j]; patternTemp.stateCodes.push_back(code); } NCL_ASSERT(indexInPattern == patternLength); std::set<NxsCharacterPattern>::iterator lowBoundLoc = patternSet.lower_bound(patternTemp); if ((lowBoundLoc == patternSet.end()) || (patternTemp < *lowBoundLoc)) { std::set<NxsCharacterPattern>::iterator insertedIt = patternSet.insert(lowBoundLoc, patternTemp); if (compressedIndexPattern) { const NxsCharacterPattern & patInserted = *insertedIt; (*compressedIndexPattern)[j] = &patInserted; } } else { NCL_ASSERT(patternTemp == *lowBoundLoc); lowBoundLoc->sumOfPatternWeights += patternWeight; lowBoundLoc->count += 1; if (compressedIndexPattern) { (*compressedIndexPattern)[j] = &(*lowBoundLoc); } } } } return (unsigned)patternSet.size() - origNumPatterns; }
namespace HPHP { /////////////////////////////////////////////////////////////////////////////// static Mutex s_thread_info_mutex; static std::set<ThreadInfo*> s_thread_infos; __thread char* ThreadInfo::t_stackbase = 0; IMPLEMENT_THREAD_LOCAL_NO_CHECK_HOT(ThreadInfo, ThreadInfo::s_threadInfo); ThreadInfo::ThreadInfo() : m_stacklimit(0), m_executing(Idling) { assert(!t_stackbase); t_stackbase = static_cast<char*>(stack_top_ptr()); map<int, ObjectAllocatorBaseGetter> &wrappers = ObjectAllocatorCollector::getWrappers(); m_allocators.resize(wrappers.rbegin()->first + 1); for (map<int, ObjectAllocatorBaseGetter>::iterator it = wrappers.begin(); it != wrappers.end(); it++) { m_allocators[it->first] = it->second(); assert(it->second() != nullptr); } m_mm = MemoryManager::TheMemoryManager(); m_profiler = nullptr; m_pendingException = nullptr; m_coverage = new CodeCoverage(); Transl::TargetCache::threadInit(); onSessionInit(); Lock lock(s_thread_info_mutex); s_thread_infos.insert(this); } ThreadInfo::~ThreadInfo() { t_stackbase = 0; Lock lock(s_thread_info_mutex); s_thread_infos.erase(this); delete m_coverage; Transl::TargetCache::threadExit(); } bool ThreadInfo::valid(ThreadInfo* info) { Lock lock(s_thread_info_mutex); return s_thread_infos.find(info) != s_thread_infos.end(); } void ThreadInfo::GetExecutionSamples(std::map<Executing, int> &counts) { Lock lock(s_thread_info_mutex); for (std::set<ThreadInfo*>::const_iterator iter = s_thread_infos.begin(); iter != s_thread_infos.end(); ++iter) { ++counts[(*iter)->m_executing]; } } void ThreadInfo::onSessionInit() { m_reqInjectionData.onSessionInit(); // Take the address of the cached per-thread stackLimit, and use this to allow // some slack for (a) stack usage above the caller of reset() and (b) stack // usage after the position gets checked. // If we're not in a threaded environment, then Util::s_stackSize will be // zero. Use getrlimit to figure out what the size of the stack is to // calculate an approximation of where the bottom of the stack should be. if (Util::s_stackSize == 0) { struct rlimit rl; getrlimit(RLIMIT_STACK, &rl); m_stacklimit = t_stackbase - (rl.rlim_cur - StackSlack); } else { m_stacklimit = (char *)Util::s_stackLimit + StackSlack; assert(uintptr_t(m_stacklimit) < (Util::s_stackLimit + Util::s_stackSize)); } } void ThreadInfo::clearPendingException() { m_reqInjectionData.clearPendingExceptionFlag(); if (m_pendingException != nullptr) delete m_pendingException; m_pendingException = nullptr; } void ThreadInfo::setPendingException(Exception* e) { m_reqInjectionData.setPendingExceptionFlag(); if (m_pendingException != nullptr) delete m_pendingException; m_pendingException = e; } void ThreadInfo::onSessionExit() { m_reqInjectionData.reset(); Transl::TargetCache::requestExit(); } void RequestInjectionData::onSessionInit() { Transl::TargetCache::requestInit(); cflagsPtr = Transl::TargetCache::conditionFlagsPtr(); reset(); started = time(0); } void RequestInjectionData::reset() { __sync_fetch_and_and(getConditionFlags(), 0); m_coverage = RuntimeOption::RecordCodeCoverage; m_debugger = false; m_debuggerIntr = false; updateJit(); while (!interrupts.empty()) interrupts.pop(); } void RequestInjectionData::updateJit() { m_jit = RuntimeOption::EvalJit && !(RuntimeOption::EvalJitDisabledByHphpd && m_debugger) && !m_debuggerIntr && !m_coverage && !shouldProfile(); } void RequestInjectionData::setMemExceededFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::MemExceededFlag); } void RequestInjectionData::setTimedOutFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::TimedOutFlag); } void RequestInjectionData::setSignaledFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::SignaledFlag); } void RequestInjectionData::setEventHookFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::EventHookFlag); } void RequestInjectionData::clearEventHookFlag() { __sync_fetch_and_and(getConditionFlags(), ~RequestInjectionData::EventHookFlag); } void RequestInjectionData::setPendingExceptionFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::PendingExceptionFlag); } void RequestInjectionData::clearPendingExceptionFlag() { __sync_fetch_and_and(getConditionFlags(), ~RequestInjectionData::PendingExceptionFlag); } void RequestInjectionData::setInterceptFlag() { __sync_fetch_and_or(getConditionFlags(), RequestInjectionData::InterceptFlag); } void RequestInjectionData::clearInterceptFlag() { __sync_fetch_and_and(getConditionFlags(), ~RequestInjectionData::InterceptFlag); } ssize_t RequestInjectionData::fetchAndClearFlags() { return __sync_fetch_and_and(getConditionFlags(), (RequestInjectionData::EventHookFlag | RequestInjectionData::InterceptFlag)); } /////////////////////////////////////////////////////////////////////////////// }
/* Receive UDP */ void receiveUdp(int idx) { struct missedDataNack missedData; long int seqNum = 0; char buffer[DGRAM_SIZE + 8]; struct sockaddr_in clientAddr, serverAddr; socklen_t clientAddrLen; int udpSocket, rc; long int recvSize = 0; int yes = 1; /* TBD: exactLocation */ long int exactLocation = 0; long int recvDataSize = 0; /* NACK */ long int expectedSeqNum = 0; int i = 0; /* lets do some time out */ /*struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000;*/ for (i = 0; i < idx; i++) { exactLocation += splitSize[idx]; } udpSocket = socket(AF_INET, SOCK_DGRAM, 0); if (udpSocket < 0) { cout << "Error: Creating Socket" << endl; exit(1); } if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { cout << "Error: Setting Socket Options" << endl; exit(1); } /*if (setsockopt(udpSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { cout << "Error: Setting Socket Options\n"); exit(1); } long int n = 1024 * 100; //experiment with it if (setsockopt(udpSocket, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n)) == -1) { cout << "Error: Setting Socket Options" << endl; exit(1); }*/ serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(UDP_PORT_NO + idx); //fprintf(stdout, "Listening on Port: %d\n", ntohs(serverAddr.sin_port)); if (bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) { cout << "Error: Binding to Socket " << ntohs(serverAddr.sin_port) << endl; exit(1); } clientAddrLen = sizeof(clientAddr); while (expectedSeqNum < splitSize[idx]) { bzero((char *) buffer, sizeof(buffer)); rc = recvfrom(udpSocket, buffer, sizeof(buffer), 0, (struct sockaddr *) &clientAddr, &clientAddrLen); if (rc < 0) { cout << "Error: Receiving Data" << endl; exit(1); } totalPackets[idx]++; memcpy(&seqNum, buffer, sizeof(long int)); seqNum = ntohl(seqNum); memcpy(&recvDataSize, (buffer + 4), sizeof(long int)); recvDataSize = ntohl(recvDataSize); recvSize += recvDataSize; //printf("Got seqNum: %ld, size: %d\n", seqNum, rc); if (expectedSeqNum < seqNum) { while (expectedSeqNum < seqNum) { /* need to get Locking */ pthread_mutex_lock(&nackLock); missedData.idx = idx; missedData.missedSeq = expectedSeqNum; missedDataSet.insert(missedData); expectedSeqNum += recvDataSize; missedDataPtr++; pthread_mutex_unlock(&nackLock); } expectedSeqNum += recvDataSize; memcpy((file + exactLocation + seqNum), (buffer + 8), recvDataSize); } else if (expectedSeqNum == seqNum) { expectedSeqNum += recvDataSize; memcpy((file + exactLocation + seqNum), (buffer + 8), recvDataSize); }else{ //OutofOrder /* got a packet out of order need to handle */ pthread_mutex_lock(&nackLock); missedData.idx = idx; missedData.missedSeq = seqNum; missedDataSet.erase(missedData); missedDataPtr--; pthread_mutex_unlock(&nackLock); memcpy((file + exactLocation + seqNum), (buffer + 8), recvDataSize); } //printf("Data Read: %d, Total Received Size: %ld SeqNum: %ld\n", rc, recvSize, seqNum); } totalRecvSize += recvSize; }
void MessageWndEdit::FindGameWords() { // add player and empire names for (EmpireManager::const_iterator it = Empires().begin(); it != Empires().end(); ++it) { m_game_words.insert(it->second->Name()); m_game_words.insert(it->second->PlayerName()); } // add system names std::vector<TemporaryPtr<System> > systems = GetUniverse().Objects().FindObjects<System>(); for (unsigned int i = 0; i < systems.size(); ++i) { if (systems[i]->Name() != "") m_game_words.insert(systems[i]->Name()); } // add ship names std::vector<TemporaryPtr<Ship> > ships = GetUniverse().Objects().FindObjects<Ship>(); for (unsigned int i = 0; i < ships.size(); ++i) { if (ships[i]->Name() != "") m_game_words.insert(ships[i]->Name()); } // add ship design names for (PredefinedShipDesignManager::iterator it = GetPredefinedShipDesignManager().begin(); it != GetPredefinedShipDesignManager().end(); ++it) { if (it->second->Name() != "") m_game_words.insert(UserString(it->second->Name())); } // add specials names std::vector<std::string> specials = SpecialNames(); for (unsigned int i = 0; i < specials.size(); ++i) { if (specials[i] != "") m_game_words.insert(UserString(specials[i])); } // add species names for (SpeciesManager::iterator it = GetSpeciesManager().begin(); it != GetSpeciesManager().end(); ++it) { if (it->second->Name() != "") m_game_words.insert(UserString(it->second->Name())); } // add techs names std::vector<std::string> techs = GetTechManager().TechNames(); for (unsigned int i = 0; i < techs.size(); ++i) { if (techs[i] != "") m_game_words.insert(UserString(techs[i])); } // add building type names for (BuildingTypeManager::iterator it = GetBuildingTypeManager().begin(); it != GetBuildingTypeManager().end(); ++it) { if (it->second->Name() != "") m_game_words.insert(UserString(it->second->Name())); } // add ship hulls for (PredefinedShipDesignManager::iterator it = GetPredefinedShipDesignManager().begin(); it != GetPredefinedShipDesignManager().end(); ++it) { if (it->second->Hull() != "") m_game_words.insert(UserString(it->second->Hull())); } // add ship parts for (PredefinedShipDesignManager::iterator it = GetPredefinedShipDesignManager().begin(); it != GetPredefinedShipDesignManager().end(); ++it) { const std::vector<std::string>& parts = it->second->Parts(); for (std::vector<std::string>::const_iterator it1 = parts.begin(); it1 != parts.end(); ++it1) { if (*it1 != "") m_game_words.insert(UserString(*it1)); } } }
void String::getCharSet(std::set<unsigned int> &cset) const { for(std::vector<unsigned int>::const_iterator itr = d_str.begin(); itr != d_str.end(); itr++) { cset.insert( *itr ); } }
bool ConsoleAdapter::consoleInputBox_KeyUp(const CEGUI::EventArgs& args) { const CEGUI::KeyEventArgs& keyargs = static_cast<const CEGUI::KeyEventArgs&>(args); if (keyargs.scancode != CEGUI::Key::Tab) { mTabPressed = false; } switch (keyargs.scancode) { case CEGUI::Key::ArrowUp: { if (mBackend->getHistory().getHistoryPosition() == 0) { mCommandLine = mInputBox->getText().c_str(); } else { // we are not at the command line but in the history // => write back the editing mBackend->getHistory().changeHistory(mBackend->getHistory().getHistoryPosition(), mInputBox->getText().c_str()); } mBackend->getHistory().moveBackwards(); if (mBackend->getHistory().getHistoryPosition() != 0) { mInputBox->setText(mBackend->getHistory().getHistoryString()); } return true; } case CEGUI::Key::ArrowDown: { if (mBackend->getHistory().getHistoryPosition() > 0) { mBackend->getHistory().changeHistory(mBackend->getHistory().getHistoryPosition(), mInputBox->getText().c_str()); mBackend->getHistory().moveForwards(); if (mBackend->getHistory().getHistoryPosition() == 0) { mInputBox->setText(mCommandLine); } else { mInputBox->setText(mBackend->getHistory().getHistoryString()); } } return true; } case CEGUI::Key::Tab: { std::string sCommand(mInputBox->getText().c_str()); // only process commands if (sCommand[0] != '/') { return true; } sCommand = sCommand.substr(1, mInputBox->getCaratIndex() - 1); if (mTabPressed == true) { const std::set<std::string> commands(mBackend->getPrefixes(sCommand)); //std::cout << sCommand << std::endl; if (commands.size() > 0) { std::set<std::string>::const_iterator iCommand(commands.begin()); std::string sMessage(""); mSelected = (mSelected + 1) % commands.size(); int select(0); while (iCommand != commands.end()) { if (select == mSelected) { std::string sCommandLine(mInputBox->getText().c_str()); // compose the new command line: old text before the caret + selected command mInputBox->setText(sCommandLine.substr(0, mInputBox->getCaratIndex()) + iCommand->substr(mInputBox->getCaratIndex() - 1)); mInputBox->setSelection(mInputBox->getCaratIndex(), 0xFFFFFFFF); } sMessage += *iCommand + ' '; ++iCommand; ++select; } mBackend->pushMessage(sMessage); } } else { mTabPressed = true; mSelected = 0; const std::set<std::string> commands(mBackend->getPrefixes(sCommand)); if (commands.size() == 0) { // TODO: Error reporting? } else { // if any command starts with the current prefix if (commands.size() == 1) { mInputBox->setText(std::string("/") + *(commands.begin()) + ' '); // this will be at the end of the text mInputBox->setCaratIndex(0xFFFFFFFF); } else { //If there are multiple matches we need to find the lowest common denominator. We'll do this by iterating through all characters and then checking with all the possible commands if they match that prefix, until we get a false. std::set<std::string>::const_iterator iSelected(commands.begin()); std::set<std::string>::const_iterator iCommand(commands.begin()); std::string sCommonPrefix(*iCommand); int select = 1; ++iCommand; while (iCommand != commands.end()) { if (select == mSelected) { iSelected = iCommand; } std::string::size_type i(0); while ((i < sCommonPrefix.length()) && (i < (*iCommand).length())) { if (sCommonPrefix[i] != (*iCommand)[i]) { break; } ++i; } if (i < sCommonPrefix.length()) { sCommonPrefix = sCommonPrefix.substr(0, i); } ++select; ++iCommand; } mInputBox->setText(std::string("/") + sCommonPrefix + iSelected->substr(sCommonPrefix.length())); mInputBox->setCaratIndex(sCommonPrefix.length() + 1); mInputBox->setSelection(sCommonPrefix.length() + 1, 0xFFFFFFFF); } } } return true; } case CEGUI::Key::Return: case CEGUI::Key::NumpadEnter: { if (mReturnKeyDown) { mReturnKeyDown = false; if (mInputBox->getSelectionLength() > 0) { unsigned long ulSelectionEnd(mInputBox->getSelectionEndIndex()); mInputBox->setText(mInputBox->getText() + ' '); mInputBox->setCaratIndex(ulSelectionEnd + 1); mInputBox->setSelection(mInputBox->getCaratIndex(), mInputBox->getCaratIndex()); } else { const CEGUI::String consoleText(mInputBox->getText()); mInputBox->setText(CEGUI::String("")); mBackend->pushMessage(("> " + consoleText).c_str()); // run the command mBackend->runCommand(consoleText.c_str()); EventCommandExecuted.emit(consoleText.c_str()); } } return true; } default: { break; } } return false; }
double F1Score( std::set<unsigned int>& com1, std::set<unsigned int>& com2, double* precision, double* recall) { *precision = 0.0f; *recall = 0.0f; //computing intersection unsigned int counter = 0; if( com1.size() < com2.size() ) { for( std::set<unsigned int>::iterator iterCom1 = com1.begin(); iterCom1 != com1.end(); iterCom1++ ) { if( com2.find( *iterCom1 ) != com2.end() ) { counter++; } } } else { for( std::set<unsigned int>::iterator iterCom2 = com2.begin(); iterCom2 != com2.end(); iterCom2++ ) { if( com1.find( *iterCom2 ) != com1.end() ) { counter++; } } } *precision = counter / (double) com1.size(); *recall = counter / (double) com2.size(); if( *precision + *recall > 0.0f ){ return 2*(*precision)*(*recall)/((*precision) + (*recall)); } return 0.0f; }
void ComputeSSO::PrintTainted(std::set<GraphNode*> tainted) { // errs()<<"\n\n Tainted Nodes: "<<tainted.size(); for(set<GraphNode*>::iterator taintNode = tainted.begin();taintNode != tainted.end();++taintNode) { //errs()<<"\n Node Label : "<<(*taintNode)->getLabel(); // errs()<<"--"; if(isa<MemNode>(*taintNode)) { // errs()<<"\n is mem node"; //string nodeLab = (*taintNode)->getLabel(); // string str = "sub_42BC4"; // std::size_t found = nodeLab.find(str); // if (found!=std::string::npos || 1) { MemNode * memNew = dyn_cast<MemNode>(*taintNode); Value * val = memNew->defLocation.second; std::set<Value*> aliases = memNew->getAliases(); if(val) { errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel(); if(isa<Instruction>(val)) { Instruction * inst = dyn_cast<Instruction>(val); string funcName = inst->getParent()->getParent()->getName(); errs()<<"\n Function: "<<funcName; } val->dump(); } if(aliases.size()>0) errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel(); for(set<Value*>::iterator alVal = aliases.begin(); alVal != aliases.end();++alVal) { if(isa<Instruction>(*alVal)) { Instruction * inst = dyn_cast<Instruction>(*alVal); string funcName = inst->getParent()->getParent()->getName(); errs()<<"\n Function: "<<funcName; } (*alVal)->dump(); } } } if(isa<VarNode>(*taintNode)) { VarNode * varNew = dyn_cast<VarNode>(*taintNode); Value * val = varNew->getValue(); //->defLocation.second; if(val) { errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel(); if(isa<Instruction>(val)) { Instruction * inst = dyn_cast<Instruction>(val); string funcName = inst->getParent()->getParent()->getName(); errs()<<"\n Function: "<<funcName; } val->dump(); } } //if } }
void UpdateData::AddOutOfRangeGUID(std::set<uint64>& guids) { m_outOfRangeGUIDs.insert(guids.begin(),guids.end()); }
bool contain(const char* s) { return pset.find(pstring(s, strlen(s) + 1)) != pset.end(); }
int main() { // This test must be run with an OpenGL target const Target &target = get_jit_target_from_environment(); if (!target.has_feature(Target::OpenGL)) { fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n"); return 1; } Var x("x"); Var y("y"); Var c("c"); // This is a simple test case where there are two expressions that are not // linearly varying in terms of a loop variable and one expression that is. fprintf(stderr, "Test f0\n"); float p_value = 8.0f; Param<float> p("p"); p.set(p_value); Func f0("f0"); f0(x, y, c) = select(c == 0, 4.0f, // Constant term c == 1, p * 10.0f, // Linear expression not in terms of a loop parameter cast<float>(x) * 100.0f); // Linear expression in terms of x Image<float> out0(8, 8, 3); f0.bound(c, 0, 3); f0.glsl(x, y, c); // Run the test varyings.clear(); f0.add_custom_lowering_pass(new CountVarying); f0.realize(out0); // Check for the correct number of varying attributes if (varyings.size() != 2) { fprintf(stderr, "Error: wrong number of varying attributes: %d should be %d\n", (int)varyings.size(), 2); return 1; } // Check for correct result values out0.copy_to_host(); for (int c=0; c != out0.extent(2); ++c) { for (int y=0; y != out0.extent(1); ++y) { for (int x=0; x != out0.extent(0); ++x) { float expected; switch (c) { case 0: expected = 4.0f; break; case 1: expected = p_value * 10.0f; break; default: expected = static_cast<float>(x) * 100.0f; } float result = out0(x, y, c); if (result != expected) { fprintf(stderr, "Incorrect value: %f != %f at %d,%d,%d.\n", result, expected, x, y, c); return 1; } } } } fprintf(stderr, "Passed!\n"); // This is a more complicated test case where several expressions are linear // in all of the loop variables. This is the coordinate transformation case fprintf(stderr, "Test f1\n"); float th = 3.141592f/8.0f; float s_th = sinf(th); float c_th = cosf(th); float m[] = { c_th, -s_th, 0.0f, s_th, c_th, 0.0f }; Param<float> m0("m0"), m1("m1"), m2("m2"), m3("m3"), m4("m4"), m5("m5"); m0.set(m[0]); m1.set(m[1]); m2.set(m[2]); m3.set(m[3]); m4.set(m[4]); m5.set(m[5]); Func f1("f1"); f1(x, y, c) = select(c == 0, m0 * x + m1 * y + m2, c == 1, m3 * x + m4 * y + m5, 1.0f); f1.bound(c, 0, 3); f1.glsl(x, y, c); Image<float> out1(8, 8, 3); // Run the test varyings.clear(); f1.add_custom_lowering_pass(new CountVarying); f1.realize(out1); // Check for the correct number of varying attributes if (varyings.size() != 4) { fprintf(stderr, "Error: wrong number of varying attributes: %d should be %d\n", (int)varyings.size(), 4); return 1; } // Check for correct result values out1.copy_to_host(); for (int c=0; c != out1.extent(2); ++c) { for (int y=0; y != out1.extent(1); ++y) { for (int x=0; x != out1.extent(0); ++x) { float expected; switch (c) { case 0: expected = m[0] * x + m[1] * y + m[2]; break; case 1: expected = m[3] * x + m[4] * y + m[5]; break; default: expected = 1.0f; } float result = out1(x, y, c); // There is no defined precision requirement in this case so an // arbitrary threshold is used to compare the result of the CPU // and GPU arithmetic if (fabs(result-expected) > 0.000001f) { fprintf(stderr, "Incorrect value: %f != %f at %d,%d,%d.\n", result, expected, x, y, c); return 1; } } } } fprintf(stderr, "Passed!\n"); // The feature is supposed to find linearly varying sub-expressions as well // so for example, if the above expressions are wrapped in a non-linear // function like sqrt, they should still be extracted. fprintf(stderr, "Test f2\n"); Func f2("f2"); f2(x, y, c) = select(c == 0, sqrt(m0 * x + m1 * y + m2), c == 1, sqrt(m3 * x + m4 * y + m5), 1.0f); f2.bound(c, 0, 3); f2.glsl(x, y, c); Image<float> out2(8, 8, 3); // Run the test varyings.clear(); f2.add_custom_lowering_pass(new CountVarying); f2.realize(out2); // Check for the correct number of varying attributes if (varyings.size() != 4) { fprintf(stderr, "Error: wrong number of varying attributes: %d should be %d\n", (int)varyings.size(), 4); return 1; } // Check for correct result values out2.copy_to_host(); for (int c=0; c != out2.extent(2); ++c) { for (int y=0; y != out2.extent(1); ++y) { for (int x=0; x != out2.extent(0); ++x) { float expected; switch (c) { case 0: expected = sqrtf(m[0] * x + m[1] * y + m[2]); break; case 1: expected = sqrtf(m[3] * x + m[4] * y + m[5]); break; default: expected = 1.0f; } float result = out2(x, y, c); // There is no defined precision requirement in this case so an // arbitrary threshold is used to compare the result of the CPU // and GPU arithmetic if (fabs(result-expected) > 0.000001f) { fprintf(stderr, "Incorrect value: %f != %f at %d,%d,%d.\n", result, expected, x, y, c); return 1; } } } } fprintf(stderr, "Passed!\n"); // This case tests a large expression linearly varying in terms of a loop // variable fprintf(stderr, "Test f3\n"); Expr foo = p; for (int i = 0; i < 10; i++) { foo = foo+foo+foo; } foo = x + foo; float foo_value = p_value; for (int i = 0; i < 10; i++) { foo_value = foo_value+foo_value+foo_value; } Func f3("f3"); f3(x, y, c) = select(c == 0, foo, c == 1, 1.0f, 2.0f); f3.bound(c, 0, 3); f3.glsl(x, y, c); Image<float> out3(8, 8, 3); // Run the test varyings.clear(); f3.add_custom_lowering_pass(new CountVarying); f3.realize(out3); // Check for the correct number of varying attributes if (varyings.size() != 2) { fprintf(stderr, "Error: wrong number of varying attributes: %d should be %d\n", (int)varyings.size(), 2); return 1; } // Check for correct result values out3.copy_to_host(); for (int c=0; c != out3.extent(2); ++c) { for (int y=0; y != out3.extent(1); ++y) { for (int x=0; x != out3.extent(0); ++x) { float expected; switch (c) { case 0: expected = (float)x + foo_value; break; case 1: expected = 1.0f; break; default: expected = 2.0f; } float result = out3(x, y, c); // There is no defined precision requirement in this case so an // arbitrary threshold is used to compare the result of the CPU // and GPU arithmetic if (fabs(result-expected) > 0.000001f) { fprintf(stderr, "Incorrect value: %f != %f at %d,%d,%d.\n", result, expected, x, y, c); return 1; } } } } fprintf(stderr, "Passed!\n"); // The test will return early on error. fprintf(stderr, "Success!\n"); // This test may abort with the message "Failed to free device buffer" due // to https://github.com/halide/Halide/issues/559 return 0; }
/** * Removes all processes and factors from this DBN. */ void clear() { prior.clear(); transition.clear(); processes_.clear(); }
template<class T> std::set<T> GetSetIntersection( const std::set<T>& a, const std::set<T>& b ) { std::set<T> c; set_intersection( a.begin(), a.end(), b.begin(), b.end(), inserter( c, c.begin() ) ); return c; }
int main(int argc, char *argv[]) { if(argc!=6 && argc!=7 && argc!=8 && argc!=9) { printf("usage: %s sourceGeneSuffixTree reverseSourceGeneSuffixTree TargetGene minimumLength minimumRepetition [outputFile]\n", argv[0]); printf(" %s sourceGeneSuffixTree reverseSourceGeneSuffixTree TargetGeneSuffixTree reverseTargetGeneSuffixTree minimumLength minimumSourceRepetition minimumTargetRepetition [outputFile]\n", argv[0]); exit(EXIT_FAILURE); } check_target_repetitions=(argc==8 || argc==9); strncpy(st_fileName, argv[1], 49); st_fileName[49]='\0'; strncpy(rst_fileName, argv[2], 49); rst_fileName[49]='\0'; fileoutput=(argc==7 || argc==9); if(fileoutput) covering_pieces.clear(); if(check_target_repetitions) { strncpy(st2_fileName, argv[3], 49); st2_fileName[49]='\0'; strncpy(rst2_fileName, argv[4], 49); rst2_fileName[49]='\0'; l=atoi(argv[5]); minRep=atoi(argv[6]); minRep2=atoi(argv[7]); if(fileoutput) strncpy(output_fileName, argv[8], 99); } else { strncpy(target_fileName, argv[3], 49); target_fileName[49]='\0'; l=atoi(argv[4]); minRep=atoi(argv[5]); if(fileoutput) strncpy(output_fileName, argv[6], 99); } if(fileoutput) { output_fileName[99]='\0'; int filename_length=strlen(output_fileName); if(filename_length>90) { fprintf(stderr, "error: \"%s\" is too much long, use a prefix shorter 90 characters or less\n", output_fileName); exit(EXIT_FAILURE); } output_fileName[filename_length]='.'; output_fileName[filename_length+1]='l'; output_fileName[filename_length+2]='o'; output_fileName[filename_length+3]='g'; output_fileName[filename_length+4]='\0'; if((output_file=fopen(output_fileName, "w"))==NULL) { fprintf(stderr, "error: %s opening fail\n", output_fileName); exit(EXIT_FAILURE); } output_fileName[filename_length]='.'; output_fileName[filename_length+1]='p'; output_fileName[filename_length+2]='i'; output_fileName[filename_length+3]='e'; output_fileName[filename_length+4]='c'; output_fileName[filename_length+5]='e'; output_fileName[filename_length+6]='s'; output_fileName[filename_length+7]='\0'; if((output_file_pieces=fopen(output_fileName, "w"))==NULL) { fprintf(stderr, "error: %s opening fail\n", output_fileName); exit(EXIT_FAILURE); } } // intestation(); complement[C]=G; complement[G]=C; complement[A]=T; complement[T]=A; complement[X]=X; base2char[A]='A'; base2char[G]='G'; base2char[T]='T'; base2char[C]='C'; base2char[X]='X'; char2base['A']=A; char2base['G']=G; char2base['T']=T; char2base['C']=C; char2base['X']=X; // printf("Loading %s.\n", st_fileName); if((st_file=fopen(st_fileName, "r"))==NULL) { fprintf(stderr, "error: %s opening fail\n", st_fileName); exit(EXIT_FAILURE); } if(fread(&(stringLength), sizeof(int), 1, st_file)!=1) { fprintf(stderr, "failed fread of stringLength\n"); exit(EXIT_FAILURE); } s=new bpmatch_utils_base[stringLength]; if((int)fread(s, sizeof(bpmatch_utils_base), stringLength, st_file)!=stringLength) { fprintf(stderr, "failed fread of source string\n"); exit(EXIT_FAILURE); } st_root=new st_node; st_leaves=new st_node*[stringLength+2]; st_unserialize_node(st_file, st_root, st_leaves); int st_file_fd; if((st_file_fd=fileno(st_file))==-1) { fprintf(stderr, "failed getting %s file descriptor", st_fileName); exit(EXIT_FAILURE); } if(fsync(st_file_fd)!=0) { fprintf(stderr, "failed fsync of %s", st_fileName); exit(EXIT_FAILURE); } if(fclose(st_file)!=0) { fprintf(stderr, "failed fclose of %s", st_fileName); exit(EXIT_FAILURE); } // for(int i=0;i<stringLength;i++) printf("%c", base2char[s[i]]); // printf("\n"); // st_print(st_root); // printf("suffix tree unserialized.\n"); // printf("Loading %s.\n", rst_fileName); if((rst_file=fopen(rst_fileName, "r"))==NULL) { fprintf(stderr, "error: %s opening fail\n", rst_fileName); exit(EXIT_FAILURE); } if(fread(&(stringLength), sizeof(int), 1, rst_file)!=1) { fprintf(stderr, "failed fread of (reversed) stringLength\n"); exit(EXIT_FAILURE); } rs=new bpmatch_utils_base[stringLength]; if((int)fread(rs, sizeof(bpmatch_utils_base), stringLength, rst_file)!=stringLength) { fprintf(stderr, "failed fread of (reversed) source string\n"); exit(EXIT_FAILURE); } rst_root=new st_node; rst_leaves=new st_node*[stringLength+2]; st_unserialize_node(rst_file, rst_root, rst_leaves); int rst_file_fd; if((rst_file_fd=fileno(rst_file))==-1) { fprintf(stderr, "failed getting %s file descriptor", rst_fileName); exit(EXIT_FAILURE); } if(fsync(rst_file_fd)!=0) { fprintf(stderr, "failed fsync of %s", rst_fileName); exit(EXIT_FAILURE); } if(fclose(rst_file)!=0) { fprintf(stderr, "failed fclose of %s", rst_fileName); exit(EXIT_FAILURE); } // for(int i=0;i<stringLength;i++) printf("%c", base2char[rs[i]]); // printf("\n"); // st_print(rst_root); // printf("suffix tree unserialized.\n"); int trueStringLength; if(check_target_repetitions) { // printf("Loading %s.\n", st2_fileName); if((st2_file=fopen(st2_fileName, "r"))==NULL) { fprintf(stderr, "error: %s opening fail\n", st2_fileName); exit(EXIT_FAILURE); } if(fread(&(stringLength), sizeof(int), 1, st2_file)!=1) { fprintf(stderr, "failed fread of stringLength\n"); exit(EXIT_FAILURE); } t=new bpmatch_utils_base[stringLength]; if((int)fread(t, sizeof(bpmatch_utils_base), stringLength, st2_file)!=stringLength) { fprintf(stderr, "failed fread of source string\n"); exit(EXIT_FAILURE); } trueStringLength=stringLength; st2_root=new st_node; st2_leaves=new st_node*[stringLength+2]; st_unserialize_node(st2_file, st2_root, st2_leaves); int st2_file_fd; if((st2_file_fd=fileno(st2_file))==-1) { fprintf(stderr, "failed getting %s file descriptor", st2_fileName); exit(EXIT_FAILURE); } if(fsync(st2_file_fd)!=0) { fprintf(stderr, "failed fsync of %s", st2_fileName); exit(EXIT_FAILURE); } if(fclose(st2_file)!=0) { fprintf(stderr, "failed fclose of %s", st2_fileName); exit(EXIT_FAILURE); } // printf("Loading %s.\n", rst2_fileName); if((rst2_file=fopen(rst2_fileName, "r"))==NULL) { fprintf(stderr, "error: %s opening fail\n", rst2_fileName); exit(EXIT_FAILURE); } if(fread(&(stringLength), sizeof(int), 1, rst2_file)!=1) { fprintf(stderr, "failed fread of (reversed) stringLength\n"); exit(EXIT_FAILURE); } rt=new bpmatch_utils_base[stringLength]; if((int)fread(rt, sizeof(bpmatch_utils_base), stringLength, rst2_file)!=stringLength) { fprintf(stderr, "failed fread of (reversed) source string\n"); exit(EXIT_FAILURE); } rst2_root=new st_node; rst2_leaves=new st_node*[stringLength+2]; st_unserialize_node(rst2_file, rst2_root, rst2_leaves); int rst2_file_fd; if((rst2_file_fd=fileno(rst2_file))==-1) { fprintf(stderr, "failed getting %s file descriptor", rst2_fileName); exit(EXIT_FAILURE); } if(fsync(rst2_file_fd)!=0) { fprintf(stderr, "failed fsync of %s", rst2_fileName); exit(EXIT_FAILURE); } if(fclose(rst2_file)!=0) { fprintf(stderr, "failed fclose of %s", rst2_fileName); exit(EXIT_FAILURE); } } else { if((target_file=fopen(target_fileName, "r"))==NULL) { fprintf(stderr, "error: %s opening fail\n", target_fileName); exit(EXIT_FAILURE); } struct stat target_fileInfo; stat(target_fileName, &target_fileInfo); stringLength=target_fileInfo.st_size; t=new bpmatch_utils_base[stringLength+1]; trueStringLength=0; bpmatch_utils_base bp; scanBp_fasta=false; while(scanBp(target_file, &bp)!=EOF) t[trueStringLength++]=bp; t[trueStringLength++]=X; int target_file_fd; if((target_file_fd=fileno(target_file))==-1) { fprintf(stderr, "failed getting gene file descriptor"); exit(EXIT_FAILURE); } if(fsync(target_file_fd)!=0) { fprintf(stderr, "failed fsync of gene"); exit(EXIT_FAILURE); } if(fclose(target_file)!=0) { fprintf(stderr, "failed fclose of gene"); exit(EXIT_FAILURE); } } if(fileoutput) tmp_piece=new char[trueStringLength+1]; // printf("\n"); // printf("*************************************************\n"); // printf("matching - l=%d - minRep=%d\n", l, minRep); // printf("*************************************************\n"); bool end=false; bool found; int shiftTo=0; int maxPrefix, maxSuffix; int state=0; at=0; int i; int coverage=0; st_search* search_source_direct=new st_search; st_search* search_source_reverse=new st_search; st_search* search_target_direct=new st_search; st_search* search_target_reverse=new st_search; search_source_direct->root=st_root; search_source_direct->string=s; search_source_reverse->root=rst_root; search_source_reverse->string=rs; if(check_target_repetitions) { search_target_direct->root=st2_root; search_target_direct->string=t; search_target_reverse->root=rst2_root; search_target_reverse->string=rt; } while(!end) { found=false; if(state==0) { //case 0 if(DEBUG) printf("case 0\n"); //searching for direct seq i=l-1; //using reverse from actual+l-1 to actual (backward parsing) initialize_new_match(search_source_direct); initialize_new_match(search_source_reverse); if(check_target_repetitions) { initialize_new_match(search_target_direct); initialize_new_match(search_target_reverse); while(i>=0 && at+i<trueStringLength && composite_match_target_check(search_source_direct, search_source_reverse, search_target_direct, search_target_reverse, complement[t[at+i]])) i--; } else { while(i>=0 && at+i<trueStringLength && composite_match(search_source_direct, search_source_reverse, complement[t[at+i]])) i--; } if(i>=0) { //not found shiftTo=at+i+1; if(DEBUG) printf("not found [%d -> %d]\n", at, shiftTo); } else { //direct sequence found i=0; //using direct from actual (forward parsing) initialize_new_match(search_source_direct); initialize_new_match(search_source_reverse); if(check_target_repetitions) { initialize_new_match(search_target_direct); initialize_new_match(search_target_reverse); while(at+i<trueStringLength && composite_match_target_check(search_source_direct, search_source_reverse, search_target_direct, search_target_reverse, t[at+i])) i++; } else { while(at+i<trueStringLength && composite_match(search_source_direct, search_source_reverse, t[at+i])) i++; } found=true; shiftTo=at+i; if(DEBUG) printf("***************************************************found [%d -> %d]\n", at, shiftTo); } } else { //case 1 if(DEBUG) printf("case 1\n"); //searching for direct (eventually ovelapping) seq maxSuffix=0; maxPrefix=0; //using direct from actual (forward parsing) initialize_new_match(search_source_direct); initialize_new_match(search_source_reverse); if(check_target_repetitions) { initialize_new_match(search_target_direct); initialize_new_match(search_target_reverse); while(at+maxSuffix<trueStringLength && composite_match_target_check(search_source_direct, search_source_reverse, search_target_direct, search_target_reverse, t[at+maxSuffix])) maxSuffix++; } else { while(at+maxSuffix<trueStringLength && composite_match(search_source_direct, search_source_reverse, t[at+maxSuffix])) maxSuffix++; } if(maxSuffix>=l) { //direct sequence found found=true; shiftTo=at+maxSuffix; if(DEBUG) printf("1**************************************************found [%d -> %d]\n", at, shiftTo); } else { if(DEBUG) printf("compute maxPrefix\n"); //using reverse from actual (backward parsing) initialize_new_match(search_source_direct); initialize_new_match(search_source_reverse); if(check_target_repetitions) { initialize_new_match(search_target_direct); initialize_new_match(search_target_reverse); while(maxPrefix<l && at-maxPrefix>=0 && composite_match_target_check(search_source_direct, search_source_reverse, search_target_direct, search_target_reverse, complement[t[at-maxPrefix]])) maxPrefix++; } else { while(maxPrefix<l && at-maxPrefix>=0 && composite_match(search_source_direct, search_source_reverse, complement[t[at-maxPrefix]])) maxPrefix++; } maxPrefix--; while(!found && maxPrefix+maxSuffix>=l) { if(DEBUG) printf("*ite %d-%d\n", maxPrefix, maxSuffix); i=maxSuffix-l; //using direct from actual (forward parsing) initialize_new_match(search_source_direct); initialize_new_match(search_source_reverse); if(check_target_repetitions) { initialize_new_match(search_target_direct); initialize_new_match(search_target_reverse); while(at+i<trueStringLength && composite_match_target_check(search_source_direct, search_source_reverse, search_target_direct, search_target_reverse, t[at+i])) i++; } else { while(at+i<trueStringLength && composite_match(search_source_direct, search_source_reverse, t[at+i])) i++; } if(i==maxSuffix) { //direct sequence found found=true; shiftTo=at+maxSuffix; } else { if(DEBUG) printf("error at %d\n", i); maxSuffix=i; } } if(!found) { //not found shiftTo=at+1; } } } if(found) { if(fileoutput) { fprintf(output_file, "%i,", at); if(state==1) { fprintf(output_file, "*"); for(int j=shiftTo-l;j<shiftTo;j++) tmp_piece[j-shiftTo+l]=base2char[t[j]]; tmp_piece[l]='\0'; } else { for(int j=at;j<shiftTo;j++) tmp_piece[j-at]=base2char[t[j]]; tmp_piece[shiftTo-at]='\0'; } for(int j=at;j<shiftTo;j++) fprintf(output_file, "%c", base2char[t[j]]); if(check_target_repetitions) fprintf(output_file, ",direct-reverse:%d-%d,targetrepetitionsdirect-reverse:%d-%d\n", last_valid_direct_count, last_valid_reverse_count, last_valid_direct_count_target, last_valid_reverse_count_target); else fprintf(output_file, ",direct-reverse:%d-%d\n", last_valid_direct_count, last_valid_reverse_count); covering_pieces.insert(std::string(tmp_piece)); } coverage+=shiftTo-at; state=1; } else state=0; at=shiftTo; if(at>=trueStringLength) end=true; } // printf("\n\ncoverage: %d/%d\n", coverage, trueStringLength-1); printf("%f\n", (double(coverage))/((double)(trueStringLength-1))); if(fileoutput) { fprintf(output_file, "\ncoverage: %d/%d\n", coverage, trueStringLength-1); fprintf(output_file, "%f\n", (double(coverage))/((double)(trueStringLength-1))); if(fclose(output_file)!=0) { fprintf(stderr, "failed fclose of output"); exit(EXIT_FAILURE); } int search_index; for(covering_pieces_ite=covering_pieces.begin();covering_pieces_ite!=covering_pieces.end();covering_pieces_ite++) { fprintf(output_file_pieces, "SEGMENT: %s\n", covering_pieces_ite->data()); fprintf(output_file_pieces, "sources direct occurrences by starting index "); initialize_new_match(search_source_direct); search_index=0; while((*covering_pieces_ite)[search_index]!='\0') search_source_direct->current_count=single_match(search_source_direct, char2base[(int)(*covering_pieces_ite)[search_index++]]); fprintf(output_file_pieces, "(%d) :", search_source_direct->current_count); if(search_source_direct->current_count>0) { if(search_source_direct->current_node->leafId==0) { //internal node for(int i=search_source_direct->current_node->firstLeaf;i<=search_source_direct->current_node->lastLeaf;i++) { fprintf(output_file_pieces, " %d", st_root->lastLeaf-st_leaves[i]->length); } } else { //leaf fprintf(output_file_pieces, " %d", st_root->lastLeaf-search_source_direct->current_node->length); } } fprintf(output_file_pieces, "\n"); fprintf(output_file_pieces, "sources reverse occurrences by starting index "); initialize_new_match(search_source_reverse); search_index=0; while((*covering_pieces_ite)[search_index]!='\0') search_source_reverse->current_count=single_match(search_source_reverse, char2base[(int)(*covering_pieces_ite)[search_index++]]); fprintf(output_file_pieces, "(%d) :", search_source_reverse->current_count); if(search_source_reverse->current_count>0) { if(search_source_reverse->current_node->leafId==0) { //internal node for(int i=search_source_reverse->current_node->firstLeaf;i<=search_source_reverse->current_node->lastLeaf;i++) { fprintf(output_file_pieces, " %d", st_root->lastLeaf-st_leaves[i]->length); } } else { //leaf fprintf(output_file_pieces, " %d", st_root->lastLeaf-search_source_reverse->current_node->length); } } fprintf(output_file_pieces, "\n"); if(check_target_repetitions) { fprintf(output_file_pieces, "target direct occurrences by starting index "); initialize_new_match(search_target_direct); search_index=0; while((*covering_pieces_ite)[search_index]!='\0') search_target_direct->current_count=single_match(search_target_direct, char2base[(int)(*covering_pieces_ite)[search_index++]]); fprintf(output_file_pieces, "(%d) :", search_target_direct->current_count); if(search_target_direct->current_count>0) { if(search_target_direct->current_node->leafId==0) { //internal node for(int i=search_target_direct->current_node->firstLeaf;i<=search_target_direct->current_node->lastLeaf;i++) { fprintf(output_file_pieces, " %d", st2_root->lastLeaf-st_leaves[i]->length); } } else { //leaf fprintf(output_file_pieces, " %d", st2_root->lastLeaf-search_target_direct->current_node->length); } } fprintf(output_file_pieces, "\n"); fprintf(output_file_pieces, "target reverse occurrences by starting index "); initialize_new_match(search_target_reverse); search_index=0; while((*covering_pieces_ite)[search_index]!='\0') search_target_reverse->current_count=single_match(search_target_reverse, char2base[(int)(*covering_pieces_ite)[search_index++]]); fprintf(output_file_pieces, "(%d) :", search_target_reverse->current_count); if(search_target_reverse->current_count>0) { if(search_target_reverse->current_node->leafId==0) { //internal node for(int i=search_target_reverse->current_node->firstLeaf;i<=search_target_reverse->current_node->lastLeaf;i++) { fprintf(output_file_pieces, " %d", st2_root->lastLeaf-st_leaves[i]->length); } } else { //leaf fprintf(output_file_pieces, " %d", st2_root->lastLeaf-search_target_reverse->current_node->length); } } fprintf(output_file_pieces, "\n"); } fprintf(output_file_pieces, "\n"); } if(fclose(output_file_pieces)!=0) { fprintf(stderr, "failed fclose of output"); exit(EXIT_FAILURE); } delete[] tmp_piece; } // printf("\ncoverage: %d/%d\n", coverage, trueStringLength, subSeqId); // printf("%f (%d sequences used)\n\n", double(coverage)/double(trueStringLength-1), subSeqId); /// printf("%f", double(coverage)/double(trueStringLength-1)); delete[] st_leaves; st_free_node(st_root); delete[] rst_leaves; st_free_node(rst_root); delete[] s; delete[] rs; if(check_target_repetitions) { delete[] st2_leaves; st_free_node(st2_root); delete[] rst2_leaves; st_free_node(rst2_root); delete[] rt; } delete[] t; // printf("termination reached without errors\n"); exit(EXIT_SUCCESS); }
bool HandleArgs(int argc, char** argv, uint32& threads, std::set<uint32>& mapList, bool& debugOutput, uint32& extractFlags) { char* param = NULL; extractFlags = 0; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--threads") == 0) { param = argv[++i]; if (!param) return false; threads = atoi(param); printf("Using %u threads\n", threads); } else if (strcmp(argv[i], "--maps") == 0) { param = argv[++i]; if (!param) return false; char* copy = strdup(param); char* token = strtok(copy, ","); while (token) { mapList.insert(atoi(token)); token = strtok(NULL, ","); } free(copy); printf("Extracting only provided list of maps (%u).\n", uint32(mapList.size())); } else if (strcmp(argv[i], "--debug") == 0) { param = argv[++i]; if (!param) return false; debugOutput = atoi(param); if (debugOutput) printf("Output will contain debug information (.obj files)\n"); } else if (strcmp(argv[i], "--extract") == 0) { param = argv[++i]; if (!param) return false; extractFlags = atoi(param); if (!(extractFlags & Constants::EXTRACT_FLAG_ALLOWED)) // Tried to use an invalid flag return false; printf("Detected flags: \n"); printf("* Extract DBCs: %s\n", (extractFlags & Constants::EXTRACT_FLAG_DBC) ? "Yes" : "No"); printf("* Extract Maps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_MAPS) ? "Yes" : "No"); printf("* Extract VMaps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_VMAPS) ? "Yes" : "No"); printf("* Extract GameObject Models: %s\n", (extractFlags & Constants::EXTRACT_FLAG_GOB_MODELS) ? "Yes" : "No"); printf("* Extract MMaps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_MMAPS) ? "Yes" : "No"); } } return true; }
bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); }
bool is_ignored(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); }
namespace WindowsRawInput { static std::set<int> keyboardKeysDown; static void *rawInputBuffer; static size_t rawInputBufferSize; static bool menuActive; static bool focused = true; static bool mouseRightDown = false; void Init() { RAWINPUTDEVICE dev[3]; memset(dev, 0, sizeof(dev)); dev[0].usUsagePage = HID_USAGE_PAGE_GENERIC; dev[0].usUsage = HID_USAGE_GENERIC_KEYBOARD; dev[0].dwFlags = g_Config.bIgnoreWindowsKey ? RIDEV_NOHOTKEYS : 0; dev[1].usUsagePage = HID_USAGE_PAGE_GENERIC; dev[1].usUsage = HID_USAGE_GENERIC_MOUSE; dev[1].dwFlags = 0; dev[2].usUsagePage = HID_USAGE_PAGE_GENERIC; dev[2].usUsage = HID_USAGE_GENERIC_JOYSTICK; dev[2].dwFlags = 0; if (!RegisterRawInputDevices(dev, 3, sizeof(RAWINPUTDEVICE))) { WARN_LOG(COMMON, "Unable to register raw input devices: %s", GetLastErrorMsg()); } } bool UpdateMenuActive() { MENUBARINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); if (GetMenuBarInfo(MainWindow::GetHWND(), OBJID_MENU, 0, &info) != 0) { menuActive = info.fBarFocused != FALSE; } else { // In fullscreen mode, we remove the menu menuActive = false; } return menuActive; } static int GetTrueVKey(const RAWKEYBOARD &kb) { int vKey = kb.VKey; switch (kb.VKey) { case VK_SHIFT: vKey = MapVirtualKey(kb.MakeCode, MAPVK_VSC_TO_VK_EX); break; case VK_CONTROL: if (kb.Flags & RI_KEY_E0) vKey = VK_RCONTROL; else vKey = VK_LCONTROL; break; case VK_MENU: if (kb.Flags & RI_KEY_E0) vKey = VK_RMENU; // Right Alt / AltGr else vKey = VK_LMENU; // Left Alt //case VK_RETURN: // if (kb.Flags & RI_KEY_E0) // vKey = VK_RETURN; // Numeric return - no code for this. Can special case. // break; // Source: http://molecularmusings.wordpress.com/2011/09/05/properly-handling-keyboard-input/ case VK_NUMLOCK: // correct PAUSE/BREAK and NUM LOCK silliness, and set the extended bit vKey = MapVirtualKey(kb.VKey, MAPVK_VK_TO_VSC) | 0x100; break; default: break; } return windowsTransTable[vKey]; } void ProcessKeyboard(RAWINPUT *raw, bool foreground) { if (menuActive && UpdateMenuActive()) { // Ignore keyboard input while a menu is active, it's probably interacting with the menu. return; } KeyInput key; key.deviceId = DEVICE_ID_KEYBOARD; if (raw->data.keyboard.Message == WM_KEYDOWN || raw->data.keyboard.Message == WM_SYSKEYDOWN) { key.flags = KEY_DOWN; key.keyCode = GetTrueVKey(raw->data.keyboard); if (key.keyCode) { NativeKey(key); keyboardKeysDown.insert(key.keyCode); } } else if (raw->data.keyboard.Message == WM_KEYUP) { key.flags = KEY_UP; key.keyCode = GetTrueVKey(raw->data.keyboard); if (key.keyCode) { NativeKey(key); auto keyDown = std::find(keyboardKeysDown.begin(), keyboardKeysDown.end(), key.keyCode); if (keyDown != keyboardKeysDown.end()) keyboardKeysDown.erase(keyDown); } } } LRESULT ProcessChar(HWND hWnd, WPARAM wParam, LPARAM lParam) { KeyInput key; key.keyCode = wParam; // Note that this is NOT a NKCODE but a Unicode character! key.flags = KEY_CHAR; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); return 0; } static bool MouseInWindow(HWND hWnd) { POINT pt; if (GetCursorPos(&pt) != 0) { RECT rt; if (GetWindowRect(hWnd, &rt) != 0) { return PtInRect(&rt, pt) != 0; } } return true; } void ProcessMouse(HWND hWnd, RAWINPUT *raw, bool foreground) { if (menuActive && UpdateMenuActive()) { // Ignore mouse input while a menu is active, it's probably interacting with the menu. return; } TouchInput touch; touch.id = 0; touch.flags = TOUCH_MOVE; touch.x = input_state.pointer_x[0]; touch.y = input_state.pointer_y[0]; KeyInput key; key.deviceId = DEVICE_ID_MOUSE; mouseDeltaX += raw->data.mouse.lLastX; mouseDeltaY += raw->data.mouse.lLastY; if (raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN) { key.flags = KEY_DOWN; key.keyCode = windowsTransTable[VK_RBUTTON]; NativeTouch(touch); if (MouseInWindow(hWnd)) { NativeKey(key); } mouseRightDown = true; } else if (raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP) { key.flags = KEY_UP; key.keyCode = windowsTransTable[VK_RBUTTON]; NativeTouch(touch); if (MouseInWindow(hWnd)) { if (!mouseRightDown) { // This means they were focused outside, and right clicked inside. // Seems intentional, so send a down first. key.flags = KEY_DOWN; NativeKey(key); key.flags = KEY_UP; NativeKey(key); } else { NativeKey(key); } } mouseRightDown = false; } // TODO : Smooth and translate to an axis every frame. // NativeAxis() } void ProcessHID(RAWINPUT *raw, bool foreground) { // TODO: Use hidparse or something to understand the data. } LRESULT Process(HWND hWnd, WPARAM wParam, LPARAM lParam) { UINT dwSize; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); if (!rawInputBuffer) { rawInputBuffer = malloc(dwSize); rawInputBufferSize = dwSize; } if (dwSize > rawInputBufferSize) { rawInputBuffer = realloc(rawInputBuffer, dwSize); } GetRawInputData((HRAWINPUT)lParam, RID_INPUT, rawInputBuffer, &dwSize, sizeof(RAWINPUTHEADER)); RAWINPUT *raw = (RAWINPUT *)rawInputBuffer; bool foreground = GET_RAWINPUT_CODE_WPARAM(wParam) == RIM_INPUT; switch (raw->header.dwType) { case RIM_TYPEKEYBOARD: ProcessKeyboard(raw, foreground); break; case RIM_TYPEMOUSE: ProcessMouse(hWnd, raw, foreground); break; case RIM_TYPEHID: ProcessHID(raw, foreground); break; } // Docs say to call DefWindowProc to perform necessary cleanup. return DefWindowProc(hWnd, WM_INPUT, wParam, lParam); } void GainFocus() { focused = true; } void LoseFocus() { // Force-release all held keys on the keyboard to prevent annoying stray inputs. KeyInput key; key.deviceId = DEVICE_ID_KEYBOARD; key.flags = KEY_UP; for (auto i = keyboardKeysDown.begin(); i != keyboardKeysDown.end(); ++i) { key.keyCode = *i; NativeKey(key); } focused = false; } void NotifyMenu() { UpdateMenuActive(); } void Shutdown() { if (rawInputBuffer) { free(rawInputBuffer); } rawInputBuffer = 0; } };
void Process::Release( Process*& worker ) { g_Workers.erase( worker ); worker = NULL; }
void doSearch( Utility::MTInput & input, Utility::MTOutput & mtOutput, Utility::MTOutput & mtConsoleOutput, size_t startLine ) const { Poco::Net::HTTPClientSession session( m_uri.getHost(), m_uri.getPort() ); { Utility::MTOutput::unique_lock lock( mtConsoleOutput.acquire()); mtConsoleOutput.os() << "Thread " << pthread_self() << " starting "; mtConsoleOutput.flush(); } std::string line; while( size_t lineNum = input.getline( line )) { if( lineNum < startLine ) continue; std::string path; bool success = false; size_t maxTries = 4; while( !success && maxTries ) { try { Utility::StrTuple term = Utility::delimitedText( line, '\t' ); if( term.size() < 4 ) break; std::string artist = term[2]; std::string title = Utility::trim(term[3]); path = make_request( artist + ' ' + title ); Poco::Net::HTTPRequest request( Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1 ); Poco::Net::HTTPResponse response; session.sendRequest(request); std::istream& rs = session.receiveResponse(response); using Poco::Dynamic::Var; using namespace Poco::JSON; Parser parser; Var result = parser.parse(rs); Object::Ptr obj = result.extract<Object::Ptr>(); int nResults = obj->getValue<int>("resultCount"); { Utility::MTOutput::unique_lock lock( mtConsoleOutput.acquire()); mtConsoleOutput.os() << lineNum << ": " << path << ' ' << nResults << " results " << std::endl; } if( nResults ) { Array::Ptr arr; arr = obj->getArray( "results" ); if( !arr ) { std::cerr << "Could not get results " << std::endl; continue; } std::string releaseDate; std::string genre; std::string artistName; // on iTunes std::string trackName; // on iTunes bool found = false; // if there is more than one see if there is an exact match. Otherwise use the first result for( size_t i = 0; !found && i < nResults ; ++i ) { Object::Ptr result = arr->getObject(i); if( !result ) { std::cerr << " Could not get result " << i << std::endl; continue; } // get ArtistName and Title and see if they match ours Var item = result->get( "artistName" ); if( item.isString() ) artistName = item.convert< std::string >(); item = result->get( "trackName" ); if( item.isString() ) trackName = item.convert< std::string >(); if( (artistName == artist && trackName == title) ) // we have an exact match so continue found = true; // if no exact matches are found we use the first one. // We could use a better way to match the search eg case insensitive, removing featured acts etc. if( found || i == 0 ) { item = result->get( "releaseDate"); if( item.isString() ) { std::string releaseDateStr = item.convert< std::string >(); releaseDate = releaseDateStr.substr( 0, releaseDateStr.find('T') ); } item = result->get( "primaryGenreName" ); if( item.isString() ) genre = item.convert< std::string >(); } } if( m_filteredGenres.count( genre ) == 0 ) { Utility::MTOutput::unique_lock lock( mtOutput.acquire()); // output the result. Spotify link, artist(spotify), title(spotify) // artist(iTunes), title(iTunes), releaseDate, genre, numTracks (term[4]) mtOutput.os() << lineNum << '\t' << term[0] << '\t' << term[1] << '\t' << artist << '\t' << title << '\t' << artistName << '\t' << trackName << '\t' << releaseDate << '\t' << genre << '\t' << term[4] << '\n'; mtOutput.flush(); } } success = true; } catch( std::exception const& err ) { success = false; if( --maxTries ) { sleep(1); } else { Utility::MTOutput::unique_lock lock( mtConsoleOutput.acquire()); std::cerr << "ERROR: " << err.what() << lineNum << ": " << path << std::endl; } } } } { Utility::MTOutput::unique_lock lock( mtConsoleOutput.acquire()); mtConsoleOutput.os() << "Thread " << pthread_self() << " exiting\n"; mtConsoleOutput.flush(); } }
void Process::ReleaseAll() { g_Workers.clear(); }
bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32>& mapids) { if (pathid >= sTaxiPathNodesByPath.size()) return false; TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathid]; std::vector<keyFrame> keyFrames; int mapChange = 0; mapids.clear(); for (size_t i = 1; i < path.size() - 1; ++i) { if (mapChange == 0) { TaxiPathNodeEntry const& node_i = path[i]; if (node_i.mapid == path[i + 1].mapid) { keyFrame k(node_i); keyFrames.push_back(k); mapids.insert(k.node->mapid); } else { mapChange = 1; } } else { --mapChange; } } int lastStop = -1; int firstStop = -1; // first cell is arrived at by teleportation :S keyFrames[0].distFromPrev = 0; if (keyFrames[0].node->actionFlag == 2) { lastStop = 0; } // find the rest of the distances between key points for (size_t i = 1; i < keyFrames.size(); ++i) { if ((keyFrames[i].node->actionFlag == 1) || (keyFrames[i].node->mapid != keyFrames[i - 1].node->mapid)) { keyFrames[i].distFromPrev = 0; } else { keyFrames[i].distFromPrev = sqrt(pow(keyFrames[i].node->x - keyFrames[i - 1].node->x, 2) + pow(keyFrames[i].node->y - keyFrames[i - 1].node->y, 2) + pow(keyFrames[i].node->z - keyFrames[i - 1].node->z, 2)); } if (keyFrames[i].node->actionFlag == 2) { // remember first stop frame if (firstStop == -1) firstStop = i; lastStop = i; } } float tmpDist = 0; for (size_t i = 0; i < keyFrames.size(); ++i) { int j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].node->actionFlag == 2) tmpDist = 0; else tmpDist += keyFrames[j].distFromPrev; keyFrames[j].distSinceStop = tmpDist; } for (int i = int(keyFrames.size()) - 1; i >= 0; --i) { int j = (i + (firstStop + 1)) % keyFrames.size(); tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev; keyFrames[j].distUntilStop = tmpDist; if (keyFrames[j].node->actionFlag == 2) tmpDist = 0; } for (size_t i = 0; i < keyFrames.size(); ++i) { if (keyFrames[i].distSinceStop < (30 * 30 * 0.5f)) keyFrames[i].tFrom = sqrt(2 * keyFrames[i].distSinceStop); else keyFrames[i].tFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30; if (keyFrames[i].distUntilStop < (30 * 30 * 0.5f)) keyFrames[i].tTo = sqrt(2 * keyFrames[i].distUntilStop); else keyFrames[i].tTo = ((keyFrames[i].distUntilStop - (30 * 30 * 0.5f)) / 30) + 30; keyFrames[i].tFrom *= 1000; keyFrames[i].tTo *= 1000; } // for (int i = 0; i < keyFrames.size(); ++i) { // sLog.outString("%f, %f, %f, %f, %f, %f, %f", keyFrames[i].x, keyFrames[i].y, keyFrames[i].distUntilStop, keyFrames[i].distSinceStop, keyFrames[i].distFromPrev, keyFrames[i].tFrom, keyFrames[i].tTo); // } // Now we're completely set up; we can move along the length of each waypoint at 100 ms intervals // speed = max(30, t) (remember x = 0.5s^2, and when accelerating, a = 1 unit/s^2 int t = 0; bool teleport = false; if (keyFrames[keyFrames.size() - 1].node->mapid != keyFrames[0].node->mapid) teleport = true; WayPoint pos(keyFrames[0].node->mapid, keyFrames[0].node->x, keyFrames[0].node->y, keyFrames[0].node->z, teleport); m_WayPoints[0] = pos; t += keyFrames[0].node->delay * 1000; uint32 cM = keyFrames[0].node->mapid; for (size_t i = 0; i < keyFrames.size() - 1; ++i) { float d = 0; float tFrom = keyFrames[i].tFrom; float tTo = keyFrames[i].tTo; // keep the generation of all these points; we use only a few now, but may need the others later if (((d < keyFrames[i + 1].distFromPrev) && (tTo > 0))) { while ((d < keyFrames[i + 1].distFromPrev) && (tTo > 0)) { tFrom += 100; tTo -= 100; if (d > 0) { float newX, newY, newZ; newX = keyFrames[i].node->x + (keyFrames[i + 1].node->x - keyFrames[i].node->x) * d / keyFrames[i + 1].distFromPrev; newY = keyFrames[i].node->y + (keyFrames[i + 1].node->y - keyFrames[i].node->y) * d / keyFrames[i + 1].distFromPrev; newZ = keyFrames[i].node->z + (keyFrames[i + 1].node->z - keyFrames[i].node->z) * d / keyFrames[i + 1].distFromPrev; bool teleport = false; if (keyFrames[i].node->mapid != cM) { teleport = true; cM = keyFrames[i].node->mapid; } // sLog.outString("T: %d, D: %f, x: %f, y: %f, z: %f", t, d, newX, newY, newZ); WayPoint pos(keyFrames[i].node->mapid, newX, newY, newZ, teleport); if (teleport) m_WayPoints[t] = pos; } if (tFrom < tTo) // caught in tFrom dock's "gravitational pull" { if (tFrom <= 30000) { d = 0.5f * (tFrom / 1000) * (tFrom / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tFrom - 30000) / 1000); } d = d - keyFrames[i].distSinceStop; } else { if (tTo <= 30000) { d = 0.5f * (tTo / 1000) * (tTo / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tTo - 30000) / 1000); } d = keyFrames[i].distUntilStop - d; } t += 100; } t -= 100; } if (keyFrames[i + 1].tFrom > keyFrames[i + 1].tTo) t += 100 - ((long)keyFrames[i + 1].tTo % 100); else t += (long)keyFrames[i + 1].tTo % 100; bool teleport = false; if ((keyFrames[i + 1].node->actionFlag == 1) || (keyFrames[i + 1].node->mapid != keyFrames[i].node->mapid)) { teleport = true; cM = keyFrames[i + 1].node->mapid; } WayPoint pos(keyFrames[i + 1].node->mapid, keyFrames[i + 1].node->x, keyFrames[i + 1].node->y, keyFrames[i + 1].node->z, teleport); // sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport); // if (teleport) m_WayPoints[t] = pos; t += keyFrames[i + 1].node->delay * 1000; // sLog.outString("------"); } uint32 timer = t; // sLog.outDetail(" Generated %lu waypoints, total time %u.", (unsigned long)m_WayPoints.size(), timer); m_next = m_WayPoints.begin(); // will used in MoveToNextWayPoint for init m_curr MoveToNextWayPoint(); // m_curr -> first point MoveToNextWayPoint(); // skip first point m_pathTime = timer; m_nextNodeTime = m_curr->first; return true; }
void operator()(code_block* block, cell size) { FACTOR_ASSERT(all_blocks->find((cell)block) != all_blocks->end()); }
void VKFragmentDecompilerThread::insertMainStart(std::stringstream & OS) { //TODO: Generate input mask during parse stage to avoid this for (const ParamType& PT : m_parr.params[PF_PARAM_IN]) { for (const ParamItem& PI : PT.items) { if (PI.name == "fogc") { glsl::insert_fog_declaration(OS); break; } } } const std::set<std::string> output_values = { "r0", "r1", "r2", "r3", "r4", "h0", "h2", "h4", "h6", "h8" }; std::string parameters = ""; const auto half4 = getHalfTypeName(4); for (auto ®_name : output_values) { const auto type = (reg_name[0] == 'r' || !device_props.has_native_half_support)? "vec4" : half4; if (m_parr.HasParam(PF_PARAM_NONE, type, reg_name)) { if (parameters.length()) parameters += ", "; parameters += "inout " + type + " " + reg_name; } } OS << "void fs_main(" << parameters << ")\n"; OS << "{\n"; for (const ParamType& PT : m_parr.params[PF_PARAM_NONE]) { for (const ParamItem& PI : PT.items) { if (output_values.find(PI.name) != output_values.end()) continue; OS << " " << PT.type << " " << PI.name; if (!PI.value.empty()) OS << " = " << PI.value; OS << ";\n"; } } if (m_parr.HasParam(PF_PARAM_IN, "vec4", "ssa")) OS << " vec4 ssa = gl_FrontFacing ? vec4(1.) : vec4(-1.);\n"; if (properties.has_wpos_input) OS << " vec4 wpos = get_wpos();\n"; bool two_sided_enabled = m_prog.front_back_color_enabled && (m_prog.back_color_diffuse_output || m_prog.back_color_specular_output); //Some registers require redirection for (const ParamType& PT : m_parr.params[PF_PARAM_IN]) { for (const ParamItem& PI : PT.items) { if (two_sided_enabled) { if (PI.name == "spec_color") { //Only redirect/rename variables if the back_color exists if (m_prog.back_color_specular_output) { if (m_prog.back_color_specular_output && m_prog.front_color_specular_output) { OS << " vec4 spec_color = gl_FrontFacing ? front_spec_color : back_spec_color;\n"; } else { OS << " vec4 spec_color = back_spec_color;\n"; } } continue; } else if (PI.name == "diff_color") { //Only redirect/rename variables if the back_color exists if (m_prog.back_color_diffuse_output) { if (m_prog.back_color_diffuse_output && m_prog.front_color_diffuse_output) { OS << " vec4 diff_color = gl_FrontFacing ? front_diff_color : back_diff_color;\n"; } else { OS << " vec4 diff_color = back_diff_color;\n"; } } continue; } } if (PI.name == "fogc") { OS << " vec4 fogc = fetch_fog_value(fog_mode);\n"; continue; } } } }
static void* operator new(std::size_t sz) { return *nonarrays.insert(::operator new(sz)).first; }
bool input_filter_pressed (const std::string &button) { return pressed.find(button) != pressed.end(); }
void CFileItemHandler::HandleFileItem(const char *ID, bool allowFile, const char *resultname, CFileItemPtr item, const CVariant ¶meterObject, const std::set<std::string> &validFields, CVariant &result, bool append /* = true */, CThumbLoader *thumbLoader /* = NULL */) { CVariant object; std::set<std::string> fields(validFields.begin(), validFields.end()); if (item.get()) { std::set<std::string>::const_iterator fileField = fields.find("file"); if (fileField != fields.end()) { if (allowFile) { if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->GetPath().empty()) object["file"] = item->GetVideoInfoTag()->GetPath().c_str(); if (item->HasMusicInfoTag() && !item->GetMusicInfoTag()->GetURL().empty()) object["file"] = item->GetMusicInfoTag()->GetURL().c_str(); if (!object.isMember("file")) object["file"] = item->GetPath().c_str(); } fields.erase(fileField); } if (ID) { if (item->HasPVRChannelInfoTag() && item->GetPVRChannelInfoTag()->ChannelID() > 0) object[ID] = item->GetPVRChannelInfoTag()->ChannelID(); else if (item->HasEPGInfoTag() && item->GetEPGInfoTag()->UniqueBroadcastID() > 0) object[ID] = item->GetEPGInfoTag()->UniqueBroadcastID(); else if (item->HasMusicInfoTag() && item->GetMusicInfoTag()->GetDatabaseId() > 0) object[ID] = (int)item->GetMusicInfoTag()->GetDatabaseId(); else if (item->HasVideoInfoTag() && item->GetVideoInfoTag()->m_iDbId > 0) object[ID] = item->GetVideoInfoTag()->m_iDbId; if (stricmp(ID, "id") == 0) { if (item->HasPVRChannelInfoTag()) object["type"] = "channel"; else if (item->HasMusicInfoTag()) { std::string type = item->GetMusicInfoTag()->GetType(); if (type == "album" || type == "song" || type == "artist") object["type"] = type; else object["type"] = "song"; } else if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_type.empty()) { std::string type = item->GetVideoInfoTag()->m_type; if (type == "movie" || type == "tvshow" || type == "episode" || type == "musicvideo") object["type"] = type; } else if (item->HasPictureInfoTag()) object["type"] = "picture"; if (!object.isMember("type")) object["type"] = "unknown"; if (fields.find("filetype") != fields.end()) { if (item->m_bIsFolder) object["filetype"] = "directory"; else object["filetype"] = "file"; } } } bool deleteThumbloader = false; if (thumbLoader == NULL) { if (item->HasVideoInfoTag()) thumbLoader = new CVideoThumbLoader(); else if (item->HasMusicInfoTag()) thumbLoader = new CMusicThumbLoader(); if (thumbLoader != NULL) { deleteThumbloader = true; thumbLoader->OnLoaderStart(); } } if (item->HasPVRChannelInfoTag()) FillDetails(item->GetPVRChannelInfoTag(), item, fields, object, thumbLoader); if (item->HasEPGInfoTag()) FillDetails(item->GetEPGInfoTag(), item, fields, object, thumbLoader); if (item->HasVideoInfoTag()) FillDetails(item->GetVideoInfoTag(), item, fields, object, thumbLoader); if (item->HasMusicInfoTag()) FillDetails(item->GetMusicInfoTag(), item, fields, object, thumbLoader); if (item->HasPictureInfoTag()) FillDetails(item->GetPictureInfoTag(), item, fields, object, thumbLoader); FillDetails(item.get(), item, fields, object, thumbLoader); if (deleteThumbloader) delete thumbLoader; object["label"] = item->GetLabel().c_str(); } else object = CVariant(CVariant::VariantTypeNull); if (resultname) { if (append) result[resultname].append(object); else result[resultname] = object; } }
bool ThreadInfo::valid(ThreadInfo* info) { Lock lock(s_thread_info_mutex); return s_thread_infos.find(info) != s_thread_infos.end(); }
void CGameSetup::LoadSkirmishAIs(const TdfParser& file, std::set<std::string>& nameList) { // i = AI index in game (no gaps), a = AI index in script // int i = 0; for (int a = 0; a < MAX_PLAYERS; ++a) { char section[50]; sprintf(section, "GAME\\AI%i\\", a); string s(section); if (!file.SectionExist(s.substr(0, s.length() - 1))) { continue; } SkirmishAIData data; data.team = atoi(file.SGetValueDef("-1", s + "Team").c_str()); if (data.team == -1) { throw content_error("missing AI.Team in GameSetup script"); } data.hostPlayer = atoi(file.SGetValueDef("-1", s + "Host").c_str()); if (data.hostPlayer == -1) { throw content_error("missing AI.Host in GameSetup script"); } data.shortName = file.SGetValueDef("", s + "ShortName"); if (data.shortName == "") { throw content_error("missing AI.ShortName in GameSetup script"); } data.version = file.SGetValueDef("", s + "Version"); if (file.SectionExist(s + "Options")) { data.options = file.GetAllValues(s + "Options"); std::map<std::string, std::string>::const_iterator kv; for (kv = data.options.begin(); kv != data.options.end(); ++kv) { data.optionKeys.push_back(kv->first); } } // get the visible name (comparable to player-name) std::string name = file.SGetValueDef(data.shortName, s + "Name"); int instanceIndex = 0; std::string name_unique = name; while (nameList.find(name_unique) != nameList.end()) { name_unique = name + "_" + IntToString(instanceIndex++); // so we possibly end up with something like myBot_0, or RAI_2 } data.name = name_unique; nameList.insert(data.name); skirmishAIStartingData.push_back(data); } unsigned aiCount = 0; if (!file.GetValue(aiCount, "GAME\\NumSkirmishAIs") || skirmishAIStartingData.size() == aiCount) { aiCount = skirmishAIStartingData.size(); } else { throw content_error( "incorrect number of skirmish AIs in GameSetup script"); } }