bool checkConstraints( MeshTopologyPtr mesh, unsigned entityDim, map<unsigned,pair<IndexType,unsigned> > &expectedConstraints, string meshName = "mesh") { bool success = true; // check constraints for entities belonging to active cells set<IndexType> myActiveCells = mesh->getMyActiveCellIndices(); for (IndexType cellIndex : myActiveCells) { CellPtr cell = mesh->getCell(cellIndex); vector<unsigned> entitiesForCell = cell->getEntityIndices(entityDim); for (vector<unsigned>::iterator entityIt = entitiesForCell.begin(); entityIt != entitiesForCell.end(); entityIt++) { unsigned entityIndex = *entityIt; pair<IndexType,unsigned> constrainingEntity = mesh->getConstrainingEntity(entityDim, entityIndex); unsigned constrainingEntityIndex = constrainingEntity.first; unsigned constrainingEntityDim = constrainingEntity.second; if ((constrainingEntityIndex==entityIndex) && (constrainingEntityDim == entityDim)) { // then we should expect not to have an entry in expectedConstraints: if (expectedConstraints.find(entityIndex) != expectedConstraints.end()) { cout << "Expected entity constraint is not imposed in " << meshName << ".\n"; cout << "Expected " << typeString(entityDim) << " " << entityIndex << " to be constrained by "; cout << typeString(expectedConstraints[entityIndex].second) << " " << expectedConstraints[entityIndex].first << endl; cout << typeString(entityDim) << " " << entityIndex << " vertices:\n"; mesh->printEntityVertices(entityDim, entityIndex); cout << typeString(expectedConstraints[entityIndex].second) << " " << expectedConstraints[entityIndex].first << " vertices:\n"; mesh->printEntityVertices(entityDim, expectedConstraints[entityIndex].first); success = false; } } else { if (expectedConstraints.find(entityIndex) == expectedConstraints.end()) { cout << "Unexpected entity constraint is imposed in " << meshName << ".\n"; string entityType; if (entityDim==0) { entityType = "Vertex "; } else if (entityDim==1) { entityType = "Edge "; } else if (entityDim==2) { entityType = "Face "; } else if (entityDim==3) { entityType = "Volume "; } string constrainingEntityType; if (constrainingEntityDim==0) { constrainingEntityType = "Vertex "; } else if (constrainingEntityDim==1) { constrainingEntityType = "Edge "; } else if (constrainingEntityDim==2) { constrainingEntityType = "Face "; } else if (constrainingEntityDim==3) { constrainingEntityType = "Volume "; } cout << entityType << entityIndex << " unexpectedly constrained by " << constrainingEntityType << constrainingEntityIndex << endl; cout << entityType << entityIndex << " vertices:\n"; mesh->printEntityVertices(entityDim, entityIndex); cout << constrainingEntityType << constrainingEntityIndex << " vertices:\n"; mesh->printEntityVertices(constrainingEntityDim, constrainingEntityIndex); success = false; } else { unsigned expectedConstrainingEntity = expectedConstraints[entityIndex].first; if (expectedConstrainingEntity != constrainingEntityIndex) { cout << "The constraining entity is not the expected one in " << meshName << ".\n"; cout << "Expected " << typeString(entityDim) << " " << entityIndex << " to be constrained by "; cout << typeString(expectedConstraints[entityIndex].second) << " " << expectedConstrainingEntity; cout << "; was constrained by " << constrainingEntityIndex << endl; cout << typeString(entityDim) << " " << entityIndex << " vertices:\n"; mesh->printEntityVertices(entityDim, entityIndex); cout << typeString(expectedConstraints[entityIndex].second) << " " << expectedConstrainingEntity << " vertices:\n"; mesh->printEntityVertices(entityDim, expectedConstrainingEntity); cout << typeString(constrainingEntityDim) << " " << constrainingEntityIndex << " vertices:\n"; mesh->printEntityVertices(constrainingEntityDim, constrainingEntityIndex); success = false; } } } } } return success; }
const string &primOpName(PrimOpPtr x) { map<int, string>::iterator i = primOpNames.find(x->primOpCode); assert(i != primOpNames.end()); return i->second; }
void setupNextSubsession(RTSPClient* rtspClient) { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias bool rtpOverTCP = false; if(rtspconf->proto == IPPROTO_TCP) { rtpOverTCP = true; } scs.subsession = scs.iter->next(); do if (scs.subsession != NULL) { if (!scs.subsession->initiate()) { env << *rtspClient << "Failed to initiate the \"" << *scs.subsession << "\" subsession: " << env.getResultMsg() << "\n"; setupNextSubsession(rtspClient); // give up on this subsession; go to the next one } else { if(strcmp("video", scs.subsession->mediumName()) == 0) { video_sess_fmt = scs.subsession->rtpPayloadFormat(); video_codec_name = strdup(scs.subsession->codecName()); if(port2channel.find(scs.subsession->clientPortNum()) == port2channel.end()) { int cid = port2channel.size(); port2channel[scs.subsession->clientPortNum()] = cid; #ifdef ANDROID if(rtspconf->builtin_video_decoder != 0) { video_codec_id = ga_lookup_codec_id(video_codec_name); } else { ////// Work with ffmpeg #endif /*if(init_vdecoder(cid, scs.subsession->fmtp_spropparametersets()) < 0) { rtsperror("cannot initialize video decoder(%d)\n", cid); rtspParam->quitLive555 = 1; return; }*/ rtsperror("video decoder(%d) initialized (client port %d)\n", cid, scs.subsession->clientPortNum()); #ifdef ANDROID //////////////////////// } #endif } } else if(strcmp("audio", scs.subsession->mediumName()) == 0) { const char *mime = NULL; audio_sess_fmt = scs.subsession->rtpPayloadFormat(); audio_codec_name = strdup(scs.subsession->codecName()); #ifdef ANDROID if((mime = ga_lookup_mime(audio_codec_name)) == NULL) { showToast(rtspParam->jnienv, "codec %s not supported", audio_codec_name); rtsperror("rtspclient: unsupported audio codec: %s\n", audio_codec_name); usleep(300000); rtspParam->quitLive555 = 1; return; } audio_codec_id = ga_lookup_codec_id(audio_codec_name); if(android_prepare_audio(rtspParam, mime, rtspconf->builtin_audio_decoder != 0) < 0) return; if(rtspconf->builtin_audio_decoder == 0) { ////////////////////////////////////// rtsperror("init software audio decoder.\n"); #endif if(adecoder == NULL) { if(init_adecoder() < 0) { rtsperror("cannot initialize audio decoder.\n"); rtspParam->quitLive555 = 1; return; } } #ifdef ANDROID ////////////////////////////////////// } #endif rtsperror("audio decoder initialized.\n"); } env << *rtspClient << "Initiated the \"" << *scs.subsession << "\" subsession (client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1 << ")\n"; // Continue setting up this subsession, by sending a RTSP "SETUP" command: rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, rtpOverTCP ? True : False/*TCP?*/, False, NULL); } return; } while(0); // // We've finished setting up all of the subsessions. Now, send a RTSP "PLAY" command to start the streaming: scs.duration = scs.session->playEndTime() - scs.session->playStartTime(); rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY); }
void run(std::istream& in) { vector<string> tokens; string line; int chromCol=0; int posCol=1; int idCol=2; int refCol=3; int altCol=4; int sampleCol=-1; while(getline(in,line,'\n')) { if(AbstractApplication::stopping()) break; if(line.empty() || line[0]=='#') continue; tokenizer.split(line,tokens); string chrom=tokens[chromCol]; chat *p2; int pos=(int)strtol(tokens[posCol].c_str(),&p2,10); string id=tokens[idCol]; string ref=tokens[refCol]; string alt=tokens[altCol]; string sampleName=tokens[sampleCol]; Row* therow=NULL; if(!rows.empty() && rows.back()->pos->chrom.compare(chrom)==0 && rows.back()->pos->pos==pos && rows.back()->ref.compare(ref)==0 && rows.back()->alt.compare(alt)==0 ) { therow=rows.back(); } else { therow=new Row; therow->pos=new ChromPosition(chrom,pos); therow->id.assign(id); therow->ref.assign(ref); therow->alt.assign(alt); rows.push_back(therow); } int index_sample=0; if(sampleCol==-1) { if(sample2col.empty()) { Sample* sample=new Sample; sample->name.assign("Sample"); sample->column_index=0; samples.push_back(sample); } index_sample=0; } else { map<string,Sample*>::iterator r= sample2col.find(sampleName); if(r==sample2col.end()) { Sample* sample=new Sample; sample->name.assign(sampleName); sample->column_index=sample2col.size(); index_sample=sample->column_index; samples.push_back(sample); sample2col.put(sample->name,sample); } else { index_sample=r->second->column_index; } } if(index_sample>=therow->data.size()) { therow->data.resize(index_sample+1); } Data* data=new Data; therow->data.assign(index_sample,data); } }
/** * This calculates the dark current corrections for IR. If * IRDARKAVG is false, then it translates the sideplane data * into the lineBasedDarkCorrections map directly and does nothing further * with the data. Otherwise, this will apply a least squares linear * fit (the original script did chi-squared, but this is okay) for * each band and uses the points on the line instead of the sideplane * data directly. * * @param icube */ void calculateIrDarkCurrent(Cube *icube) { UserInterface &ui = Application::GetUserInterface(); bool found = false; // verify if IR we have sideplane data for(int obj = 0; !found && obj < icube->label()->objects(); obj++) { PvlObject &object = icube->label()->object(obj); if(object.name() != "Table") continue; if(object.hasKeyword("Name") && object["Name"][0] == "SideplaneIr") found = true; } if(!found) { calibInfo += PvlKeyword("SideplaneCorrection", "None"); return; } Table sideplane("SideplaneIr", ui.GetFileName("FROM")); // If spectal summing is on OR compressor_id isnt N/A then // just return. PvlGroup &archive = icube->label()->findGroup("Archive", Pvl::Traverse); // If dark subtracted (compressorid is valid) and cant do linear // correction (spectral editing flag on) then do not do dark if(archive["CompressorId"][0] != "N/A" && archive["SpectralEditingFlag"][0] == "ON") { calibInfo += PvlKeyword("SideplaneCorrection", "None"); return; } // If subtracted (compressor id is valid) and dont do linear then return if(archive["CompressorId"][0] != "N/A" && ui.GetBoolean("IRORIGDARK") == true) { calibInfo += PvlKeyword("SideplaneCorrection", "None"); return; } if(archive["SpectralSummingFlag"][0] == "ON") return; // Insert the sideplane data into our lineBasedDarkCorrections map (line,band to correction) for(int line = 1; line <= icube->lineCount(); line++) { for(int band = 1; band <= icube->bandCount(); band++) { pair<int, int> index = pair<int, int>(line, band); int value = (int)sideplane[(line-1)*icube->bandCount() + (band-1)][2]; if(value != 57344) lineBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, value)); else lineBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, Null)); } } if(ui.GetBoolean("IRORIGDARK") == true) { calibInfo += PvlKeyword("SideplaneCorrection", "Sideplane"); return; } // do linear fits for(int band = 1; band <= icube->bandCount(); band++) { PolynomialUnivariate basis(1); LeastSquares lsq(basis); for(int line = 1; line <= icube->lineCount(); line++) { pair<int, int> index = pair<int, int>(line, band); map< pair<int, int>, double>::iterator val = lineBasedDarkCorrections.find(index); if(val != lineBasedDarkCorrections.end()) { vector<double> input; input.push_back(line); double expected = val->second; if(!IsSpecial(expected)) lsq.AddKnown(input, expected); } } if(lsq.Rows() == 0) return; lsq.Solve(); double coefficients[2] = { basis.Coefficient(0), basis.Coefficient(1) }; for(int line = 1; line <= icube->lineCount(); line++) { pair<int, int> index = pair<int, int>(line, band); map< pair<int, int>, double>::iterator val = lineBasedDarkCorrections.find(index); if(val != lineBasedDarkCorrections.end()) { double currentDark = val->second; if(!IsSpecial(currentDark)) { double newDark = coefficients[0] + line * coefficients[1]; // initial dark applied by compressor if(archive["CompressorId"][0] != "N/A") { // input is in (dn-dark) units // (dn-dark) - (fit-dark) = dn-fit newDark -= currentDark; } val->second = newDark; } } } } if(archive["CompressorId"][0] != "N/A") { calibInfo += PvlKeyword("SideplaneCorrection", "Fit Delta"); } else { calibInfo += PvlKeyword("SideplaneCorrection", "Fit"); } }
void *clientSession(void *arg) { unsigned int *connection = (unsigned int *) arg; int connfd = connection[0]; unsigned int ip = connection[1]; sem_wait(&sem); if (repeatedLogins.find(ip) == repeatedLogins.end()) repeatedLogins.insert(pair<unsigned int, pair<string, int> >(ip, pair<string, int>("", 2))); sem_post(&sem); delete connection; int n = 0; char *message = new char[BUFFER_SIZE]; char *username = new char[BUFFER_SIZE]; char *password = new char[BUFFER_SIZE]; bzero(message, BUFFER_SIZE); bool loggingIn = true; while (loggingIn) { if (send(connfd, "> Username: "******"error: "); pthread_exit(NULL); } bzero(username, BUFFER_SIZE); if ((n = recv(connfd, username, BUFFER_SIZE, 0)) == -1) { perror("error: "); pthread_exit(NULL); } else if (n == 0) { if (close(connfd) == -1) { perror("error: "); pthread_exit(NULL); } delete username; delete message; pthread_exit(NULL); } if (send(connfd, "> Password: "******"error: "); pthread_exit(NULL); } bzero(password, BUFFER_SIZE); if (recv(connfd, password, BUFFER_SIZE, 0) == -1) { perror("error: "); pthread_exit(NULL); } else if (n == 0) { if (close(connfd) == -1) { perror("error: "); pthread_exit(NULL); } delete username; delete password; delete message; pthread_exit(NULL); } sem_wait(&sem); string user(username); string pass(password); if (accounts.find(user) != accounts.end()) { if (accounts[user].isBlocked(ip)) { if (accounts[user].blockExpired(ip, BLOCK_TIME)) { accounts[user].removeBlocked(ip); } else { sem_post(&sem); stringstream blockStream; blockStream << "IP was blocked for " << BLOCK_TIME << " seconds for 3 consecutively failed logins\n"; string blockMessage = blockStream.str(); if (send(connfd, blockMessage.data(), blockMessage.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } bzero(message, BUFFER_SIZE); continue; } } if (accounts[user].getPassword() == pass) { if (accounts[user].getConnection() == -1) { string validLogin("Welcome to simple chat server!\n"); if (send(connfd, validLogin.data(), validLogin.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } if (send(connfd, "> ", 2, 0) == -1) { perror("error: "); pthread_exit(NULL); } loggingIn = false; accounts[user].setConnection(connfd); bzero(message, BUFFER_SIZE); } else { string dupeLogin("User already signed in, try again.\n"); if (send(connfd, dupeLogin.data(), dupeLogin.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } } } else { string invalidPassword("Invalid password, try again.\n"); if (repeatedLogins[ip].first == user) { repeatedLogins[ip].second--; if (repeatedLogins[ip].second <= 0) { accounts[user].addBlocked(ip); repeatedLogins[ip].first = ""; repeatedLogins[ip].second = 2; } } else { repeatedLogins[ip].first = user; repeatedLogins[ip].second = 2; } if (send(connfd, invalidPassword.data(), invalidPassword.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } } } else { string invalidLogin("Invalid username, try again.\n"); if (send(connfd, invalidLogin.data(), invalidLogin.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } } sem_post(&sem); } delete password; string user(username); if (recv(connfd, message, BUFFER_SIZE, 0) == -1) { perror("error: "); pthread_exit(NULL); } socklen_t port = atoi(message); if ((msgfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("error: "); pthread_exit(NULL); } clientAddress.sin_port = port; if (connect(msgfd, (struct sockaddr *) &clientAddress, sizeof(clientAddress)) == -1) { perror("error: "); pthread_exit(NULL); } time(¤tTime); sem_wait(&sem); accounts[user].setMessageConnection(msgfd); accounts[user].setTimeout(currentTime); sem_post(&sem); while ((n = recv(connfd, message, BUFFER_SIZE, 0)) > 0) { string response; stringstream ss; ss << message; string command; ss >> command; if (command == "whoelse") { stringstream st; sem_wait(&sem); for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) { if (it->second.getConnection() != -1 && it->first != user) { st << it->first << endl; } } sem_post(&sem); st << "> "; response = st.str(); } else if (command == "wholasthr") { stringstream st; time_t current; time(¤t); sem_wait(&sem); for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) { if (it->second.getConnection() != -1) it->second.setLast(current); if (difftime(current, it->second.getLast()) < LAST_HOUR && it->first != user) { st << it->first << endl; } } sem_post(&sem); st << "> "; response = st.str(); } else if (command == "broadcast") { string nextMessage = ""; ss >> nextMessage; if (nextMessage == "") { response = "error: broadcast expected a message\n> "; } else { stringstream st; st << user << ": "; st << nextMessage; string endMessage; getline(ss, endMessage); st << endMessage; st << "\n"; string broadcastMessage = st.str(); sem_wait(&sem); for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) { if (it->second.getConnection() != -1 && it->first != user) { if (send(accounts[it->first].getMessageConnection(), broadcastMessage.data(), broadcastMessage.length(), 0) == -1) { perror("error: "); pthread_exit(NULL); } } } response = "> "; sem_post(&sem); } } else if (command == "message") {
void *processRequest (void *socketid) { int n; int *sock = (int*)socketid; int acceptSock = *sock; string videoName; bool clientSignaledToClose = false; while(!clientSignaledToClose){ char SIDReq[1024]; memset(SIDReq, 0, sizeof(SIDReq)); //Receive packet say("Receiving packet...\n"); if ((n = Xrecv(acceptSock, SIDReq, sizeof(SIDReq), 0)) <= 0) { cerr << "Xrecv failed!" << endl; Xclose(acceptSock); delete sock; return NULL; } string SIDReqStr(SIDReq); say("Got request: " + SIDReqStr); // if the request is about number of chunks return number of chunks // since this is first time, you would return along with header // If Request contains "numchunks", return number of CID's. if(isNumChunksRequest(SIDReqStr)){ // Get Video Name out of the request string prefix = "get numchunks "; videoName = SIDReqStr.substr(prefix.length()); say("Request asks for number of chunks: " + videoName); //Figure out what video they would like // Check to see if this video is the one that the user is looking for if(CIDlist.find(videoName) != CIDlist.end()){ // Add the number of chunks to the string stringstream yy; yy << CIDlist[videoName]->size(); string response = yy.str(); // Add a character of whitespace to the response response += " "; // Append on the list of Server AD-HIDs to the response for(vector<string>::iterator it = ContentServerXidList[videoName]->begin(); it != ContentServerXidList["BigBuckBunny"]->end(); ++it){ response += *it + " "; } // Send back the number of CIDs followed by list of AD-HIDs say("Sending back " + response, LVL_DEBUG); Xsend(acceptSock,(void *) response.c_str(), response.length(), 0); } else{ cerr << "Invalid Video Name: " << videoName << endl; Xclose(acceptSock); delete sock; return NULL; } } else if(isTerminationRequest(SIDReqStr)){ clientSignaledToClose = true; } else if(isVideoSelectionRequest(SIDReqStr)){ ostringstream oss; for(vector<string>::iterator it = videoList.begin(); it != videoList.end(); ++it){ oss << *it << " "; } Xsend(acceptSock,(void *) oss.str().c_str(), oss.str().length(), 0); } else { // Otherwise, if the request was not about the number of chunks, // it must be a request for a certain chunk // Format of the request: start-offset:end-offset // Each offset position corresponds to a CID (chunk) say("Request is for a certain chunk span"); // Parse the Request, extract start and end offsets int findpos = SIDReqStr.find(":"); // split around this position string prefix = "block "; string str = SIDReqStr.substr(prefix.length(), findpos); int start_offset = atoi(str.c_str()); str = SIDReqStr.substr(findpos + 1); int end_offset = atoi(str.c_str()); // construct the string from CIDlist // return the list of CIDs, NOT including end_offset string requestedCIDlist = ""; for(int i = start_offset; i < end_offset; i++){ requestedCIDlist += CIDlist[videoName]->at(i) + " "; } Xsend(acceptSock, (void *)requestedCIDlist.c_str(), requestedCIDlist.length(), 0); say("sending requested CID list: ", LVL_DEBUG); } } Xclose(acceptSock); delete sock; return NULL; }
BOOL CMsgSite::GetMsg(u32& identify, CShareLock& modlock, map<DWORD, CModuleInfo*>& modmap, CMemItem *pMsgBuf, CTCPSocket *psokt, void *userData, MSG_CXT* pMsgCxt) { PBYTE pBegin = NULL; PBYTE pEnd = NULL; DWORD dwAddSize = 0; BOOL bRet = TRUE; CModuleInfo *mod = NULL; DWORD dwSheetHeadSize = sizeof(Tsheet); ASSERT(pMsgCxt->pMsgHead && pMsgCxt->pUserData); pBegin = pMsgBuf->GetBufferPtr(); pEnd = pBegin + pMsgBuf->GetDataRealSize(); while (pBegin < pEnd || pMsgCxt->dwMsgSect == MSG_END) { switch (pMsgCxt->dwMsgSect) { case MSG_HEAD: if (pMsgCxt->pMsgHead->GetDataRealSize() < 3 * sizeof(DWORD)) { dwAddSize = (pEnd - pBegin + pMsgCxt->pMsgHead->GetDataRealSize()) <= 3 * sizeof(DWORD) ? pEnd - pBegin : 3 * sizeof(DWORD) - pMsgCxt->pMsgHead->GetDataRealSize(); pMsgCxt->pMsgHead->AddData(pBegin, dwAddSize); pBegin += dwAddSize; if (pMsgCxt->pMsgHead->GetDataRealSize() != 3 * sizeof(DWORD)) { continue; } } if (pMsgCxt->dwMsgSize == 0) { DWORD dwMsgHead = *(DWORD *)(pMsgCxt->pMsgHead->GetBufferPtr()); /// fixme : header flag error, should return error and close msg ASSERT(dwMsgHead == SHEET_HEAD); if (dwMsgHead != SHEET_HEAD) { bRet = FALSE; goto _aleave; } pMsgCxt->dwMsgSize = *(DWORD *)(pMsgCxt->pMsgHead->GetBufferPtr() + sizeof(DWORD)); pMsgCxt->dwSheetSize = *(DWORD *)(pMsgCxt->pMsgHead->GetBufferPtr() + sizeof(DWORD) + sizeof(DWORD)); /// set pMsgCxt->pMsgHead buffer size in range ,will greatly reduce copy times ASSERT(pMsgCxt->dwMsgSize < SHEET_MAX_SIZE); } /// construct sheet head if (pMsgCxt->pMsgHead->GetDataRealSize() < pMsgCxt->dwSheetSize) { dwAddSize = (pEnd - pBegin + pMsgCxt->pMsgHead->GetDataRealSize()) <= pMsgCxt->dwSheetSize ? pEnd - pBegin : pMsgCxt->dwSheetSize - pMsgCxt->pMsgHead->GetDataRealSize(); pMsgCxt->pMsgHead->AddData(pBegin, dwAddSize); pBegin += dwAddSize; if (pMsgCxt->pMsgHead->GetDataRealSize() != pMsgCxt->dwSheetSize) { continue; } } if (pMsgCxt->sh == NULL) { pMsgCxt->sh = (Tsheet *)pMsgCxt->pMsgHead->GetBufferPtr(); } ASSERT(pMsgCxt->dwSheetSize == (sizeof(Tsheet) + pMsgCxt->sh->src_ip_num * sizeof(DWORD) + pMsgCxt->sh->dst_ip_num * sizeof(DWORD))); ASSERT(pMsgCxt->pMsgHead->GetDataRealSize() == pMsgCxt->dwSheetSize); /// set user pre pUserData recv buffer size if (pMsgCxt->sh->tunnel == SHEET_ENABLE_TUNNEL) { ASSERT(pMsgCxt->sh->direction == SHEET_REPLY); pMsgCxt->dwUserDataSize = pMsgCxt->dwMsgSize - pMsgCxt->sh->tunnelsize - pMsgCxt->dwSheetSize; } else { pMsgCxt->dwUserDataSize = pMsgCxt->dwMsgSize - pMsgCxt->dwSheetSize; } pMsgCxt->pUserData->SetBufferSize(pMsgCxt->dwUserDataSize); pMsgCxt->dwMsgSect = (pMsgCxt->dwMsgSize == pMsgCxt->pMsgHead->GetDataRealSize()) ? MSG_END : MSG_USER_BODY; break; case MSG_USER_BODY: /// construct sheet carry user buffer head if (pMsgCxt->pUserData->GetDataRealSize() < pMsgCxt->dwUserDataSize) { dwAddSize = (pEnd - pBegin + pMsgCxt->pUserData->GetDataRealSize()) <= pMsgCxt->dwUserDataSize ? pEnd - pBegin : pMsgCxt->dwUserDataSize - pMsgCxt->pUserData->GetDataRealSize(); pMsgCxt->pUserData->AddData(pBegin, dwAddSize); pBegin += dwAddSize; if (pMsgCxt->pUserData->GetDataRealSize() != pMsgCxt->dwUserDataSize) { continue; } } /// throw other msg //if (identify != pMsgCxt->sh->identity) //{ // pMsgCxt->bTunnelUnused = TRUE; //} pMsgCxt->dwMsgSect = (pMsgCxt->dwMsgSize == (pMsgCxt->dwSheetSize + pMsgCxt->dwUserDataSize)) ? MSG_END : MSG_TUNNEL_BODY; break; case MSG_TUNNEL_BODY: /// check if use tunnel buffer, then recv buf to tunnel buff if (pMsgCxt->sh->direction == SHEET_REPLY && pMsgCxt->sh->tunnel && pMsgCxt->sh->tunnelsize) { /// get mod if (NULL == pMsgCxt->mod) { map<DWORD, CModuleInfo *>::iterator it; modlock.ShareLock(); if (modmap.end() != (it = modmap.find(pMsgCxt->sh->reg_module_type))) { pMsgCxt->mod = it->second; } modlock.LeaveLock(); ASSERT(pMsgCxt->mod); if (((CModuleInfo *)pMsgCxt->mod)->ThrowReplyPkt(pMsgCxt->sh->sheet_num)) { pMsgCxt->bTunnelUnused = TRUE; } else { ReqCxt *cxt = ((CModuleInfo *)pMsgCxt->mod)->GetReqParam(pMsgCxt->sh->sheet_num); ASSERT(cxt); ASSERT(cxt->tunnelbuflen >= pMsgCxt->sh->tunnelsize); cxt->tunnelbuflen = pMsgCxt->sh->tunnelsize; pMsgCxt->pTunnelBuf->AttachBufferEx((byte *)cxt->tunnelbuf, pMsgCxt->sh->tunnelsize); } } /// construct sheet carry user tunnel buffer if (pMsgCxt->pTunnelBuf->GetDataRealSize() < pMsgCxt->sh->tunnelsize) { dwAddSize = (pEnd - pBegin + pMsgCxt->pTunnelBuf->GetDataRealSize()) <= pMsgCxt->sh->tunnelsize ? pEnd - pBegin : pMsgCxt->sh->tunnelsize - pMsgCxt->pMsgHead->GetDataRealSize(); if (pMsgCxt->bTunnelUnused) { /// just throw pMsgCxt->pTunnelBuf->AddDataVirtual(pBegin, dwAddSize); } else { pMsgCxt->pTunnelBuf->AddData(pBegin, dwAddSize); } pBegin += dwAddSize; if (pMsgCxt->pTunnelBuf->GetDataRealSize() != pMsgCxt->sh->tunnelsize) { continue; } } pMsgCxt->dwMsgSect = MSG_END; } else { ASSERT(0); } break; case MSG_END: if (pMsgCxt->bTunnelUnused) { _SafeDeletePtr(pMsgCxt->pMsgHead); } else { ASSERT(pMsgCxt->dwMsgSize == pMsgCxt->sh->total_size); if (pMsgCxt->sh->direction == SHEET_REPLY && pMsgCxt->sh->tunnel && pMsgCxt->sh->tunnelsize) { ASSERT(pMsgCxt->pTunnelBuf->GetDataRealSize() == pMsgCxt->sh->tunnelsize); ASSERT(*(u32 *)(pMsgCxt->pTunnelBuf->GetBufferPtr() + pMsgCxt->sh->tunnelsize - sizeof(u32)) == SHEET_END); if (*(u32 *)(pMsgCxt->pTunnelBuf->GetBufferPtr() + pMsgCxt->sh->tunnelsize - sizeof(u32)) != SHEET_END) { _SafeDeletePtr(pMsgCxt->pMsgHead); bRet = FALSE; goto _aleave; } /// restore check data pMsgCxt->sh->RestoreSheet((char *)pMsgCxt->pTunnelBuf->GetBufferPtr(), pMsgCxt->sh->tunnelsize); pMsgCxt->pTunnelBuf->DetachBuffer(); ((CModuleInfo *)pMsgCxt->mod)->SetTunnelBufferStatus(pMsgCxt->sh->sheet_num, FALSE); } else { ASSERT(*(u32 *)(pMsgCxt->pUserData->GetBufferPtr() + pMsgCxt->dwUserDataSize - sizeof(u32)) == SHEET_END); /*if (*(u32 *)(pMsgCxt->pTunnelBuf->GetBufferPtr() + pMsgCxt->sh->tunnelsize - sizeof(u32)) != SHEET_END) { _SafeDeletePtr(pMsgCxt->pMsgHead); bRet = FALSE; goto _aleave; }*/ /// restore check data pMsgCxt->sh->RestoreSheet((char *)pMsgCxt->pUserData->GetBufferPtr(), pMsgCxt->dwUserDataSize); } pMsgCxt->sh->trace_back = (u64)psokt->GetSocketHandle(); /// user call back must take away msg quickly /// callback masg m_callback(pMsgCxt->pMsgHead, pMsgCxt->pUserData, psokt, userData); } pMsgCxt->Reset(); break; default: ASSERT(0); } } _aleave: return bRet; }
void NiRoom::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const { //--BEGIN PRE-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// NiNode::Write( out, link_map, missing_link_stack, info ); numItems = (int)(items.size()); numPortals2 = (int)(portals2.size()); numInPortals = (int)(inPortals.size()); numWalls = (int)(wallPlane.size()); NifStream( numWalls, out, info ); for (unsigned int i1 = 0; i1 < wallPlane.size(); i1++) { NifStream( wallPlane[i1], out, info ); }; NifStream( numInPortals, out, info ); for (unsigned int i1 = 0; i1 < inPortals.size(); i1++) { if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*inPortals[i1]), out ); } else { if ( inPortals[i1] != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(inPortals[i1]) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( inPortals[i1] ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } }; NifStream( numPortals2, out, info ); for (unsigned int i1 = 0; i1 < portals2.size(); i1++) { if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*portals2[i1]), out ); } else { if ( portals2[i1] != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(portals2[i1]) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( portals2[i1] ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } }; NifStream( numItems, out, info ); for (unsigned int i1 = 0; i1 < items.size(); i1++) { if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*items[i1]), out ); } else { if ( items[i1] != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(items[i1]) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( items[i1] ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } }; //--BEGIN POST-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// }
//template<class ObjectT, ObjectT nullObjectValue> void find_distances_to_maximizing_objects(const bpp::Tree &tree, const vector<int> &breadth_first_visit_order, const map<ObjectT, map<ObjectT, set<int> *> *> &alternative_nearest_objects, const map<ObjectT, int> &leaf_of_object, map<int, map<ObjectT, double> *> &distances_to_maximizing_objects) { set<ObjectT> maximizing_objects; map<ObjectT, map<ObjectT, set<int> *> *>::const_iterator obj_objs_nodes_iter; map<ObjectT, set<int> *>::const_iterator obj_nodes_iter; ObjectT obj0, obj1; for (obj_objs_nodes_iter = alternative_nearest_objects.begin(); obj_objs_nodes_iter != alternative_nearest_objects.end(); ++obj_objs_nodes_iter) { obj0 = obj_objs_nodes_iter->first; maximizing_objects.insert(obj0); for (obj_nodes_iter = obj_objs_nodes_iter->second->begin(); obj_nodes_iter != obj_objs_nodes_iter->second->end(); ++obj_nodes_iter) { obj1 = obj_nodes_iter->first; maximizing_objects.insert(obj1); } } set<ObjectT>::const_iterator max_obj_iter; int nodeId; for (max_obj_iter = maximizing_objects.begin(); max_obj_iter != maximizing_objects.end(); ++max_obj_iter) { nodeId = leaf_of_object.find(*max_obj_iter)->second; distances_to_maximizing_objects[nodeId] = new map<ObjectT, double>; (*distances_to_maximizing_objects[nodeId])[*max_obj_iter] = 0.0; } map<int, map<ObjectT, double> *>::iterator node_obj_dist_iter, parent_node_obj_dist_iter; map<ObjectT, double>::iterator obj_dist_iter, parent_obj_dist_iter; double parent_distance_to_object_through_node, parent_distance_to_object, node_distance_to_object; int parentId; ObjectT obj; for (int i = breadth_first_visit_order.size() - 1; i >= 1; --i) { nodeId = breadth_first_visit_order[i]; parentId = tree.getFatherId(nodeId); node_obj_dist_iter = distances_to_maximizing_objects.find(nodeId); if (node_obj_dist_iter == distances_to_maximizing_objects.end()) { continue; } parent_node_obj_dist_iter = distances_to_maximizing_objects.find(parentId); if (parent_node_obj_dist_iter == distances_to_maximizing_objects.end()) { distances_to_maximizing_objects[parentId] = new map<ObjectT, double>; } for (obj_dist_iter = distances_to_maximizing_objects[nodeId]->begin(); obj_dist_iter != distances_to_maximizing_objects[nodeId]->end(); ++obj_dist_iter) { obj = obj_dist_iter->first; node_distance_to_object = obj_dist_iter->second; parent_distance_to_object_through_node = node_distance_to_object + tree.getDistanceToFather(nodeId); parent_obj_dist_iter = distances_to_maximizing_objects[parentId]->find(obj); if (parent_obj_dist_iter == distances_to_maximizing_objects[parentId]->end()) { (*distances_to_maximizing_objects[parentId])[obj] = parent_distance_to_object_through_node; } else { parent_distance_to_object = (*distances_to_maximizing_objects[parentId])[obj]; if (parent_distance_to_object_through_node < parent_distance_to_object) { (*distances_to_maximizing_objects[parentId])[obj] = parent_distance_to_object_through_node; } } } } }
int main(){ cntp=sieve(); two63 = (1ll<<63); recur(0, 63, 1); // copy(s.begin(), s.end(), ostream_iterator<ll>(cout, "\n")); printf("%d\n", s.size()); vector<int> es; for(set<ll>::iterator it=s.begin(); it!=s.end(); it++){ es.clear(); ll cur = *it; ll oldcur=cur; int sum=0; for(int i=0; i<cntp && cur>1 ; i++){ int cnt=0; while(cur%primes[i]==0) cur/=primes[i], cnt++; if(cnt>0) es.push_back(cnt); sum+=cnt; } memset(cntprimes, 0, sizeof cntprimes); while(sum){ int cur=sum; for(int j=0; j<cntp && cur>1 ; j++){ int cnt=0; while(cur%primes[j]==0) cur/=primes[j], cnt++; cntprimes[j]+=cnt; } sum--; } for(int i=0; i<es.size(); i++){ while(es[i]){ int cur=es[i]; for(int j=0; j<cntp && cur>1 ; j++){ int cnt=0; while(cur%primes[j]==0) cur/=primes[j], cnt++; cntprimes[j]-=cnt; } es[i]--; } } ll val=1; bool valid=true; for(int i=0; i<cntp && valid; i++){ while(cntprimes[i]--){ val*=primes[i]; if(val>=two63) {valid=false; break;} } } if(valid){ if(m.find(val)==m.end()) m[val]=oldcur; else m[val]=min(oldcur, m[val]); } } // freopen("factors.out", "w", stdout); //printf("%d\n", m.size()); //for(map<ll, ll>::iterator it = m.begin(); it!=m.end(); it++) printf("%lld %lld\n", it->first, it->second); ll n; while(scanf("%lld", &n)>0){ if(n==1) { printf("1 2\n"); continue; } printf("%llu %llu\n", n, m[n]); } return 0; }
void find_duplication_distances(const bpp::Tree &tree, const vector<int> &breadth_first_visit_order, const map<int, AttributeT> attribute_of_node, const map<int, map<AttributeT, TreeDistanceInfo<ObjectT, nullObjectValue> *> *> distance_from_object_with_attribute_to_node, const LeftRightIdsOfNodeIdMap &idMap, const map<int, int> &nodeIdOfLeftIdMap, const map<ObjectT, int> &leaf_of_object, const map<int, ObjectT> &object_of_leaf, const map<ObjectT, map<ObjectT, set<int> *> *> &alternative_nearest_objects, map<ObjectT, map<ObjectT, DupInfo *> *> &duplication_node_of_objects, map<int, ObjObjInfo *> &pair_of_objects_yielding_duplication_node_distance, map<int, ObjObjInfo *> &pair_of_nearest_objects_to_maximal_node, map<int, double> &greatest_distance_of_maximal_descendant) { if (alternative_nearest_objects.size() == 0) { // There is nothing to do here but set the root int rootId = tree.getRootId(); greatest_distance_of_maximal_descendant[rootId] = -1; return; } // A maximal node is one for which, for some attribute, it is not the case // that the node, its parent, and all its siblings have the same nearest // object in the tree with that attribute. There must be at least two // distinct objects with the same attribute such that they are the nearest // object with that attribute to some of the node, its parent, and its // siblings. All such pairs of objects, and the maximal nodes to which they // pertain, have previously been recorded in alternative_nearest_objects. // For each pair of objects in alternative_nearest_objects, we will find // the most recent common ancestor (MRCA) of that pair of objects. That is // the duplication node for the pair of objects. We also will find the tree // distance between the two objects. If the tree obeyed a molecular clock, // then half this tree distance would tell us how long ago the duplication // happened, and each of the two objects would be exactly this distance from // the duplication node. Because the tree does not obey a molecular clock, // for any particular duplication node, the distances we get this way from // different pairs of duplicated objects that descend from it may be // different. For each duplication node, we will record the maximum of all // such distances for any pair of duplicated objects descending from that // node, and which pair of objects yielded this maximum. Call this maximum // duplication_node_distance. // For each maximal node, it is maximal due to several possible pairs of // alternative nearest objects. It may not always be the case that for each // pair of alternative nearest objects causing a particular node to be // maximal, one or both members of the pair will be descendants of the maximal // node. The duplication node between them also may not be a descendant of // the maximal node. The duplication distance of a maximal node will be the // maximum duplication_node_distance for all duplication nodes of pairs of // alternative nearest objects to the maximal node. We will find the // duplication distance for each maximal node, and record which pair of // objects has the duplication_node_distance yielding that duplication // distance. Note that this pair of objects may not be the same as the one // yielding the duplication_node_distance of the duplication node. // We find the distances from each of the objects that cause nodes to be // maximal to each of their ancestors. map<int, map<ObjectT, double> *> distances_to_maximizing_objects; find_distances_to_maximizing_objects(tree, breadth_first_visit_order, alternative_nearest_objects, leaf_of_object, distances_to_maximizing_objects); // The left_ids and right_ids of the nodes in this tree have previously been // computed and passed in idMap (which has idMap[nodeId] == pair<left_id, // right_id>). These numbers, which were computed by a modified preorder tree // traversal, have the useful properties that: // node N1 descends from ndoe N2 if and only if (iff): // left_id(N1) >= left_id(N2) and right_id(N1) <= right_id(N2) // node N is an ancestor of nodes N1, ..., Nk iff: // left_id(Ni) >= left_id(N) for all i = 1,...,k and // right_id(Ni) <= right_id(N) for all i = 1,...,k // node N is the most recent common ancestor of nodes N1, ..., Nk iff // node N is an ancestor of nodes N1, ..., Nk and // any of the following equivalent conditions holds: // (i) node N has the greatest left_id among ancestors of nodes N1,...,Nk // (ii) node N has the least right_id among ancestors of nodes N1,...,Nk // (iii) node N appears last in the breadth_first_search_order among // ancestors of nodes N1,...,Nk // We'll be using (iii). // We'll be looking up nodes by either their left_id or their right_id. The // nodeIdOfLeftIdMap was passed in, but we now create a nodeIdOfRighgtIdMap as // well, using the idMap (which has idMap[nodeId] == pair<left_id, right_id>). map<int, int> nodeIdOfRightIdMap; map<int, pair<int, int> >::const_iterator node_id_iter; for (node_id_iter = idMap.begin(); node_id_iter != idMap.end(); ++node_id_iter) { nodeIdOfRightIdMap[node_id_iter->second.second] = node_id_iter->first; } // We will be finding the tree distances between pairs of // alternative_nearest_objects. To make it easy to test the condition that // N is an ancestor of N1 and N2, i.e., that // left_id(N1) >= left_id(N) and left_id(N2) >= left_id(N) and // right_id(N1) <= right_id(N) and right_id(N2) <= right_id(N), // we will keep track of each pair of leaves N1 and N2 as // left_id = min(left_id(N1), left_id(N2)) and // right_id = max(right_id(N1), right_id(N2)). map<int, vector<int> *> other_leaf_right_ids_of_leaf_left_ids; map<int, vector<int> *>::const_iterator right_left_iter; int leftId0, leftId1, rightId0, rightId1, leftId, rightId; map<ObjectT, set<int> *>::const_iterator obj_nodes_iter; map<ObjectT, map<ObjectT, set<int> *> *>::const_iterator obj_objs_nodes_iter; int obj0, obj1, lesserObj, greaterObj; map<ObjectT, int>::const_iterator obj_leaf_iter; map<int, pair<int,int> >::const_iterator node_left_right_iter; map<ObjectT, map<ObjectT, DupInfo *> *>::iterator obj_obj_dup_iter; for (obj_objs_nodes_iter = alternative_nearest_objects.begin(); obj_objs_nodes_iter != alternative_nearest_objects.end(); ++obj_objs_nodes_iter) { obj0 = obj_objs_nodes_iter->first; obj_leaf_iter = leaf_of_object.find(obj0); node_left_right_iter = idMap.find(obj_leaf_iter->second); leftId0 = node_left_right_iter->second.first; rightId0 = node_left_right_iter->second.second; for (obj_nodes_iter = obj_objs_nodes_iter->second->begin(); obj_nodes_iter != obj_objs_nodes_iter->second->end(); ++obj_nodes_iter) { obj1 = obj_nodes_iter->first; lesserObj = (obj0 < obj1) ? obj0 : obj1; greaterObj = (obj0 < obj1) ? obj1 : obj0; obj_obj_dup_iter = duplication_node_of_objects.find(lesserObj); if (obj_obj_dup_iter == duplication_node_of_objects.end()) { duplication_node_of_objects[lesserObj] = new map<ObjectT, DupInfo *>; } obj_leaf_iter = leaf_of_object.find(obj1); node_left_right_iter = idMap.find(obj_leaf_iter->second); leftId1 = node_left_right_iter->second.first; rightId1 = node_left_right_iter->second.second; leftId = (leftId0 < leftId1) ? leftId0 : leftId1; rightId = (rightId0 > rightId1) ? rightId0 : rightId1; right_left_iter = other_leaf_right_ids_of_leaf_left_ids.find(leftId); if (right_left_iter == other_leaf_right_ids_of_leaf_left_ids.end()) { other_leaf_right_ids_of_leaf_left_ids[leftId] = new vector<int>; } other_leaf_right_ids_of_leaf_left_ids[leftId]->push_back(rightId); } } // We sort the left_ids and right_ids. This way when we are checking whether // a node is an ancestor of some pair, it will be easy for us to only check // those pairs of which it could possibly be an ancestor. vector<int> sorted_left_ids_of_leaves; for (right_left_iter = other_leaf_right_ids_of_leaf_left_ids.begin(); right_left_iter != other_leaf_right_ids_of_leaf_left_ids.end(); ++right_left_iter) { sorted_left_ids_of_leaves.push_back(right_left_iter->first); std::sort(right_left_iter->second->begin(), right_left_iter->second->end()); std::reverse(right_left_iter->second->begin(), right_left_iter->second->end()); } std::sort(sorted_left_ids_of_leaves.begin(), sorted_left_ids_of_leaves.end()); int least_left_id_greater_than_node_left_id, greatest_right_id_less_than_node_right_id; vector<int>::iterator j, k; int r; AttributeT attr; int nodeId, childId; double distanceToLesserObj, distanceToGreaterObj, duplication_node_distance, new_duplication_node_distance; map<int, ObjObjInfo *>::iterator node_obj_pair_iter; map<int, int>::const_iterator int_node_iter; map<int, AttributeT>::const_iterator node_attr_iter; map<int, ObjectT>::const_iterator leaf_obj_iter; map<ObjectT, int>::const_iterator ancestral_iter; map<int, map<AttributeT, TreeDistanceInfo<ObjectT, nullObjectValue> *> *>::const_iterator dist_attr_node_iter; // Now we go up the tree computing the distances between each pair of // alternative nearest objects, and all the duplication_node_distances. for (int i = breadth_first_visit_order.size() - 1; i >= 0; --i) { nodeId = breadth_first_visit_order[i]; const vector<int> &children = tree.getSonsId(nodeId); duplication_node_distance = -1.0; for (int c = 0; c < children.size(); ++c) { childId = children[c]; node_obj_pair_iter = pair_of_objects_yielding_duplication_node_distance.find(childId); if (node_obj_pair_iter != pair_of_objects_yielding_duplication_node_distance.end()) { new_duplication_node_distance = getDuplicationNodeDistance(childId, duplication_node_of_objects, pair_of_objects_yielding_duplication_node_distance); if (duplication_node_distance < 0.0) { pair_of_objects_yielding_duplication_node_distance[nodeId] = new ObjObjInfo(); pair_of_objects_yielding_duplication_node_distance[ nodeId]->setValues( pair_of_objects_yielding_duplication_node_distance[ childId]->getLesserObj(), pair_of_objects_yielding_duplication_node_distance[ childId]->getGreaterObj()); duplication_node_distance = new_duplication_node_distance; } else { if (new_duplication_node_distance > duplication_node_distance) { pair_of_objects_yielding_duplication_node_distance[ nodeId]->setValues( pair_of_objects_yielding_duplication_node_distance[ childId]->getLesserObj(), pair_of_objects_yielding_duplication_node_distance[ childId]->getGreaterObj()); duplication_node_distance = new_duplication_node_distance; } } } } node_left_right_iter = idMap.find(nodeId); leftId = node_left_right_iter->second.first; rightId = node_left_right_iter->second.second; // If the binary_search returns -1, this means leftId is before the // beginning of sorted_left_ids_of_leaves. So it will be correct that j = // sorted_left_ids_of_leaves.begin() j = sorted_left_ids_of_leaves.begin() + 1 + binary_search(leftId, sorted_left_ids_of_leaves); least_left_id_greater_than_node_left_id = *j; // least_left_id_greater_than_node_left_id will be increasing as we go // through this loop; we stop when it goes past rightId. while (j != sorted_left_ids_of_leaves.end() && least_left_id_greater_than_node_left_id < rightId) { int_node_iter = nodeIdOfLeftIdMap.find(least_left_id_greater_than_node_left_id); node_attr_iter = attribute_of_node.find(int_node_iter->second); leaf_obj_iter = object_of_leaf.find(int_node_iter->second); obj0 = leaf_obj_iter->second; // If the binary_search returns -1, this means rightId is after the end of // the right_ids that are paired with // least_left_id_greater_than_node_left_id (since they are sorted in // reverse order). So it will be correct that k = // other_leaf_right_ids_of_leaf_left_ids[least_left_id_greater_than_node_left_id]->begin(). // beginning of the right_ids that are paired with // least_left_id_greater_than_node_left_id. Hence none of them can be // descendant from this node, and we should continue. k = other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]->begin() + 1 + reverse_binary_search(rightId, *(other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id])); greatest_right_id_less_than_node_right_id = *k; // greatest_right_id_less_than_node_right_id will be decreasing as we go // through this loop; we stop when it goes past leftId. while (k != other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]->end() && greatest_right_id_less_than_node_right_id > leftId) { int_node_iter = nodeIdOfRightIdMap.find( greatest_right_id_less_than_node_right_id); leaf_obj_iter = object_of_leaf.find(int_node_iter->second); obj1 = leaf_obj_iter->second; // This node is the duplication node of obj0, obj1 lesserObj = (obj0 < obj1) ? obj0 : obj1; greaterObj = (obj0 < obj1) ? obj1 : obj0; distanceToLesserObj = (*distances_to_maximizing_objects[nodeId])[lesserObj]; distanceToGreaterObj = (*distances_to_maximizing_objects[nodeId])[greaterObj]; (*duplication_node_of_objects[lesserObj])[greaterObj] = new DupInfo(nodeId, distanceToLesserObj, distanceToGreaterObj); new_duplication_node_distance = (distanceToLesserObj + distanceToGreaterObj) / 2; if (duplication_node_distance < 0.0) { pair_of_objects_yielding_duplication_node_distance[nodeId] = new ObjObjInfo(); pair_of_objects_yielding_duplication_node_distance[ nodeId]->setValues(lesserObj, greaterObj); duplication_node_distance = new_duplication_node_distance; } else { if (new_duplication_node_distance > duplication_node_distance) { pair_of_objects_yielding_duplication_node_distance[ nodeId]->setValues(lesserObj, greaterObj); duplication_node_distance = new_duplication_node_distance; } } // Since we've found the MRCA of obj0, obj1, we don't need to check // for this pair any more. In fact, we had better not, otherwise we // would erroneously keep setting the duplication node to other // ancestors closer to the root of the tree. So we must erase // right_id here. k = other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]->erase(k); if (k != other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]->end()) { // Now k points to the item that originally came *after* // greatest_right_id_less_than_node_right_id in the vector, which // means that it is *less* than // greatest_right_id_less_than_node_right_id (since the vector is in // reverse order), and hence still less than rightId. greatest_right_id_less_than_node_right_id = *k; } } if (other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]->size() == 0) { // Since we've found the duplication nodes of all pairs with obj0, we // don't need to check it any more. So we can erase the left_id. delete other_leaf_right_ids_of_leaf_left_ids[ least_left_id_greater_than_node_left_id]; other_leaf_right_ids_of_leaf_left_ids.erase( least_left_id_greater_than_node_left_id); j = sorted_left_ids_of_leaves.erase(j); } else { ++j; } // Now j points to the item that originall came after // least_left_id_greater_than_node_left_id in sorted_left_ids_of_leaves, // which means that it greater than // least_left_id_greater_than_node_left_id, and hence also than leftId. if (j != sorted_left_ids_of_leaves.end()) { least_left_id_greater_than_node_left_id = *j; } } } if (other_leaf_right_ids_of_leaf_left_ids.size() > 0) { cerr << "Warning: other_leaf_right_ids_of_leaf_left_ids ended nonempty" << endl; } // Now we go through alternative_nearest_objects computing the duplication // distances of the maximal nodes. set<int>::iterator maximal_node_iter; int duplicationNodeId; map<int, ObjObjInfo *>::iterator obj_obj_max_node_iter; for (obj_objs_nodes_iter = alternative_nearest_objects.begin(); obj_objs_nodes_iter != alternative_nearest_objects.end(); ++obj_objs_nodes_iter) { obj0 = obj_objs_nodes_iter->first; for (obj_nodes_iter = obj_objs_nodes_iter->second->begin(); obj_nodes_iter != obj_objs_nodes_iter->second->end(); ++obj_nodes_iter) { obj1 = obj_nodes_iter->first; lesserObj = (obj0 < obj1) ? obj0 : obj1; greaterObj = (obj0 < obj1) ? obj1 : obj0; duplicationNodeId = (*duplication_node_of_objects[lesserObj]) [greaterObj]->getDuplicationNodeId(); for (maximal_node_iter = obj_nodes_iter->second->begin(); maximal_node_iter != obj_nodes_iter->second->end(); ++maximal_node_iter) { obj_obj_max_node_iter = pair_of_nearest_objects_to_maximal_node.find( *maximal_node_iter); if (obj_obj_max_node_iter == pair_of_nearest_objects_to_maximal_node.end()) { pair_of_nearest_objects_to_maximal_node[*maximal_node_iter] = new ObjObjInfo(); pair_of_nearest_objects_to_maximal_node[ *maximal_node_iter]->setValues(lesserObj, greaterObj); } else { if (getDuplicationNodeDistance(duplicationNodeId, duplication_node_of_objects, pair_of_objects_yielding_duplication_node_distance) > getMaximalNodeDistance(*maximal_node_iter, duplication_node_of_objects, pair_of_objects_yielding_duplication_node_distance, pair_of_nearest_objects_to_maximal_node)) { pair_of_nearest_objects_to_maximal_node[ *maximal_node_iter]->setValues(lesserObj, greaterObj); } } } } } // Now we go up the tree finding, for each maximal node, the greatest // duplication distance of any of its strict descendants (i.e., not including // itself) which is also a maximal node. We store the pair of the maximal // node's own duplication distance and this for each of the maximal nodes, and // for the root. map<int, double> all_node_greatest_distance_of_maximal_descendant; map<int, double>::const_iterator node_iter, parent_iter; int parentId; double currentDistance; for (int i = breadth_first_visit_order.size() - 1; i >= 1; --i) { nodeId = breadth_first_visit_order[i]; node_iter = all_node_greatest_distance_of_maximal_descendant.find(nodeId); parentId = tree.getFatherId(nodeId); parent_iter = all_node_greatest_distance_of_maximal_descendant.find(parentId); if (node_iter != all_node_greatest_distance_of_maximal_descendant.end()) { if (parent_iter == all_node_greatest_distance_of_maximal_descendant.end()) { all_node_greatest_distance_of_maximal_descendant[parentId] = node_iter->second; } else { if (node_iter->second > parent_iter->second) { all_node_greatest_distance_of_maximal_descendant[parentId] = node_iter->second; } } } obj_obj_max_node_iter = pair_of_nearest_objects_to_maximal_node.find(nodeId); if (obj_obj_max_node_iter != pair_of_nearest_objects_to_maximal_node.end()) { if (node_iter == all_node_greatest_distance_of_maximal_descendant.end()) { greatest_distance_of_maximal_descendant[nodeId] = -1.0; } else { greatest_distance_of_maximal_descendant[nodeId] = node_iter->second; } currentDistance = getMaximalNodeDistance(nodeId, duplication_node_of_objects, pair_of_objects_yielding_duplication_node_distance, pair_of_nearest_objects_to_maximal_node); if (parent_iter == all_node_greatest_distance_of_maximal_descendant.end()) { all_node_greatest_distance_of_maximal_descendant[parentId] = currentDistance; } else { if (currentDistance > parent_iter->second) { all_node_greatest_distance_of_maximal_descendant[parentId] = currentDistance; } } } } int rootId = tree.getRootId(); obj_obj_max_node_iter = pair_of_nearest_objects_to_maximal_node.find(rootId); node_iter = all_node_greatest_distance_of_maximal_descendant.find(rootId); if (node_iter == all_node_greatest_distance_of_maximal_descendant.end()) { greatest_distance_of_maximal_descendant[rootId] = -1.0; } else { greatest_distance_of_maximal_descendant[rootId] = node_iter->second; } map<int, map<ObjectT, double> *>::iterator node_obj_dist_iter; for (node_obj_dist_iter = distances_to_maximizing_objects.begin(); node_obj_dist_iter != distances_to_maximizing_objects.end(); ++node_obj_dist_iter) { delete node_obj_dist_iter->second; } }
BeginMap::BeginMap(map<string, string> params):Level(){ MyGame::loaded=0; textIndex=0; isthread=false; SoundEffectManager::unloadData(); SoundEffectManager::loadFromFile("/Users/alexpeixoto/Desktop/sound.list"); p=new Adventure::Player("/Developer/movement.png", 32, 64); Point2f playerPosition; t=new Core::TextControl("/Developer/times.ttf"); d=new Dialog("/Developer/times.ttf"); pf=nullptr; mapLevel="/Users/alexpeixoto/Documents/maps/beginMap.map"; collisionLevel="/Users/alexpeixoto/Documents/maps/beginMap.map.collision"; itemLevel="/Users/alexpeixoto/Documents/maps/beginMap.map.item"; soundLevel="/Users/alexpeixoto/Documents/maps/beginMap.map.sound"; objectLevel="/Users/alexpeixoto/Documents/maps/beginMap.map.object"; warpLevel="/Users/alexpeixoto/Documents/maps/beginMap.map.warp"; mapManager.loadTileLayer(mapLevel); mapManager.loadCollisionMap(collisionLevel); mapManager.loadItemMap(itemLevel); mapManager.loadSoundMap(soundLevel); mapManager.loadObjectMap(objectLevel); mapManager.loadWarpMap(warpLevel); WarpManager::loadFromFile("/Users/alexpeixoto/Desktop/beginMap.map.warpList"); initData(); if(params.find("position") != params.end()){ if(params.at("position")=="outHouse"){ //disable animation mode=1; playerPosition.x = 320; playerPosition.y = 140; p->updateDirection(Adventure::Character::Directions::DOWN, true); p->call(); } else if(params.at("position")=="outTest"){ playerPosition.x = 560; playerPosition.y = 170; mapManager.move(-400, 0); p->updateDirection(Adventure::Character::Directions::LEFT, true); } else if(params.at("position")=="outObject"){ playerPosition.x = 290; playerPosition.y = 360; mapManager.move(0, -100); p->updateDirection(Adventure::Character::Directions::UP, true); } else{ playerPosition.x = 150; playerPosition.y = 300; p->updateDirection(Adventure::Character::Directions::LEFT, true); } } else{ playerPosition.x = 150; playerPosition.y = 300; p->updateDirection(Adventure::Character::Directions::LEFT, true); } p->setPosition(playerPosition); p->setLoop(true); p->setPixelsPerCall(150); p->resetLoopTo(3); p->setWidthScale(1); p->setHeightScale(1); p->setChangeOnCall(20); if(MyGame::oneCross==false){ BackgroundMusic::intersectWith("/Users/alexpeixoto/Downloads/AF/beginmap.ogg", BackgroundMusic::IntersectMode::CROSS, 4); MyGame::oneCross=true; } }
inline int setIndex(string s){ if(label2Index.find(s) == label2Index.end()) label2Index[s] = totalIndex++; }
static bool isFieldValid(const map<string, string> &codec, const char *field, Predicate p) { map<string, string>::const_iterator key(codec.find(field)); return key != codec.end() and p(key->second); }
void AdMatchManagerI::PvLog(const set<AdGroupPtr>& zone_selected, const UserProfile& profile, uint64_t user_key, AdInfoSeq& ad_info_seq, const string& referer, const AdZonePtr& zone_ptr, const map<Ice::Long, int>& group_costs, int rotate_index){ TimeStat ts; ostringstream log; int abs_pos = 1; vector<string> logseq; string referer_tmp = referer; LogHelper::instance().Process(referer_tmp); for(set<AdGroupPtr>::iterator sit = zone_selected.begin(); sit != zone_selected.end(); ++sit, ++abs_pos){ AdInfo ad_info; MyUtil::Date date(time(NULL)); AdGroupPtr group_ptr = *sit; AdEffectStat::instance().IncPv(user_key, group_ptr->group_id()); //MCE_INFO("AdMatchNManagerI::GetAds --> IncPv user_key = " << user_key << " group_id = " << group_ptr->group_id()); if(!group_ptr->creative_ids().empty()){ //ad_info.creativeid = *(group_ptr->creative_ids().begin()); int next_creative_index = 0; if(zone_ptr->GetRotateSize()){ next_creative_index = rotate_index / zone_ptr->GetRotateSize(); //MCE_INFO("AdMatchManagerI::PvLog --> userid = " << userid << " rotate_index = " << rotate_index << " RotateSize = " << zone_ptr->GetRotateSize() << " next_creative_index = " << next_creative_index); } ad_info.creativeid = group_ptr->GetNextCreative(next_creative_index); } else{ ad_info.creativeid = 0; } ad_info.groupid = group_ptr->group_id(); ad_info.updateTime = 0; LogParas log_para; log_para.server_index_ = server_index_; map<Ice::Long, int>::const_iterator cost_it = group_costs.find(ad_info.groupid); if(cost_it == group_costs.end()){ log_para.cost_ = 0; } else{ log_para.cost_ = cost_it->second; } log_para.user_profile_ = profile; log_para.pv_time_ = Date(time(NULL)).time(); log_para.creative_id_ = ad_info.creativeid; log_para.user_key_ = user_key; log_para.bid_unit_key_ = group_ptr->bid_unit_key(); log_para.max_price_ = group_ptr->max_price(); log_para.zone_id_ = zone_ptr->id(); log_para.ad_count_ = zone_ptr->ad_count(); ad_info.text = LogHelper::instance().MakeText(log_para); ad_info_seq.push_back(ad_info); //call AdLogAdapter Ice::Long zone_id = log_para.zone_id_; Ice::Long creativeid = log_para.creative_id_; string http = LogHelper::instance().MakeHttp(log_para); string ip = LogHelper::instance().MakeIp(profile.ip()); log << "[email protected]||" << ip << "||" << date.toDateTime() << "||\"GET " << http << " HTTP/1.0\"||" << "200||" << "undefined||" << "undefined||" << "undefined||" << "2||" << "1||" << "none||" << referer_tmp << "||" << zone_id << "^B^B^B^B^B^B^B" <<"||" << creativeid << "^B" << group_ptr->member_id() << "^B" << group_ptr->bid_unit_id() << "^B0^B" << group_ptr->max_price() << "^B" << referer_tmp << "^B" << abs_pos << "" << "^B1" << "^B2||4"; logseq.push_back(log.str()); /*try{ ts.reset(); logseq.push_buck(log.str()); //AdLogAdapter::instance().Pv(log.str()); //MCE_INFO("AdMatchManagerI::PvLog --> TIME_TEST write pv_log : " << ts.getTime()); } catch(Ice::Exception& e){ MCE_WARN("AdMatchManagerI::PvLog --> call AdLogAdapter.Pv ERR line:"<<__LINE__<<" err:"<<e); } catch(std::exception& e){ MCE_WARN("AdMatchManagerI::PvLog --> call AdLogAdapter.Pv ERR line:"<<__LINE__<<" err:"<<e.what()); }*/ log.str(""); } try{ AdLogAdapter::instance().PvBySeq(logseq); //MCE_INFO("AdMatchManagerI::PvLog --> TIME_TEST write pv_log : " << ts.getTime()); } catch(Ice::Exception& e){ MCE_WARN("AdMatchManagerI::PvLog --> call AdLogAdapter.Pv ERR line:"<<__LINE__<<" err:"<<e); } catch(std::exception& e){ MCE_WARN("AdMatchManagerI::PvLog --> call AdLogAdapter.Pv ERR line:"<<__LINE__<<" err:"<<e.what()); } }
static bool is_inactive(const map<string, string> &codec) { map<string, string>::const_iterator iter = codec.find(Account::VIDEO_CODEC_ENABLED); return iter == codec.end() or iter->second != "true"; }
VOID Trace(TRACE trace, VOID *v) { if ( KnobNoSharedLibs.Value() && IMG_Type(SEC_Img(RTN_Sec(TRACE_Rtn(trace)))) == IMG_TYPE_SHAREDLIB) return; RTN rtn = TRACE_Rtn(trace); ADDRINT rtn_address; const char *rtn_name; UINT32 rtn_num; if (!RTN_Valid(rtn)) { //cerr << "Cannot find valid RTN for trace at address" << TRACE_Address(trace); rtn_address = 0; rtn_name = "UNKNOWN"; rtn_num = 0; } else { rtn_num = RTN_Id(rtn); rtn_address = RTN_Address(rtn); rtn_name = RTN_Name(rtn).c_str(); } map<UINT32, RTN_TABLE_ENTRY *>::const_iterator it = rtn_table.find(rtn_num); if (it == rtn_table.end()) { char *str = new char [ strlen(rtn_name) + 1]; strcpy(str, rtn_name); RTN_TABLE_ENTRY *rtn_table_entry = new RTN_TABLE_ENTRY(rtn_address, str); rtn_table[rtn_num] = rtn_table_entry; } const BOOL accurate_handling_of_predicates = KnobProfilePredicated.Value(); for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)) { // Summarize the stats for the bbl in a 0 terminated list // This is done at instrumentation time const UINT32 n = IndexStringLength(bbl, 1); UINT16 *const stats = new UINT16[ n + 1]; UINT16 *const stats_end = stats + (n + 1); UINT16 *curr = stats; UINT32 numins = 0; UINT32 size = 0; for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) { if ((INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins)) && !INS_IsStandardMemop(ins)) continue; numins += 1; size += INS_Size(ins); // Count the number of times a predicated instruction is actually executed // this is expensive and hence disabled by default if( INS_IsPredicated(ins) && accurate_handling_of_predicates ) { INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(docount), IARG_FAST_ANALYSIS_CALL, IARG_PTR, &(GlobalStatsDynamic.predicated_true[INS_Opcode(ins)]), IARG_END); } curr = INS_GenerateIndexString(ins,curr,1); } // string terminator *curr++ = 0; ASSERTX( curr == stats_end ); // Insert instrumentation to count the number of times the bbl is executed BBLSTATS * bblstats = new BBLSTATS(stats, INS_Address(BBL_InsHead(bbl)), rtn_num, size, numins ); INS_InsertCall(BBL_InsHead(bbl), IPOINT_BEFORE, AFUNPTR(docount), IARG_FAST_ANALYSIS_CALL, IARG_PTR, &(bblstats->_counter), IARG_END); // Remember the counter and stats so we can compute a summary at the end statsList.push_back(bblstats); } }
bool // returns true if success processTreeSection(FILE *fp, string& theline, bool& new_section) { string *tid = NULL; TChain *t1 = NULL; vector<string> v_tokens; string treename; if (gl_verbose) cout << "Processing Tree section" << endl; new_section=false; while (getLine(fp,theline,"Tree")) { if (!theline.size()) continue; if (theline[0] == '#') continue; // comments are welcome if (theline[0] == '[') { new_section=true; break; } string key, value; if (!getKeyValue(theline,key,value)) continue; //-------------------- if (key == "id") { //-------------------- if (tid != NULL) { cerr << "no more than one id per F1 section allowed " << value << endl; break; } tid = new string(value); map<string, TChain *>::const_iterator tit = glmap_id2chain.find(*tid); if (tit != glmap_id2chain.end()) { cerr << "Tree id " << *tid << " already defined" << endl; break; } //------------------------------ } else if( key == "treename" ) { //------------------------------ if( !tid ) { cerr << "id key must be defined first in the section" << endl; continue; } if( t1 ) { cerr << "Tree already defined" << endl; continue; } treename = value; //------------------------------ } else if( key == "globslist" ) { //------------------------------ t1 = getChainFromGlobslist(*tid,treename,value); if( !t1 ) exit(-1); //------------------------------ } else if( key == "copytree" ) { //------------------------------ if( !tid ) { cerr << "id key must be defined first in the section" << endl; continue; } Tokenize(value,v_tokens,","); if (v_tokens.size() != 2) { cerr << "copytree syntax expected: copytree=treeid,cutstring: " << value << endl; continue; } TChain *t2 = findChain(v_tokens[0]); if (!t2) { cerr << "tree " << v_tokens[0] << " must be defined previously" << endl; continue; } if (gl_verbose) cout<<"Begin CopyTree of "<<v_tokens[0]<<" with selection "<<v_tokens[1]<<flush; t1 = (TChain *)(t2->CopyTree(v_tokens[1].c_str())); if( !t1 ) { cerr << "CopyTree failed" << endl; exit(-1); } if (gl_verbose) cout<<"...Done."<<endl; //------------------------------ } else if( key == "save2file" ) { //------------------------------ if( !t1 ) { cerr << "save2file: must define tree first" << endl; continue; } TFile *rootfile = openRootFile(value,"RECREATE"); t1->SetDirectory(rootfile); t1->Write(); rootfile->Flush(); if (gl_verbose) cout << "Tree written to file " << value << endl; rootfile->Close(); //------------------------------ } else if( key == "unbinnedfit" ) { //------------------------------ if( !tid ) { cerr << "id key must be defined first in the section" << endl; continue; } if( !t1 ) { cerr << "Tree must already be defined using 'globslist'" << endl; continue; } int fitresult=-99; Tokenize(value,v_tokens,","); switch(v_tokens.size()) { case 2: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(), v_tokens[1].c_str()); break; case 3: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(), v_tokens[1].c_str(), v_tokens[2].c_str()); break; case 4: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(), // funcname v_tokens[1].c_str(), // varexp v_tokens[2].c_str(), // selection v_tokens[3].c_str()); // option break; default: cerr << "unbinnedfit: expect 2-4 arguments separated by commas: " << value <<endl; exit(-1); } cout << "fit result returned = " << fitresult << endl; cout << "Number of selected entries in the fit = " << t1->GetSelectedRows() << endl; } else { cerr << "unknown key " << key << endl; } } if (tid) delete tid; return (t1 != NULL); } // processTreesection
bool LoadSound(const char* filename, bool sfxr) { auto it = sound_files.find(filename); Sound snd; if (it == sound_files.end()) { size_t len = 0; uchar *buf = LoadFile(filename, &len); if (!buf) return false; if (sfxr) { snd.buf = buf; snd.len = len; } else { SDL_AudioSpec wav_spec; Uint32 wav_len; auto wav_spec_ret = SDL_LoadWAV_RW(SDL_RWFromMem(buf, len), true, &wav_spec, &snd.buf, &wav_len); free(buf); if (!wav_spec_ret) return false; snd.len = wav_len; SDL_AudioCVT wav_cvt; int ret = SDL_BuildAudioCVT(&wav_cvt, wav_spec.format, wav_spec.channels, wav_spec.freq, playbackspec.format, playbackspec.channels, playbackspec.freq); if (ret < 0) { SDL_FreeWAV(snd.buf); return false; } if (ret) { wav_cvt.buf = (uchar *)malloc(snd.len * wav_cvt.len_mult); wav_cvt.len = snd.len; memcpy(wav_cvt.buf, snd.buf, snd.len); SDL_FreeWAV(snd.buf); SDL_ConvertAudio(&wav_cvt); snd.buf = wav_cvt.buf; // caution: len is not size of buffer anymore, but size of valid data.. // that works ok with SDL_FreeWAV/free snd.len = size_t(wav_cvt.len * wav_cvt.len_ratio); } } snd.sfxr = sfxr; sound_files[filename] = snd; } else { snd = it->second; if (sfxr != snd.sfxr) // wav file and sfxr file with same name? should be very rare :) return false; } if (sfxr) { uchar *file = snd.buf; int version = 0; fread_mem(&version, 1, sizeof(int), file); if(version!=102) return false; fread_mem(&wave_type, 1, sizeof(int), file); fread_mem(&sound_vol, 1, sizeof(float), file); fread_mem(&p_base_freq, 1, sizeof(float), file); fread_mem(&p_freq_limit, 1, sizeof(float), file); fread_mem(&p_freq_ramp, 1, sizeof(float), file); fread_mem(&p_freq_dramp, 1, sizeof(float), file); fread_mem(&p_duty, 1, sizeof(float), file); fread_mem(&p_duty_ramp, 1, sizeof(float), file); fread_mem(&p_vib_strength, 1, sizeof(float), file); fread_mem(&p_vib_speed, 1, sizeof(float), file); fread_mem(&p_vib_delay, 1, sizeof(float), file); fread_mem(&p_env_attack, 1, sizeof(float), file); fread_mem(&p_env_sustain, 1, sizeof(float), file); fread_mem(&p_env_decay, 1, sizeof(float), file); fread_mem(&p_env_punch, 1, sizeof(float), file); fread_mem(&filter_on, 1, sizeof(bool), file); fread_mem(&p_lpf_resonance, 1, sizeof(float), file); fread_mem(&p_lpf_freq, 1, sizeof(float), file); fread_mem(&p_lpf_ramp, 1, sizeof(float), file); fread_mem(&p_hpf_freq, 1, sizeof(float), file); fread_mem(&p_hpf_ramp, 1, sizeof(float), file); fread_mem(&p_pha_offset, 1, sizeof(float), file); fread_mem(&p_pha_ramp, 1, sizeof(float), file); fread_mem(&p_repeat_speed, 1, sizeof(float), file); fread_mem(&p_arp_speed, 1, sizeof(float), file); fread_mem(&p_arp_mod, 1, sizeof(float), file); } cursnd = snd; return true; }
void callback(event *ev) { map<string, bool>::iterator iter; string hex_id; string actual_identifier; int ntohl_number_of_fragments; int distance; hex_id = chararray_to_hex(ev->id); switch (ev->type) { case SCOPE_PUBLISHED: cout << "SCOPE_PUBLISHED: " << hex_id << endl; delete ev; break; case SCOPE_UNPUBLISHED: cout << "SCOPE_UNPUBLISHED: " << hex_id << endl; delete ev; break; case START_PUBLISH: cout << "START_PUBLISH: " << hex_id << endl; /*I don't need to do anything here..The publisher will receive the backpath "hello" message implicitly when the first request for retransmission will be sent*/ delete ev; break; case STOP_PUBLISH: cout << "STOP_PUBLISH: " << hex_id << endl; delete ev; break; case PUBLISHED_DATA: //cout << "PUBLISHED_DATA: " << hex_id << endl; pthread_mutex_lock(&global_mutex); iter = expectedInfo.find(ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN)); if (iter != expectedInfo.end()) { /*this is not a retransmitted fragment*/ if ((*iter).second == false) { (*iter).second = true; /*this is the the first fragment I receive*/ /*start measuring*/ gettimeofday(&start_tv, &tz); printf("START TIME: %ld,%ld \n", start_tv.tv_sec, start_tv.tv_usec); create_random_ID(backchannel_id); ba->publish_info(backchannel_id, ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid1, DOMAIN_LOCAL, NULL, 0); ba->subscribe_info(backchannel_id, ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid2, DOMAIN_LOCAL, NULL, 0); efs = new ExpectedFragmentSequence(); efs->firstID = ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN) + string((const char *) ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, sizeof (int)).c_str(), sizeof (int)) + hex_to_chararray("00000000"); memcpy(&ntohl_number_of_fragments, ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, sizeof (int)).c_str(), sizeof (int)); efs->number_of_fragments = ntohl(ntohl_number_of_fragments); efs->fragments_so_far = 1; efs->fragments_map = bitvector(efs->number_of_fragments); distance = calculate_number_of_fragments(efs->firstID, ev->id) - 1; //e.g. from 0 to 1 distance = 1 efs->fragments_map[distance] = true; efs->time_beat = 3; efs->p_to_s_channel = ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid2 + backchannel_id; efs->s_to_p_channel = ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid1 + backchannel_id; retransmission_channel_map.insert(pair<string, string > (efs->p_to_s_channel, bin_item_identifier)); efs->printEFS(); //cout << efs->fragments_map.to_string().c_str() << endl; pthread_create(&timeout_thread, NULL, timeout_handler, NULL); } else { distance = calculate_number_of_fragments(efs->firstID, ev->id) - 1; //e.g. from 0 to 1 distance = 1 if (bitvector::bit::unspecified_bool_type(efs->fragments_map[distance]) == false) { efs->fragments_so_far++; efs->fragments_map[distance] = true; efs->time_beat = 3; //cout << efs->fragments_map.to_string().c_str() << endl; if (efs->fragments_so_far == efs->number_of_fragments) { pthread_cancel(timeout_thread); efs->printResult(); delete efs; efs = NULL; delete ev; delete ba; break; } } else { cout << "Received a duplicate fragment: " << hex_id << endl; } } } else { /*A retransmission*/ actual_identifier = (*retransmission_channel_map.find(ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN))).second + ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, PURSUIT_ID_LEN); distance = calculate_number_of_fragments(efs->firstID, actual_identifier) - 1; //e.g. from 0 to 1 distance = 1 if (bitvector::bit::unspecified_bool_type(efs->fragments_map[distance]) == false) { efs->fragments_so_far++; efs->fragments_map[distance] = true; efs->time_beat = 3; //cout << efs->fragments_map.to_string().c_str() << endl; if (efs->fragments_so_far == efs->number_of_fragments) { pthread_cancel(timeout_thread); efs->printResult(); delete efs; efs = NULL; delete ev; delete ba; break; } } else { cout << "Received a duplicate fragment: " << hex_id << endl; } } pthread_mutex_unlock(&global_mutex); delete ev; break; } }
Tag * Tag::find( const string & s ) { if ( tags.find( s ) == tags.end() ) return 0; return tags[s]; }
/** * This populates darkCorrections with the result of the equation: * dark = a + x * b * for each line,band. a, b are from the "vis_*_dark_model.tab" files * and x is the ExposureDuration. * * @param icube */ void calculateVisDarkCurrent(Cube *icube) { PvlGroup &inst = icube->label()->findGroup("Instrument", Pvl::Traverse); // This is the dark current corrections for VIS bool hires = ((inst["SamplingMode"][0] == "HIGH") || (inst["SamplingMode"][0] == "HI-RES")); QString calFile = "$cassini/calibration/vims/vis_"; if(hires) { calFile += "hires"; } else { calFile += "lowres"; } calFile += "_dark_model_v????.tab"; FileName calFileName(calFile); calFileName = calFileName.highestVersion(); calibInfo += PvlKeyword("DarkCurrentFile", calFileName.originalPath() + "/" + calFileName.name()); calFile = calFileName.expanded(); EndianSwapper swapper("LSB"); FILE *calFilePtr = fopen(calFile.toAscii().data(), "r"); double visExposure = toDouble(inst["ExposureDuration"][1]); int sampleOffset, lineOffset; GetOffsets(*icube->label(), sampleOffset, lineOffset); /** * Reading in one parameter at a time: * parameter 1 = constant coefficient * parameter 2 = exposure coefficient * param1 + param2*exposure = dark correction * * Do byte swapping where necessary. */ for(int parameter = 1; parameter <= 2; parameter ++) { for(int band = 1; band <= 96; band++) { for(int sample = 1; sample <= 64; sample++) { float calData; if(fread(&calData, sizeof(calData), 1, calFilePtr) != 1) { // error! QString msg = "Error reading file [" + calFile + "]"; throw IException(IException::Io, msg, _FILEINFO_); } int associatedSample = sample - sampleOffset + 1; calData = swapper.Float(&calData); pair<int, int> index = pair<int, int>(associatedSample, band); map< pair<int, int>, double>::iterator pos = sampleBasedDarkCorrections.find(index); if(pos == sampleBasedDarkCorrections.end()) { sampleBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, calData)); } else { (*pos).second = (*pos).second + visExposure * calData; } } } } fclose(calFilePtr); // If spectral summing is on, go in sets of 8 and set darks to the average /* PvlGroup &archive = icube->Label()->findGroup("Archive", Pvl::Traverse); if(archive["SpectralSummingFlag"][0] == "ON") { for(int band = 1; band <= 96; band += 8) { for(int sample = 1; sample <= 64; sample++) { Statistics stats; // we're calculating an average of 8 of these values through the bands for(int avgIndex = 0; avgIndex < 8; avgIndex ++) { // this wont go out of bounds as long as we have 8 as the increment pair<int,int> index = pair<int,int>(sample, band+avgIndex); stats.AddData(sampleBasedDarkCorrections.find(index)->second); } // now set the values to the average for(int setIndex = 0; setIndex < 8; setIndex ++) { pair<int,int> index = pair<int,int>(sample, band+setIndex); if(!setIndex) printf("Changing %.4f to %.4f\n", sampleBasedDarkCorrections.find(index)->second, stats.Average()); sampleBasedDarkCorrections.find(index)->second = stats.Average(); } } } }*/ }
void Tag::ensure( const string & n, bool regular ) { if ( tags.find( n ) == tags.end() ) (void)new Tag( n, regular ); }
bool VarFileInfo::Test(int j) const { map <int, struct STAT64>::const_iterator iter = _varStatMap.find(j); return(iter != _varStatMap.end()); }
void XmlPrinter::printProbeHelper (xmlTextWriterPtr writer, Component * component) { addAttributes(writer, component->getAttributes( )); std::map<string, string> desc = component->getDescription( ); string body = component->getDescriptionBody( ); if ( ( desc.size( ) > 0 ) || !body.empty( ) ) { addSimpleElement(writer, "Description", body, &desc); } if ( !component->getConfiguration( ).empty( ) ) { THROW_IF_XML2_ERROR(xmlTextWriterStartElement(writer, BAD_CAST "Configuration")); THROW_IF_XML2_ERROR(xmlTextWriterWriteRaw(writer, BAD_CAST component->getConfiguration( ).c_str( ))); THROW_IF_XML2_ERROR(xmlTextWriterEndElement(writer)); // Configuration } list<DataItem *> datum = component->getDataItems( ); if ( datum.size( ) > 0 ) { THROW_IF_XML2_ERROR(xmlTextWriterStartElement(writer, BAD_CAST "DataItems")); list<DataItem *>::iterator data; for ( data = datum.begin( ); data != datum.end( ); data++ ) { printDataItem(writer, *data); } THROW_IF_XML2_ERROR(xmlTextWriterEndElement(writer)); // DataItems } list<Component *> children = component->getChildren( ); if ( children.size( ) > 0 ) { THROW_IF_XML2_ERROR(xmlTextWriterStartElement(writer, BAD_CAST "Components")); list<Component *>::iterator child; for ( child = children.begin( ); child != children.end( ); child++ ) { xmlChar *name = NULL; if ( !( *child )->getPrefix( ).empty( ) ) { map<string, SchemaNamespace>::iterator ns = sDevicesNamespaces.find(( *child )->getPrefix( )); if ( ns != sDevicesNamespaces.end( ) ) { name = BAD_CAST(*child)->getPrefixedClass( ).c_str( ); } } if ( name == NULL ) { name = BAD_CAST(*child)->getClass( ).c_str( ); } THROW_IF_XML2_ERROR(xmlTextWriterStartElement(writer, name)); printProbeHelper(writer, *child); THROW_IF_XML2_ERROR(xmlTextWriterEndElement(writer)); // Component } THROW_IF_XML2_ERROR(xmlTextWriterEndElement(writer)); // Components } }
BBObj *_bbObjFromHandle( int handle,BBObjType *type ){ map<int,BBObj*>::const_iterator it=handle_map.find( handle ); if( it==handle_map.end() ) return 0; BBObj *obj=it->second; return obj->type==type ? obj : 0; }
void SfMgr::addNtk2(uint32_t from_handler,uint32_t to_handler,map<uint32_t,V3NetId>& IdMap,uint32_t nid,map<uint32_t,bool>& block_list,bool add_in,bool add_out){ V3NtkInput* fromHandler = (V3NtkInput*)v3Handler.getHandler(from_handler); V3NtkInput* toHandler = (V3NtkInput*)v3Handler.getHandler(to_handler); // cout<<"*****create_net_start:"<<fromHandler->getNtkName()<<"*****"<<endl; V3NetVec orderedNets; orderedNets.clear(); V3BvNtk* ntk = (V3BvNtk*)(fromHandler->getNtk()); orderedNets.reserve(ntk->getNetSize()); dfsNtkForGeneralOrder(ntk,orderedNets); assert (orderedNets.size() <= ntk->getNetSize()); V3BvNtk* new_ntk = (V3BvNtk*)(toHandler->getNtk()); for(unsigned i = 0 ; i < orderedNets.size() ; ++i){ V3NetId old_nid = orderedNets[i]; map<uint32_t,bool>::iterator it = block_list.find( old_nid.id); if(it!=block_list.end()){ if(!it->second){ cout<<"block:"<<it->first<<endl; continue; } else if(it->second){ //const V3GateType& type = ntk->getGateType(old_nid); string name = fromHandler->getNetNameOrFormedWithId(old_nid); V3NetId new_nid= getMapNetId2(fromHandler,toHandler,old_nid,IdMap,nid); cout<<"boundary:"<<it->first<<endl; continue; } } const V3GateType& type = ntk->getGateType(old_nid); string name = fromHandler->getNetNameOrFormedWithId(old_nid); // V3NetId new_nid = toHandler->createNet(name ,static_cast<V3BvNtk*>(ntk)->getNetWidth(old_nid)); // new_nid.cp = old_nid.cp; // IdMap[old_nid.id]=new_nid; // ??? V3NetId new_nid= getMapNetId2(fromHandler,toHandler,old_nid,IdMap,nid); cout<<"i:"<<old_nid.id <<" name:"<< name << " type:"<<(old_nid.cp ? "~" : "")<< V3GateTypeStr[type]<<endl; if(BV_CONST==type) continue; if (V3_MODULE == type) { Msg(MSG_WAR) << "Currently Expression Over Module Instances has NOT Been Implemented !!" << endl; } if (isV3PairType(type)) { V3NetId old_nid0 = ntk->getInputNetId(old_nid, 0); V3NetId old_nid1 = ntk->getInputNetId(old_nid, 1); V3NetId new_nid0 = getMapNetId2(fromHandler,toHandler,old_nid0,IdMap,nid); V3NetId new_nid1 = getMapNetId2(fromHandler,toHandler,old_nid1,IdMap,nid); // new_nid0.cp = old_nid0.cp; // new_nid1.cp = old_nid1.cp; cout<<"new:"<<new_nid.id << " type:"<< (new_nid.cp ? "~" : "")<< V3GateTypeStr[new_ntk->getGateType(new_nid)]<<endl; cout<<"new0:"<<new_nid0.id << " type:"<< (new_nid0.cp ? "~" : "")<< V3GateTypeStr[new_ntk->getGateType(new_nid0)]<<endl; cout<<"new1:"<<new_nid1.id << " type:"<< (new_nid1.cp ? "~" : "")<< V3GateTypeStr[new_ntk->getGateType(new_nid1)]<<endl; assert(createBvPairGate(new_ntk, type, new_nid, new_nid0, new_nid1)); } else if (isV3ReducedType(type)) { V3NetId old_nid0 = ntk->getInputNetId(old_nid, 0); V3NetId new_nid0 = getMapNetId2(fromHandler,toHandler,old_nid0,IdMap,nid); // new_nid0.cp = old_nid0.cp; assert(createBvReducedGate(new_ntk, type, new_nid, new_nid0)); } else if (BV_MUX == type) { V3NetId old_nid0 = ntk->getInputNetId(old_nid, 0); V3NetId old_nid1 = ntk->getInputNetId(old_nid, 1); V3NetId old_nid2 = ntk->getInputNetId(old_nid, 2); V3NetId new_nid0 = getMapNetId2(fromHandler,toHandler,old_nid0,IdMap,nid); V3NetId new_nid1 = getMapNetId2(fromHandler,toHandler,old_nid1,IdMap,nid); V3NetId new_nid2 = getMapNetId2(fromHandler,toHandler,old_nid2,IdMap,nid); // new_nid0.cp = old_nid0.cp; // new_nid1.cp = old_nid1.cp; // new_nid2.cp = old_nid2.cp; assert(createBvMuxGate(new_ntk, new_nid, new_nid0, new_nid1, new_nid2)); } else if (BV_SLICE == type) { V3NetId old_nid0 = ntk->getInputNetId(old_nid, 0); V3NetId new_nid0 = getMapNetId2(fromHandler,toHandler,old_nid0,IdMap,nid); // new_nid0.cp = old_nid0.cp; const uint32_t msb = static_cast<V3BvNtk*>(ntk)->getInputSliceBit(old_nid, true); const uint32_t lsb = static_cast<V3BvNtk*>(ntk)->getInputSliceBit(old_nid, false); assert(createBvSliceGate(new_ntk, new_nid, new_nid0, msb,lsb)); } else if(BV_CONST == type){ } else if (AIG_NODE == type) { assert(0); } else if(AIG_FALSE == type){ assert(0); } else if(V3_PI ==type){ if(add_in){ assert(createInput(new_ntk, new_nid)); } } else if(V3_PIO==type){ if((add_in)&&(add_out)){ assert(createInout(new_ntk, new_nid)); } } else{ assert(0); } } if(add_out){ for(uint32_t i = 0 , j = ntk->getOutputSize() ; i < j ; ++i){ V3NetId outid = ntk->getOutput(i); V3NetId new_outid = getMapNetId2(fromHandler,toHandler,outid,IdMap,nid); // new_outid.cp = outid.cp; assert(createOutput(new_ntk, new_outid)); } } V3StrVec outputName(new_ntk->getOutputSize(), ""); for (uint32_t i = 0; i < new_ntk->getOutputSize(); ++i){ if (outputName[i].size()){ toHandler->recordOutName(i, outputName[i]); } else{ toHandler->recordOutName(i, "output_" + v3Int2Str(i)); } } // cout<<"*****create_net_end:"<<fromHandler->getNtkName()<<"*****"<<endl; }
void SbmlReader::createReaction(const map< string, Id > &molSidcmptMIdMap ) { Reaction* reac; map< string,double > rctMap; map< string,double >::iterator rctMap_iter; map< string,double >prdMap; map< string,double >::iterator prdMap_iter; map< string,EnzymeInfo >enzInfoMap; for ( unsigned int r = 0; r < model_->getNumReactions(); r++ ) { Id reaction_; reac = model_->getReaction( r ); noOfsub_ = 0; noOfprd_ = 0; std:: string id; //=reac->getId(); if ( reac->isSetId() ) id = reac->getId(); std::string name; if ( reac->isSetName() ) { name = reac->getName(); name = nameString(name); } if (name.empty()) { if (id.empty()) assert("Reaction id and name is empty"); else name = id; } string grpname = getAnnotation( reac,enzInfoMap ); if ( (grpname != "") && (enzInfoMap[grpname].stage == 3) ) { setupEnzymaticReaction( enzInfoMap[grpname],grpname ,molSidcmptMIdMap,name); } //if (grpname != "") // { //cout << "\n enz matic reaction " << enzInfoMap[grpname].stage; //setupEnzymaticReaction( enzInfoMap[grpname],grpname ,molSidcmptMIdMap); //} else if ( grpname == "" ) { if (reac->getNumModifiers() > 0) setupMMEnzymeReaction( reac,id,name ,molSidcmptMIdMap); else { bool rev=reac->getReversible(); bool fast=reac->getFast(); if ( fast ) { cout<<"warning: for now fast attribute is not handled"<<endl; errorFlag_ = true; } int numRcts = reac->getNumReactants(); int numPdts = reac->getNumProducts(); if ( numRcts == 0 && numPdts != 0 ) { cout << "Reaction with zero Substrate is not possible but exist in this model"; const SpeciesReference* pdt = reac->getProduct( 0 ); std::string spName = pdt->getSpecies(); Id parent = molSidcmptMIdMap.find( spName )->second; //gives compartment of spName cout << " \n \t ################################# Sub = 0 and prd != 0 need to the reac ############### "; const SpeciesReference* rect=reac->getReactant(0); std::string sp=rect->getSpecies(); Id comptRef = molSidcmptMIdMap.find(sp)->second; //gives compartment of sp Id meshEntry = Neutral::child( comptRef.eref(), "mesh" ); Shell* shell = reinterpret_cast< Shell* >( Id().eref().data() ); reaction_ = shell->doCreate("Reac", meshEntry, name, 1); //shell->doAddMsg( "Single", meshEntry, "remeshReacs", reaction_, "remesh"); //Get Substrate addSubPrd(reac,reaction_,"prd"); } //if numRcts == 0 else { const SpeciesReference* rect=reac->getReactant(0); std::string sp=rect->getSpecies(); Id comptRef = molSidcmptMIdMap.find(sp)->second; //gives compartment of sp Id meshEntry = Neutral::child( comptRef.eref(), "mesh" ); Shell* shell = reinterpret_cast< Shell* >( Id().eref().data() ); reaction_ = shell->doCreate("Reac", comptRef, name, 1); //shell->doAddMsg( "Single", meshEntry, "remeshReacs", reaction_, "remesh"); //Get Substrate addSubPrd(reac,reaction_,"sub"); //Get Product addSubPrd(reac,reaction_,"prd"); } if ( reac->isSetKineticLaw() ) { KineticLaw * klaw=reac->getKineticLaw(); //vector< double > rate = getKLaw( klaw,rev ); vector< double > rate; rate.clear(); getKLaw( klaw,rev,rate ); if ( errorFlag_ ) return; else if ( !errorFlag_ ) { //cout << " Reaction name " << name << " kf " << rate[0] << " kb " << rate[1]<<endl; Field < double > :: set( reaction_, "Kf", rate[0] ); Field < double > :: set( reaction_, "Kb", rate[1] ); /*if (numRcts > 1) rate[0] = rate[0]*pow(1e3,1.0); cout << "Reaction " << id << " " << name << " " << rate[0] << " " << rate[1]<<endl; Field < double > :: set( reaction_, "Kf", rate[0] ); Field < double > :: set( reaction_, "Kb", rate[1] ); */ } } //issetKineticLaw } //else } // else grpname == "" }//for unsigned } //reaction
void readUserDataCsv(map<int,User*> &userMap, Category *cats, int const * const categoryMap, map<int,int> &adToCat, set<int> &enabledAds) { string line; ifstream file; file.open("user_data.csv"); int lines = 0; getline(file, line); // Header while(getline(file, line, ',')) { if(lines % 10000 == 0) cerr << ":"; #ifdef EARLY_BREAK if(lines > EARLY_BREAK) break; #endif ++lines; // Read time: // Timestamp of type "2017-06-30 12:34:56" // 0 2 4 6 8 12 16 18 int month, day, hour, minute, second; sscanf(&(line.c_str()[6]), "%d-%d %d:%d:%d", &month, &day, &hour, &minute, &second); long time = month * 32 + day; time = 24*time + hour; time = 60*time + minute; time = 60*time + second; // Read user id: getline(file, line, ','); int id; sscanf(&(line.c_str()[1]), "%d", &id); //cerr << "User id " << id << endl; // event: getline(file, line, ','); // Channel (ignore for now: getline(file, line, ','); // User position: double lat, lon; getline(file, line, ','); sscanf(&(line.c_str()[1]), "%lf", &lat); getline(file, line, ','); sscanf(&(line.c_str()[1]), "%lf", &lon); //cerr << "Position: " << lat << ", " << lon << endl; // Origin: getline(file, line, ','); // Rest of line: int adID; getline(file, line, ','); sscanf(&(line.c_str()[1]), "%d", &adID); getline(file, line); // Update cnt for views: if(enabledAds.find(adID) != enabledAds.end()) { Category &CC = cats[categoryMap[adToCat[adID]]]; CC.adImpressionsCounts[adID]++; } // Update last position: User *user; if(userMap.find(id) == userMap.end()) { user = new User; userMap[id] = user; } else user = userMap[id]; user->lastPosition = PD(lat,lon); Impression impression; impression.time = time; impression.adID = adID; user->impressions.push_back(impression); } // Find maxViewDist for all users: cerr << "Finding max dist view for all users." << endl; for(map<int,User*>::iterator it = userMap.begin(); it != userMap.end(); ++it) { User *user = it->second; // Sort impressions by date: sort(user->impressions.begin(), user->impressions.end()); // Find maximal allowed dist for ads by considering the last 5 impressions: PD userPos = user->lastPosition; user->maxViewDist = 0; int cnt = 0; for(vector<Impression>::reverse_iterator it2 = user->impressions.rbegin(); it2 != user->impressions.rend() && ++cnt <= 5; ++it2) { double dist = distSq(userPos, getAdPosition(it2->adID, cats, categoryMap, adToCat)); if(dist > user->maxViewDist) user->maxViewDist = dist; } } cout << lines << " lines read from user_data.csv. " << userMap.size() << " users." << endl; file.close(); }