void HPBD::build() { PBD *base = p.back(); int *edge_num = new int[base->obj->p.size()]; int *tmp_i = new int[base->obj->p.size()]; bool *is_fine = new bool[base->obj->p.size()]; bool *is_mark = new bool[base->obj->p.size()]; double *weight = new double[base->obj->p.size()]; hash_map<PBDparticle *,int> h; vector<int> *v = new vector<int>[base->obj->p.size()]; PBDparticle **next_pp = new PBDparticle*[base->obj->p.size()]; int i, j, k; int l_iter; for(l_iter = 1; l_iter < level_max; l_iter++) { base = p.back(); h.clear(); for(i=0;i<base->obj->p.size();i++) { edge_num[i] = 0; is_fine[i] = false; is_mark[i] = false; h[base->obj->p[i]] = i; tmp_i[i] = i; v[i].clear(); if(base->obj->p[i]->w<E) weight[i] = -1; else weight[i] = 1/base->obj->p[i]->w; } for(i=0;i<base->con.size();i++) { if(base->con[i]->n == 2) { edge_num[h[base->con[i]->p[0]]]++; edge_num[h[base->con[i]->p[1]]]++; v[h[base->con[i]->p[0]]].push_back(h[base->con[i]->p[1]]); v[h[base->con[i]->p[1]]].push_back(h[base->con[i]->p[0]]); } } for(i=0;i<base->obj->p.size();i++) { sort(v[i].begin(),v[i].end()); v[i].erase(unique(v[i].begin(),v[i].end()),v[i].end()); } random_shuffle(tmp_i, tmp_i+base->obj->p.size()); for(k=0;k<base->obj->p.size();k++) { i = tmp_i[k]; if(!is_fine[i]) { if(edge_num[i] >= k_e) { vector3f sum; for(j=0;j<v[i].size();j++) { if(is_fine[v[i][j]] && edge_num[v[i][j]] <= k_e) break; vector3f xx = (base->obj->p[v[i][j]]->pos - base->obj->p[i]->pos); xx.normalize(); sum += xx; } if(j == v[i].size()) { if(v[i].size() > 0) { sum.normalize(); double ssum=0; for(j=0;j<v[i].size();j++) { vector3f xx = (base->obj->p[v[i][j]]->pos - base->obj->p[i]->pos); xx.normalize(); ssum = max(ssum,abs(xx*sum)); } // printf("%lf\n",ssum); if(ssum > 0.92) // 18 angle { // base->obj->p[i]->temp = true; continue; } } is_fine[i] = true; for(j=0;j<v[i].size();j++) { edge_num[v[i][j]]--; } } } } } PBD *next = new PBD(); next->obj = new PBDobject(); int cnt=0; while(1) { int dddddd = 0; for(i=0;i<base->obj->p.size();i++) { if(is_fine[i]) { if(is_mark[i]) continue; int pj; double mm = -1; for(j=0; j<v[i].size();j++) if(!is_fine[v[i][j]]) { if(mm<-0.5 || mm > base->obj->p[i]->pos.dist(base->obj->p[v[i][j]]->pos)) { mm = base->obj->p[i]->pos.dist(base->obj->p[v[i][j]]->pos); pj = v[i][j]; } } if(mm < -0.5) continue; dddddd = 1; if(rand()%2==0)continue; is_mark[i] = true; for(j=0;j<v[i].size();j++) { if(weight[i] < -0.2) weight[v[i][j]] = -1; else weight[v[i][j]] += weight[i] / v[i].size(); if(is_mark[v[i][j]] || pj == v[i][j])continue; v[pj].push_back(v[i][j]); v[v[i][j]].push_back(pj); } sort(v[pj].begin(),v[pj].end()); v[pj].erase(unique(v[pj].begin(),v[pj].end()),v[pj].end()); } } if(dddddd == 0)break; cnt++; } printf("%d\n",cnt); for(i=0;i<base->obj->p.size();i++) { sort(v[i].begin(),v[i].end()); v[i].erase(unique(v[i].begin(),v[i].end()),v[i].end()); } for(i=0;i<base->obj->p.size();i++) { if(!is_fine[i]) { PBDparticle *particle = new PBDparticle(); particle->set(base->obj->p[i]); if(weight[i] < -0.2) particle->w = 0; else { particle->w = 1/weight[i]; } base->obj->p[i]->temp = true; next->obj->p.push_back(particle); for(j=0;j<v[i].size();j++) { if(!is_fine[v[i][j]] && v[i][j] < i) { PBDconstraint_distance *constraint = new PBDconstraint_distance(); constraint->n = 2; constraint->p.push_back(particle); constraint->p.push_back(next_pp[v[i][j]]); constraint->del.push_back(vector3f(0,0,0)); constraint->del.push_back(vector3f(0,0,0)); constraint->stiff = next->k_stretch * (1 - (double)(l_iter)/level_max *(0.5)); constraint->init_dist = particle->pos.dist(next_pp[v[i][j]]->pos); next->con.push_back(constraint); } } next_pp[i] = particle; } } p.push_back(next); printf("- %d\np : %d\nc : %d\n",l_iter,next->obj->p.size(), next->con.size()); } for(i=0;i<level_max; i++) { // p[i]->iter_max -= (int)(i*1.5); // if(p[i]->iter_max <= 0) p[i]->iter_max = 1; } }
void Subtypes::sortSubTypes() { sort(subtypesCreature.begin(),subtypesCreature.end()); subtypesCreature.erase(unique(subtypesCreature.begin(),subtypesCreature.end()),subtypesCreature.end()); return; }
QString Driver::findOrInsertName(const QString &name) { return unique(name); }
vector<int> NList::expandNumberList(vector<int> & nlist) { // Convert vector<int> n; ////////////////// // Check ranges for (int i=0; i<nlist.size(); i++) { if ( nlist[i] == -1 ) { if ( nlist[i-1] > nlist[i+1] ) { int tmp = nlist[i+1]; nlist[i+1] = nlist[i-1]; nlist[i-1] = tmp; } } } ////////////////// // Expand ranges for (int i=0; i<nlist.size(); i++) { if ( nlist[i]>0 ) { // Only add valid codes if ( nlist[i] <= maxcat ) n.push_back(nlist[i]); } else { int start = nlist[i-1]+1; int end = nlist[i+1]-1; if ( end > maxcat ) end = maxcat; for (int j=start; j<=end; j++) n.push_back(j); } } // Sort and uniquify stable_sort(n.begin(),n.end()); vector<int>::iterator ne = unique(n.begin(),n.end()); n.erase(ne, n.end()); // Shift to 0..N-1 coding for (int i=0; i<n.size(); i++) --n[i]; // Or is it a negative complement? if ( negmode ) { vector<bool> k(maxcat,false); for (int i=0; i<n.size(); i++) k[ n[i] ] = true; vector<int> n2 = n; n.clear(); for (int i=0; i<maxcat; i++) { if ( ! k[i] ) { n.push_back(i); } } } return n; }
int otsu(double* data_out, double** thr, double* sep, double* data, int xsize, int ysize, int N) { int _verbose=1; int LEVELS = 256; //double data_out[xsize * ysize]; // Unique int unI_size; double* unI; unique(xsize*ysize, data, &unI_size, &unI); if(_verbose>=1) { std::cout << std::endl << "unI_c = "; double_vector_print(unI_size, unI); } // Histogram int* counts; double* bins; int nbins; if (unI_size < LEVELS) nbins = unI_size; else nbins = LEVELS; if (nbins < LEVELS) { counts = new int[unI_size]; for (int i = 0; i < unI_size; i++) counts[i] = 0; bins = new double[unI_size]; for (int i = 0; i < unI_size; i++) bins[i] = unI[i]; } else if (nbins == LEVELS) { counts = new int[LEVELS]; for (int i = 0; i < LEVELS; i++) counts[i] = 0; bins = new double[LEVELS]; double step = (LEVELS - 1) / LEVELS / 2; bins[0] = step; for (int i = 1; i < LEVELS; i++) bins[i] = bins[i - 1] + step; } free(unI); histogram(counts, xsize*ysize, nbins, data, bins); // Display vector for matlab comparison if(_verbose) { std::cout << std::endl << "cBins = "; double_vector_print(nbins, bins); double_vector_save_to_file("cBins.txt", nbins, bins); std::cout << std::endl << "cHist = "; int_vector_print(nbins, counts); int_vector_save_to_file("cHist.txt", nbins, counts); } double* P=(double*)malloc(nbins*sizeof(*P)); for (int i = 0; i < nbins; i++) P[i] = (double) counts[i] / (xsize * ysize); // cumsum double* w=(double*)malloc(nbins*sizeof(*P)); double* mu=(double*)malloc(nbins*sizeof(*P)); double* Pi=(double*)malloc(nbins*sizeof(*P)); Pi[0] = P[0]; for (int i = 1; i < nbins; i++) Pi[i] = (i + 1) * P[i]; cumsum(w, P, nbins); cumsum(mu, Pi, nbins); if(_verbose) { double_vector_save_to_file("P.txt", nbins, P); double_vector_save_to_file("w.txt", nbins, w); double_vector_save_to_file("mu.txt", nbins, mu); } double* w_aux = NULL; double* mu_aux = NULL; double* aux1; double* aux2; double* sigma2B; double sigma2Bmax; int ind_sigma2Bmax; if (N == 2) { w_aux = new double[nbins - 2]; mu_aux = new double[nbins - 2]; aux1 = new double[nbins - 2]; aux2 = new double[nbins - 2]; sigma2B = new double[nbins - 2]; for (int i = 0; i < nbins - 2; i++) { w_aux[i] = w[i + 1]; mu_aux[i] = mu[i + 1]; aux1[i] = mu[nbins - 1] * w_aux[i] - mu_aux[i]; } if(_verbose) { std::cout << std::endl << "saving aux"<<std::endl; double_vector_save_to_file("aux1.txt", nbins - 2, aux1); //double_vector_save_to_file("aux2.txt", nbins - 2, aux2); } vector_pow(aux2, aux1, 2, nbins - 2); divide_vectors(aux1, aux2, w_aux, nbins - 2); for (int i = 0; i < nbins - 2; i++) aux2[i] = 1 - w_aux[i]; divide_vectors(sigma2B, aux1, aux2, nbins - 2); vector_max(&sigma2Bmax, &ind_sigma2Bmax, sigma2B, nbins - 2); if(_verbose) { double_vector_save_to_file("aux1b.txt", nbins - 2, aux1); double_vector_save_to_file("aux2b.txt", nbins - 2, aux2); double_vector_save_to_file("sigma2B.txt", nbins - 2, sigma2B); std::cout << "Maximo: " << sigma2Bmax << std::endl << "Posicion del maximo: " << ind_sigma2Bmax << std::endl; std::cout << "pixval: " << bins[ind_sigma2Bmax + 1] << std::endl; } for (int i = 0; i < xsize * ysize; i++) if (data[i] <= bins[ind_sigma2Bmax + 1]) data_out[i] = 0.0; else data_out[i] = 1.0; double* th_aux; th_aux = new double[1]; th_aux[0] = bins[ind_sigma2Bmax + 1]; *thr = th_aux; } else if (N == 3) { // w_aux = new double[nbins ]; // mu_aux = new double[nbins ]; aux1 = new double[nbins]; aux2 = new double[nbins]; sigma2B = new double[nbins * nbins]; double* w0= new double[nbins*nbins]; double* w1= new double[nbins*nbins]; double* w2= new double[nbins*nbins]; double* mu0_aux= new double[nbins]; double* mu2_aux= new double[nbins]; double* mu0= new double[nbins*nbins]; double* mu2= new double[nbins*nbins]; vector_flip(aux1, P, nbins); cumsum(aux2, aux1, nbins); vector_flip(aux1, aux2, nbins); for (int i = 0; i < nbins; i++) for (int j = 0; j < nbins; j++) { w0[i * nbins + j] = w[i]; w2[i * nbins + j] = aux1[j]; } double_vector_save_to_file("w0.txt", nbins*nbins, w0); double_vector_save_to_file("w2.txt", nbins*nbins, w2); divide_vectors(mu0_aux, mu, w, nbins); vector_flip(aux1, Pi, nbins); cumsum(aux2, aux1, nbins); double* aux3=new double[nbins]; vector_flip(aux3, P, nbins); cumsum(aux1, aux3, nbins); divide_vectors(aux3, aux2, aux1, nbins); vector_flip(mu2_aux, aux3, nbins); for (int i = 0; i < nbins; i++) for (int j = 0; j < nbins; j++) { mu0[i * nbins + j] = mu0_aux[i]; mu2[i * nbins + j] = mu2_aux[j]; } double_vector_save_to_file("mu0.txt", nbins*nbins, mu0); double_vector_save_to_file("mu2.txt", nbins*nbins, mu2); for (int i = 0; i < nbins * nbins; i++) { w1[i] = 1 - w0[i] - w2[i]; } double* aux4=new double[nbins * nbins]; double* aux5=new double[nbins * nbins]; double* t1=new double[nbins * nbins]; double* t2=new double[nbins * nbins]; double* t3=new double[nbins * nbins]; double* t4=new double[nbins * nbins]; double* t34=new double[nbins * nbins]; double* t34_aux=new double[nbins * nbins]; for (int i = 0; i < nbins * nbins; i++) aux4[i] = mu0[i] - mu[nbins - 1]; vector_pow(aux5, aux4, 2, nbins * nbins); multiplicate_vectors(t1, w0, aux5, nbins * nbins); multiplicate_vectors(t3, w0, aux4, nbins * nbins); for (int i = 0; i < nbins * nbins; i++) aux4[i] = mu2[i] - mu[nbins - 1]; vector_pow(aux5, aux4, 2, nbins * nbins); multiplicate_vectors(t2, w2, aux5, nbins * nbins); multiplicate_vectors(t4, w2, aux4, nbins * nbins); for (int i = 0; i < nbins * nbins; i++) t34[i] = t3[i] + t4[i]; vector_pow(t34_aux, t34, 2, nbins * nbins); divide_vectors(t34, t34_aux, w1, nbins * nbins); for (int i = 0; i < nbins * nbins; i++) { sigma2B[i] = t1[i] + t2[i] + t34[i]; if (w1[i] <= 0) sigma2B[i] = 0; } if(_verbose) { double_vector_save_to_file("sigma2B.txt", nbins*nbins, sigma2B); double_vector_save_to_file("sigma2B.txt", nbins*nbins, sigma2B); } vector_max(&sigma2Bmax, &ind_sigma2Bmax, sigma2B, nbins * nbins); std::cout << "Maximo: " << sigma2Bmax << std::endl << "Posicion del maximo: " << ind_sigma2Bmax << std::endl; int k1, k2; k1 = (int) ind_sigma2Bmax / nbins; k2 = ind_sigma2Bmax % nbins; std::cout << "k1 = " << k1 << ", k2 = " << k2 << std::endl; for (int i = 0; i < xsize * ysize; i++) if (data[i] <= bins[k1]) data_out[i] = 0.0; else if ((data[i] > bins[k1]) && (data[i] <= bins[k2])) data_out[i] = 0.5; else data_out[i] = 1.0; double* thr_aux; thr_aux = new double[2]; thr_aux[0] = bins[k1]; thr_aux[1] = bins[k2]; *thr = thr_aux; delete[] w0; delete[] w1; delete[] w2; delete[] mu0_aux; delete[] mu2_aux; delete[] mu0; delete[] mu2; delete[] aux3; delete[] aux4; delete[] aux5; delete[] t1; delete[] t2; delete[] t3; delete[] t4; delete[] t34; delete[] t34_aux; } double* sep_aux=new double[nbins]; double* sep_aux_2=new double[nbins]; for(int i=0;i<nbins;i++) sep_aux[i]=i+1-mu[nbins-1]; vector_pow(sep_aux_2, sep_aux, 2, nbins); multiplicate_vectors(sep_aux, sep_aux_2, P, nbins); double cumu=0; for (int i=0;i<nbins;i++) cumu+=sep_aux[i]; *sep=sigma2Bmax/cumu; //*Iseg = data_out; delete[] counts; delete[] aux1; delete[] aux2; delete[] bins; if (w_aux) delete[] w_aux; if (mu_aux) delete[] mu_aux; delete[] sigma2B; delete[] sep_aux; delete[] sep_aux_2; free(w); free(mu); free(Pi); return 0; }
ConsensusMap& ConsensusMap::operator+=(const ConsensusMap& rhs) { ConsensusMap empty_map; // reset these: RangeManagerType::operator=(empty_map); if (!this->getIdentifier().empty() || !rhs.getIdentifier().empty()) { LOG_INFO << "DocumentIdentifiers are lost during merge of ConsensusMaps\n"; } DocumentIdentifier::operator=(empty_map); UniqueIdInterface::operator=(empty_map); // append dataProcessing data_processing_.insert(data_processing_.end(), rhs.data_processing_.begin(), rhs.data_processing_.end()); // append fileDescription file_description_.insert(rhs.file_description_.begin(), rhs.file_description_.end()); // update filename and map size Map<UInt64, FileDescription>::const_iterator it = file_description_.begin(); Map<UInt64, FileDescription>::const_iterator it2 = rhs.file_description_.begin(); for (; it != file_description_.end() && it2 != rhs.file_description_.end(); ++it, ++it2) { getFileDescriptions()[it->first].filename = "mergedConsensusXMLFile"; getFileDescriptions()[it->first].size = it->second.size + it2->second.size; } // append proteinIdenficiation protein_identifications_.insert(protein_identifications_.end(), rhs.protein_identifications_.begin(), rhs.protein_identifications_.end()); // ensure non-redundant modification parameter for (std::vector<ProteinIdentification>::iterator it_1 = protein_identifications_.begin(); it_1 != protein_identifications_.end(); ++it_1) { std::vector<String>::iterator it_2; // remove redundant variable modifications std::vector<String>& varMod = const_cast<std::vector<String>&>(it_1->getSearchParameters().variable_modifications); sort(varMod.begin(), varMod.end()); it_2 = unique(varMod.begin(), varMod.end()); varMod.resize(it_2 - varMod.begin()); // remove redundant fixed modifications std::vector<String>& fixMod = const_cast<std::vector<String>&>(it_1->getSearchParameters().fixed_modifications); sort(fixMod.begin(), fixMod.end()); it_2 = unique(fixMod.begin(), fixMod.end()); fixMod.resize(it_2 - fixMod.begin()); } // append unassignedPeptideIdentifiactions unassigned_peptide_identifications_.insert(unassigned_peptide_identifications_.end(), rhs.unassigned_peptide_identifications_.begin(), rhs.unassigned_peptide_identifications_.end()); // append consensusElements to consensusElementList: this->insert(this->end(), rhs.begin(), rhs.end()); // todo: check for double entries // features, unassignedpeptides, proteins... // consistency try { UniqueIdIndexer<ConsensusMap>::updateUniqueIdToIndex(); } catch (Exception::Postcondition /*&e*/) // assign new UID's for conflicting entries { Size replaced_uids = UniqueIdIndexer<ConsensusMap>::resolveUniqueIdConflicts(); LOG_INFO << "Replaced " << replaced_uids << " invalid uniqueID's\n"; } return *this; }
void TdbDatabase::storePackage(const Package& p) { TdbKeyValue kv; // check if this package is already indexed kv.setKey(p.name() + "-version"); kv.setValue(tdb_fetch(m_tdbFile, kv.key())); if (kv.value_str() == p.version()) { kv.setKey(p.name() + "-release"); kv.setValue(tdb_fetch(m_tdbFile, kv.key())); if (kv.value_str() == p.release()) { return; } } // OK, we have something new int res = 0; kv.setKey(p.name() + "-version"); kv.setValue(p.version()); res = tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_MODIFY); if (res != 0 ) tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_INSERT); kv.setKey(p.name() + "-release"); kv.setValue(p.release()); res = tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_MODIFY); if (res != 0 ) tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_INSERT); kv.setKey(p.name() + "-architecture"); kv.setValue(p.architecture()); res = tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_MODIFY); if (res != 0 ) tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_INSERT); kv.setKey(p.name() + "-compression"); kv.setValue(p.compression()); res = tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_MODIFY); if (res != 0 ) tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_INSERT); string filesString; bool first = true; for (const auto& elem : p.files()) { TdbKeyValue fkv(elem, p.name()); const int ret = tdb_store(m_tdbFile, fkv.key(), fkv.value(), TDB_INSERT); if (ret != 0) { fkv.setValue(tdb_fetch(m_tdbFile, fkv.key())); vector<string> others; istringstream iss(fkv.value_str()); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(others)); others.push_back(p.name()); auto uIter = unique(others.begin(), others.end()); others.resize(uIter - others.begin()); string newValue; bool isthefirst = true; for (auto& other : others) { if (isthefirst) { isthefirst = false; } else { newValue += " "; } newValue += other; } fkv.setValue(newValue); tdb_store(m_tdbFile, fkv.key(), fkv.value(), TDB_MODIFY); } if (first) { filesString.append(elem); first = false; } else { filesString.append(" " + elem); } } kv.setKey(p.name() + "-files"); kv.setValue(filesString); res = tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_MODIFY); if (res != 0 ) tdb_store(m_tdbFile, kv.key(), kv.value(), TDB_INSERT); }
void SortUnique(Cont & c, Less && less, Equals && equals) { sort(c.begin(), c.end(), std::forward<Less>(less)); c.erase(unique(c.begin(), c.end(), std::forward<Equals>(equals)), c.end()); }
void BonusList::eliminateDuplicates() { sort( bonuses.begin(), bonuses.end() ); bonuses.erase( unique( bonuses.begin(), bonuses.end() ), bonuses.end() ); }
Win32CallstackResolver::Win32CallstackResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths, volatile bool *killSignal) { wstring configPath = StringFormat::UTF82Wide(FileIO::GetAppFolderFilename("config.ini")); { FILE *f = NULL; _wfopen_s(&f, configPath.c_str(), L"a"); if(f) fclose(f); } DWORD sz = 2048; wchar_t *inputBuf = new wchar_t[sz]; for(;;) { DWORD read = GetPrivateProfileStringW(L"renderdoc", L"ignores", NULL, inputBuf, sz, configPath.c_str()); if(read == sz - 1) { sz *= 2; delete[] inputBuf; inputBuf = new wchar_t[sz]; continue; } break; } wstring ignores = inputBuf; delete[] inputBuf; split(ignores, pdbIgnores, L';'); wstring widepdbsearch = StringFormat::UTF82Wide(pdbSearchPaths); split(widepdbsearch, pdbRememberedPaths, L';'); if(memcmp(moduleDB, "WN32CALL", 8)) { RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?"); return; } char *chunks = moduleDB + 8; char *end = chunks + DBSize - 8; EnumModChunk *chunk = (EnumModChunk *)(chunks); WCHAR *modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); // loop over all our modules for(; chunks < end; chunks += sizeof(EnumModChunk) + (chunk->imageNameLen) * sizeof(WCHAR)) { chunk = (EnumModChunk *)chunks; modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); if(killSignal && *killSignal) break; Module m; m.name = modName; m.base = chunk->base; m.size = chunk->size; m.moduleId = 0; if(find(pdbIgnores.begin(), pdbIgnores.end(), m.name) != pdbIgnores.end()) { RDCWARN("Not attempting to get symbols for %ls", m.name.c_str()); modules.push_back(m); continue; } // get default pdb (this also looks up symbol server etc) // Always done in unicode std::wstring defaultPdb = DIA2::LookupModule(modName, chunk->guid, chunk->age); // strip newline if(defaultPdb != L"" && defaultPdb[defaultPdb.length() - 1] == '\n') defaultPdb.pop_back(); // if we didn't even get a default pdb we'll have to prompt first time through bool failed = false; if(defaultPdb == L"") { defaultPdb = strlower(basename(m.name)); size_t it = defaultPdb.find(L".dll"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } it = defaultPdb.find(L".exe"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } failed = true; } std::wstring pdbName = defaultPdb; int fallbackIdx = -1; while(m.moduleId == 0) { if(failed) { fallbackIdx++; // try one of the folders we've been given, just in case the symbols // are there if(fallbackIdx < (int)pdbRememberedPaths.size()) { pdbName = pdbRememberedPaths[fallbackIdx] + L"\\" + basename(pdbName); } else { pdbName = dirname(defaultPdb) + L"\\" + basename(defaultPdb); // prompt for new pdbName, unless it's renderdoc or dbghelp if(pdbName.find(L"renderdoc.") != wstring::npos || pdbName.find(L"dbghelp.") != wstring::npos || pdbName.find(L"symsrv.") != wstring::npos) pdbName = L""; else pdbName = pdbBrowse(pdbName); // user cancelled, just don't load this pdb if(pdbName == L"") break; } failed = false; } m.moduleId = DIA2::GetModule(pdbName.c_str(), chunk->guid, chunk->age); if(m.moduleId == 0) { failed = true; } else { if(fallbackIdx >= (int)pdbRememberedPaths.size()) { wstring dir = dirname(pdbName); if(find(pdbRememberedPaths.begin(), pdbRememberedPaths.end(), dir) == pdbRememberedPaths.end()) { pdbRememberedPaths.push_back(dir); } } } } // didn't load the pdb? go to the next module. if(m.moduleId == 0) { modules.push_back(m); // still add the module, with 0 module id RDCWARN("Couldn't get symbols for %ls", m.name.c_str()); // silently ignore renderdoc.dll, dbghelp.dll, and symsrv.dll without asking to permanently // ignore if(m.name.find(L"renderdoc.") != wstring::npos || m.name.find(L"dbghelp.") != wstring::npos || m.name.find(L"symsrv.") != wstring::npos) continue; wchar_t text[1024]; wsprintf(text, L"Do you want to permanently ignore this file?\nPath: %ls", m.name.c_str()); int ret = MessageBoxW(NULL, text, L"Ignore this pdb?", MB_YESNO); if(ret == IDYES) pdbIgnores.push_back(m.name); continue; } DIA2::SetBaseAddress(m.moduleId, chunk->base); RDCLOG("Loaded Symbols for %ls", m.name.c_str()); modules.push_back(m); } sort(pdbIgnores.begin(), pdbIgnores.end()); pdbIgnores.erase(unique(pdbIgnores.begin(), pdbIgnores.end()), pdbIgnores.end()); merge(pdbIgnores, ignores, L';'); WritePrivateProfileStringW(L"renderdoc", L"ignores", ignores.c_str(), configPath.c_str()); }
void SortUnique(Cont & c) { sort(c.begin(), c.end()); c.erase(unique(c.begin(), c.end()), c.end()); }
void * client_list(void*arg) { //list win.create_flist(); while(1) { int max_y,max_x; getmaxyx(win.get_flist(),max_y,max_x); int i=0; sort(list.begin(),list.end()); vector<string>::iterator iter=unique(list.begin(),list.end()); list.erase(iter,list.end()); int total = list.size(); int page=max_y-3; int page_num=total/page; int page_mod =total%page; if(page_mod>0) { page_num+1; } strstream ss; string str_page_num; ss<<page_num; string _out_page; win.win_refresh(win.get_flist()); for(i=0;i< page_num;i++) { string str_i; strstream ssi; ssi<<i+1; ssi>>str_i; _out_page=str_i+"/"+str_page_num; win.clear_win_line(win.get_flist(),max_y-2,1); win.put_str_to_win(win.get_flist(),max_y-2,max_x/2,_out_page); int y=0; for(int j=0;j<page;++j) { y++; y=y%(max_y-3); int index =i*page+j; if(index<total) { string _fri=list[index]; if(y==0) { win.win_refresh(win.get_flist()); sleep(3); win.clear_win_line(win.get_flist(),1,max_y-4); continue; } win.put_str_to_win(win.get_flist(),y,2,_fri); }else { break; } } } win.win_refresh(win.get_flist()); usleep(10000); } }
int distributeCandies(vector<int>& candies) { int mx = candies.size() / 2; sort(candies.begin(), candies.end()); int diff = unique(candies.begin(), candies.end()) - candies.begin(); return min(mx, diff); }
vector<Page*>* QueryProcessor::process(int structure, string search) { bool is_not = false; int not_pos = 0; unsigned long length = 0; vector<Page*> hold; unordered_set<string>::const_iterator probe; istringstream searchStream(search); vector<string> tokens{istream_iterator<string>{searchStream}, istream_iterator<string>{}}; //Clear Results(reusable funct.) processedResults->clear(); rawResults->clear(); //Remove Stop Words for (int i = 0; i < tokens.size(); ++i) { probe = stopWords->find(tokens[i]); if(probe != stopWords->end()) { tokens.erase(tokens.begin()+i); } } //Checking for NOT, Lowercase, & Stem for (int i = 0; i < tokens.size(); ++i) { //cout << tokens[i] << endl; if (tokens[i] == "NOT") { is_not = true; not_pos = i; } transform(tokens[i].begin(), tokens[i].end(), tokens[i].begin(), ::tolower); Porter2Stemmer::stem(tokens[i]); } //Length of Search Terms if(is_not) { length = tokens.size() - (tokens.size()-not_pos) - 1; } else if (tokens.size() > 1) { length = tokens.size()-1; } else if (tokens.size() == 1) { length = 0; rawResults->push_back(index->getListOfPages(structure, tokens[0])); } //Length > 0, add to results for(int i = 0; i < length; ++i) { rawResults->push_back(index->getListOfPages(structure, tokens[i+1])); } //Single Search Term if(length == 0) { rawResults->push_back(index->getListOfPages(structure, tokens[0])); length = 1; } //AND... if( (tokens[0].compare("AND") == 0 || tokens[0].compare("and") == 0) && length >= 2 ) { size_t size = 0; vector<Page*> temp; set_intersection(rawResults->operator[](0).begin(), rawResults->operator[](0).end(), rawResults->operator[](1).begin(), rawResults->operator[](1).end(), back_inserter(temp)); if(length > 2) { for (int i = 2; i < length; ++i) { size = temp.size(); set_intersection(temp.begin(), temp.end(), rawResults->operator[](i).begin(), rawResults->operator[](i).end(), back_inserter(temp)); vector<Page*> vec(temp.begin()+size, temp.begin()+temp.size()); sort(temp.begin(), temp.end()); *processedResults = vec; } } else if(length == 2) { *processedResults = temp; } } //OR... else if(( tokens[0].compare("OR") == 0 || tokens[0].compare("or") == 0 ) && length >= 2) { vector<Page*> temp = rawResults->operator[](0); for (int i = 1; i < length; ++i) { temp = merge_copy(temp, rawResults->operator[](i)); sort( temp.begin(), temp.end() ); temp.erase( unique( temp.begin(), temp.end() ), temp.end() ); } *processedResults = temp; } //Single Term else { *processedResults = rawResults->operator[](0); } //NOT... if(is_not && tokens.size() >= 3) { size_t size = 0; int notLength = 0; vector<Page*> temp; for(int i = not_pos + 1; i < tokens.size(); ++i, ++notLength) { rawResults->push_back(index->getListOfPages(structure, tokens[i])); } set_difference(processedResults->begin(), processedResults->end(), rawResults->operator[](length).begin(), rawResults->operator[](length).end(), back_inserter(temp) ); if(notLength > 1) { for (int i = 1; i < notLength; ++i) { size = (size_t)temp.size(); set_difference(temp.begin(), temp.end(), rawResults->operator[](length+i).begin(), rawResults->operator[](length+i).end(), back_inserter(temp)); vector<Page*> vec(temp.begin()+size, temp.begin()+temp.size()); temp = vec; sort(temp.begin(), temp.end()); *processedResults = vec; } } else { *processedResults = temp; } } //Calculate Relevancy relevancy->clear(); relevancy->reserve(processedResults->size()); for(int i = 0; i < processedResults->size(); ++i) { int temp = 0; if(tokens[0] == "and" || tokens[0] == "or") { for (int j = 0; j < length ; ++j) { temp += processedResults->operator[](i)->getCount(tokens[j+1]); } } else { temp += processedResults->operator[](i)->getCount(tokens[0]); } relevancy->operator[](i) = temp; } //Sorting Results(relevancy) int pos_min,temp; Page* temp2; if (processedResults->size() > 1) { //Selection Sort: http://cforbeginners.com/ssort.html for (int i=0; i < processedResults->size()-1; i++) { pos_min = i;//set pos_min to the current index of array for (int j=i+1; j < processedResults->size(); j++) { if (relevancy->operator[](j) > relevancy->operator[](pos_min)) pos_min=j; //pos_min will keep track of the index that min is in, this is needed when a swap happens } //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur if (pos_min != i) { temp = relevancy->operator[](i); temp2 = processedResults->operator[](i); relevancy->operator[](i) = relevancy->operator[](pos_min); processedResults->operator[](i) = processedResults->operator[](pos_min); relevancy->operator[](pos_min) = temp; processedResults->operator[](pos_min) = temp2; } } } return processedResults; }
void Ui3Reader::createWrapperDeclContents(const QDomElement &e) { QString objClass = getClassName(e); if (objClass.isEmpty()) return; QDomNodeList nl; QString exportMacro; int i; QDomElement n; QStringList::ConstIterator it; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("exportmacro")); if (nl.length() == 1) exportMacro = nl.item(0).firstChild().toText().data(); QStringList::ConstIterator ns = namespaces.constBegin(); while (ns != namespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class "; if (!exportMacro.isEmpty()) out << exportMacro << ' '; out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << '{' << endl; /* qmake ignore Q_OBJECT */ out << " Q_OBJECT" << endl; out << endl; out << "public:" << endl; // constructor if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, bool modal = false, Qt::WindowFlags fl = 0);" << endl; } else if (objClass == QLatin1String("QWidget")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0);" << endl; } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = Qt::WType_TopLevel);" << endl; isMainWindow = true; } else { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0);" << endl; } // destructor out << " ~" << bareNameOfClass << "();" << endl; out << endl; // database connections dbConnections = unique(dbConnections); bool hadOutput = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty()) { // only need pointers to non-default connections if ((*it) != QLatin1String("(default)") && !(*it).isEmpty()) { out << indent << "QSqlDatabase* " << *it << "Connection;" << endl; hadOutput = true; } } } if (hadOutput) out << endl; QStringList publicSlots, protectedSlots, privateSlots; QStringList publicSlotTypes, protectedSlotTypes, privateSlotTypes; QStringList publicSlotSpecifier, protectedSlotSpecifier, privateSlotSpecifier; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("slots") && n.parentNode().toElement().tagName() != QLatin1String("connections")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1Char(';'))) functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String(QLatin1String("protected"))) { protectedSlots += functionName; protectedSlotTypes += returnType; protectedSlotSpecifier += specifier; } else if (access == QLatin1String("private")) { privateSlots += functionName; privateSlotTypes += returnType; privateSlotSpecifier += specifier; } else { publicSlots += functionName; publicSlotTypes += returnType; publicSlotSpecifier += specifier; } } QStringList publicFuncts, protectedFuncts, privateFuncts; QStringList publicFunctRetTyp, protectedFunctRetTyp, privateFunctRetTyp; QStringList publicFunctSpec, protectedFunctSpec, privateFunctSpec; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("functions")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1Char(';'))) functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String("protected")) { protectedFuncts += functionName; protectedFunctRetTyp += returnType; protectedFunctSpec += specifier; } else if (access == QLatin1String("private")) { privateFuncts += functionName; privateFunctRetTyp += returnType; privateFunctSpec += specifier; } else { publicFuncts += functionName; publicFunctRetTyp += returnType; publicFunctSpec += specifier; } } QStringList publicVars, protectedVars, privateVars; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("variable")); for (i = 0; i < (int)nl.length(); i++) { n = nl.item(i).toElement(); // Because of compatibility the next lines have to be commented out. // Someday it should be uncommented. //if (n.parentNode().toElement().tagName() != QLatin1String("variables")) // continue; QString access = n.attribute(QLatin1String("access"), QLatin1String("protected")); QString var = fixDeclaration(n.firstChild().toText().data().trimmed()); if (!var.endsWith(QLatin1Char(';'))) var += QLatin1Char(';'); if (access == QLatin1String("public")) publicVars += var; else if (access == QLatin1String("private")) privateVars += var; else protectedVars += var; } if (!publicVars.isEmpty()) { for (it = publicVars.constBegin(); it != publicVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!publicFuncts.isEmpty()) writeFunctionsDecl(publicFuncts, publicFunctRetTyp, publicFunctSpec); if (!publicSlots.isEmpty()) { out << "public slots:" << endl; if (!publicSlots.isEmpty()) writeFunctionsDecl(publicSlots, publicSlotTypes, publicSlotSpecifier); } // find signals QStringList extraSignals; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("signal")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("signals") && n.parentNode().toElement().tagName() != QLatin1String("connections")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString sigName = n.firstChild().toText().data().trimmed(); if (sigName.endsWith(QLatin1Char(';'))) sigName = sigName.left(sigName.length() - 1); extraSignals += fixDeclaration(sigName); } // create signals if (!extraSignals.isEmpty()) { out << "signals:" << endl; for (it = extraSignals.constBegin(); it != extraSignals.constEnd(); ++it) out << " void " << (*it) << ';' << endl; out << endl; } if (!protectedVars.isEmpty()) { out << "protected:" << endl; for (it = protectedVars.constBegin(); it != protectedVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!protectedFuncts.isEmpty()) { if (protectedVars.isEmpty()) out << "protected:" << endl; writeFunctionsDecl(protectedFuncts, protectedFunctRetTyp, protectedFunctSpec); } out << "protected slots:" << endl; out << " virtual void languageChange();" << endl; if (!protectedSlots.isEmpty()) { out << endl; writeFunctionsDecl(protectedSlots, protectedSlotTypes, protectedSlotSpecifier); } out << endl; // create all private stuff if (!privateFuncts.isEmpty() || !privateVars.isEmpty()) { out << "private:" << endl; if (!privateVars.isEmpty()) { for (it = privateVars.constBegin(); it != privateVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!privateFuncts.isEmpty()) writeFunctionsDecl(privateFuncts, privateFunctRetTyp, privateFunctSpec); } if (!privateSlots.isEmpty()) { out << "private slots:" << endl; writeFunctionsDecl(privateSlots, privateSlotTypes, privateSlotSpecifier); } out << "};" << endl; for (i = 0; i < (int) namespaces.count(); i++) out << '}' << endl; out << endl; }
void TriMesh2D::compute_edges() { std::vector<EdgeWithTris> edges_temp; for(unsigned int f = 0; f < tris.size(); ++f) { //compute edges EdgeWithTris e0(tris[f][0], tris[f][1], f); EdgeWithTris e1(tris[f][1], tris[f][2], f); EdgeWithTris e2(tris[f][2], tris[f][0], f); //ensure consistency, by sorting indices if(e0.edge[1]<e0.edge[0]) swap(e0.edge[1],e0.edge[0]); if(e1.edge[1]<e1.edge[0]) swap(e1.edge[1],e1.edge[0]); if(e2.edge[1]<e2.edge[0]) swap(e2.edge[1],e2.edge[0]); //add them edges_temp.push_back(e0); edges_temp.push_back(e1); edges_temp.push_back(e2); } sort(edges_temp.begin(), edges_temp.end(), ewt_cmp); //go through pairs, and copy tri info over. unsigned int pos = 0; while(pos < edges_temp.size()-1) { if(edges_temp[pos].edge == edges_temp[pos+1].edge) { //determine the triangle pair Vec2i tri(edges_temp[pos].tris[0], edges_temp[pos+1].tris[0]); //copy into both edges_temp[pos].tris = tri; edges_temp[pos+1].tris = tri; ++pos; //can skip ahead one more, since we've handled this pair. } ++pos; } edges_temp.erase( unique( edges_temp.begin(), edges_temp.end() ), edges_temp.end() ); //we should now have a collection of winged edges, in some sorted order //copy the edges into the edge list... edges.resize(edges_temp.size()); for(unsigned int i = 0; i < edges_temp.size(); ++i) { edges[i] = edges_temp[i].edge; } //now, construct the tri_to_edge_map tri_to_edge_map.resize(tris.size()); std::vector<int> tri_edges_so_far(tris.size(), 0); for(unsigned int i = 0; i < edges_temp.size(); ++i) { EdgeWithTris cur = edges_temp[i]; int tri0 = cur.tris[0]; tri_to_edge_map[tri0][ tri_edges_so_far[tri0] ] = i; ++tri_edges_so_far[tri0]; int tri1 = cur.tris[1]; if(tri1 != -1) { //if there is a second tri bordering this edge... tri_to_edge_map[tri1][ tri_edges_so_far[tri1] ] = i; ++tri_edges_so_far[tri1]; } } for(unsigned int i = 0; i < tri_to_edge_map.size(); ++i) { //reorder the edges in the map... the code apparently depends on the //fact that the ordering of the edges lines up with the ordering of the vertices Vec3ui new_order; Vec2ui e0(tris[i][0], tris[i][1]); if(e0[0] > e0[1]) swap(e0[0],e0[1]); new_order[0] = (e0 == edges[tri_to_edge_map[i][0]]? tri_to_edge_map[i][0] : (e0 == edges[tri_to_edge_map[i][1]]? tri_to_edge_map[i][1] : tri_to_edge_map[i][2]) ); Vec2ui e1(tris[i][1], tris[i][2]); if(e1[0] > e1[1]) swap(e1[0],e1[1]); new_order[1] = (e1 == edges[tri_to_edge_map[i][0]]? tri_to_edge_map[i][0] : (e1 == edges[tri_to_edge_map[i][1]]? tri_to_edge_map[i][1] : tri_to_edge_map[i][2]) ); Vec2ui e2(tris[i][2], tris[i][0]); if(e2[0] > e2[1]) swap(e2[0],e2[1]); new_order[2] = (e2 == edges[tri_to_edge_map[i][0]]? tri_to_edge_map[i][0] : (e2 == edges[tri_to_edge_map[i][1]]? tri_to_edge_map[i][1] : tri_to_edge_map[i][2]) ); tri_to_edge_map[i] = new_order; } //compute midpoints and normals for(unsigned int e = 0; e < edges.size(); ++e) { Vec2f v0 = vertices[edges[e][0]]; Vec2f v1 = vertices[edges[e][1]]; Vec2f edge_vec = v1-v0; Vec2f normal = perp(edge_vec); float length = mag(edge_vec); edge_lengths.push_back(length); normal /= length; edge_normals.push_back(normal); edge_midpoints.push_back(0.5f*(v0+v1)); } }
/*! Creates an implementation (cpp-file) for the form given in \a e. \sa createFormDecl(), createObjectImpl() */ void Ui3Reader::createFormImpl(const QDomElement &e) { QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); // generate local and local includes required QStringList globalIncludes, localIncludes; QStringList::Iterator it; QMap<QString, CustomInclude> customWidgetIncludes; // find additional slots and functions QStringList extraFuncts; QStringList extraFunctTyp; QStringList extraFunctSpecifier; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("slots") && n.parentNode().toElement().tagName() != QLatin1String("connections")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1Char(';'))) functionName.chop(1); extraFuncts += functionName; extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void")); extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual")); } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("functions")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1Char(';'))) functionName.chop(1); extraFuncts += functionName; extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void")); extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual")); } // additional includes (local or global) and forward declaractions nl = e.parentNode().toElement().elementsByTagName(QLatin1String("include")); for (i = 0; i < (int) nl.length(); i++) { QDomElement n2 = nl.item(i).toElement(); QString s = n2.firstChild().toText().data(); if (n2.attribute(QLatin1String("location")) != QLatin1String("local")) { if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s)) continue; if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation")) continue; globalIncludes += s; } } registerDatabases(e); dbConnections = unique(dbConnections); bool dbForm = false; if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.begin(); it != dbConnections.end(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // do the local includes afterwards, since global includes have priority on clashes for (i = 0; i < (int) nl.length(); i++) { QDomElement n2 = nl.item(i).toElement(); QString s = n2.firstChild().toText().data(); if (n2.attribute(QLatin1String("location")) == QLatin1String("local") && !globalIncludes.contains(s)) { if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s)) continue; if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation")) continue; localIncludes += s; } } // additional custom widget headers nl = e.parentNode().toElement().elementsByTagName(QLatin1String("header")); for (i = 0; i < (int) nl.length(); i++) { QDomElement n2 = nl.item(i).toElement(); QString s = n2.firstChild().toText().data(); if (n2.attribute(QLatin1String("location")) != QLatin1String("local")) globalIncludes += s; else localIncludes += s; } out << "#include <qvariant.h>" << endl; // first for gcc 2.7.2 globalIncludes = unique(globalIncludes); for (it = globalIncludes.begin(); it != globalIncludes.end(); ++it) { if (!(*it).isEmpty()) out << "#include <" << fixHeaderName(*it) << '>' << endl; } if (externPixmaps) { out << "#include <qimage.h>" << endl; out << "#include <qpixmap.h>" << endl << endl; } /* Put local includes after all global includes */ localIncludes = unique(localIncludes); for (it = localIncludes.begin(); it != localIncludes.end(); ++it) { if (!(*it).isEmpty() && *it != QFileInfo(fileName + QLatin1String(".h")).fileName()) out << "#include \"" << fixHeaderName(*it) << '\"' << endl; } QString uiDotH = fileName + QLatin1String(".h"); if (QFile::exists(uiDotH)) { if (!outputFileName.isEmpty()) uiDotH = QString::fromUtf8(combinePath(uiDotH.ascii(), outputFileName.ascii())); out << "#include \"" << uiDotH << '\"' << endl; writeFunctImpl = false; } // register the object and unify its name objName = registerObject(objName); if (externPixmaps) { pixmapLoaderFunction = QLatin1String("QPixmap::fromMimeSource"); } // constructor if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) { out << "/*" << endl; out << " * Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl; out << " * name 'name' and widget flags set to 'f'." << endl; out << " *" << endl; out << " * The " << objClass.mid(1).toLower() << " will by default be modeless, unless you set 'modal' to" << endl; out << " * true to construct a modal " << objClass.mid(1).toLower() << '.' << endl; out << " */" << endl; out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)" << endl; out << " : " << objClass << "(parent, name, modal, fl)"; } else if (objClass == QLatin1String("QWidget")) { out << "/*" << endl; out << " * Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl; out << " * name 'name' and widget flags set to 'f'." << endl; out << " */" << endl; out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl; out << " : " << objClass << "(parent, name, fl)"; } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) { out << "/*" << endl; out << " * Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl; out << " * name 'name' and widget flags set to 'f'." << endl; out << " *" << endl; out << " */" << endl; out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl; out << " : " << objClass << "(parent, name, fl)"; isMainWindow = true; } else { out << "/*" << endl; out << " * Constructs a " << nameOfClass << " which is a child of 'parent', with the" << endl; out << " * name 'name'.' " << endl; out << " */" << endl; out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name)" << endl; out << " : " << objClass << "(parent, name)"; } out << endl; out << '{' << endl; // // setup the gui // out << indent << "setupUi(this);" << endl << endl; if (isMainWindow) out << indent << "(void)statusBar();" << endl; // database support dbConnections = unique(dbConnections); if (dbConnections.count()) out << endl; for (it = dbConnections.begin(); it != dbConnections.end(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { out << indent << (*it) << "Connection = QSqlDatabase::database(\"" <<(*it) << "\");" << endl; } } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("widget")); for (i = 1; i < (int) nl.length(); i++) { // start at 1, 0 is the toplevel widget n = nl.item(i).toElement(); QString s = getClassName(n); if ((dbForm || subDbForms) && (s == QLatin1String("QDataBrowser") || s == QLatin1String("QDataView"))) { QString objName = getObjectName(n); QString tab = getDatabaseInfo(n, QLatin1String("table")); QString con = getDatabaseInfo(n, QLatin1String("connection")); out << indent << "QSqlForm* " << objName << "Form = new QSqlForm(this);" << endl; out << indent << objName << "Form->setObjectName(\"" << objName << "Form\");" << endl; QDomElement n2; for (n2 = n.firstChild().toElement(); !n2.isNull(); n2 = n2.nextSibling().toElement()) createFormImpl(n2, objName, con, tab); out << indent << objName << "->setForm(" << objName << "Form);" << endl; } } if (extraFuncts.contains(QLatin1String("init()"))) out << indent << "init();" << endl; // end of constructor out << '}' << endl; out << endl; // destructor out << "/*" << endl; out << " * Destroys the object and frees any allocated resources" << endl; out << " */" << endl; out << nameOfClass << "::~" << bareNameOfClass << "()" << endl; out << '{' << endl; if (extraFuncts.contains(QLatin1String("destroy()"))) out << indent << "destroy();" << endl; out << indent << "// no need to delete child widgets, Qt does it all for us" << endl; out << '}' << endl; out << endl; // handle application events if required bool needFontEventHandler = false; bool needSqlTableEventHandler = false; bool needSqlDataBrowserEventHandler = false; nl = e.elementsByTagName(QLatin1String("widget")); for (i = 0; i < (int) nl.length(); i++) { if (!DomTool::propertiesOfType(nl.item(i).toElement() , QLatin1String("font")).isEmpty()) needFontEventHandler = true; QString s = getClassName(nl.item(i).toElement()); if (s == QLatin1String("QDataTable") || s == QLatin1String("QDataBrowser")) { if (!isFrameworkCodeGenerated(nl.item(i).toElement())) continue; if (s == QLatin1String("QDataTable")) needSqlTableEventHandler = true; if (s == QLatin1String("QDataBrowser")) needSqlDataBrowserEventHandler = true; } if (needFontEventHandler && needSqlTableEventHandler && needSqlDataBrowserEventHandler) break; } out << "/*" << endl; out << " * Sets the strings of the subwidgets using the current" << endl; out << " * language." << endl; out << " */" << endl; out << "void " << nameOfClass << "::languageChange()" << endl; out << '{' << endl; out << " retranslateUi(this);" << endl; out << '}' << endl; out << endl; // create stubs for additional slots if necessary if (!extraFuncts.isEmpty() && writeFunctImpl) { it = extraFuncts.begin(); QStringList::Iterator it2 = extraFunctTyp.begin(); QStringList::Iterator it3 = extraFunctSpecifier.begin(); while (it != extraFuncts.end()) { QString type = fixDeclaration(*it2); if (type.isEmpty()) type = QLatin1String("void"); type = type.simplified(); QString fname = fixDeclaration(Parser::cleanArgs(*it)); if (!(*it3).startsWith(QLatin1String("pure"))) { // "pure virtual" or "pureVirtual" out << type << ' ' << nameOfClass << "::" << fname << endl; out << '{' << endl; if (*it != QLatin1String("init()") && *it != QLatin1String("destroy()")) { QRegExp numeric(QLatin1String("^(?:signed|unsigned|u?char|u?short|u?int" "|u?long|Q_U?INT(?:8|16|32)|Q_U?LONG|float" "|double)$")); QString retVal; /* We return some kind of dummy value to shut the compiler up. 1. If the type is 'void', we return nothing. 2. If the type is 'bool', we return 'false'. 3. If the type is 'unsigned long' or 'quint16' or 'double' or similar, we return '0'. 4. If the type is 'Foo *', we return '0'. 5. If the type is 'Foo &', we create a static variable of type 'Foo' and return it. 6. If the type is 'Foo', we assume there's a default constructor and use it. */ if (type != QLatin1String("void")) { QStringList toks = type.split(QLatin1String(" ")); bool isBasicNumericType = (toks.filter(numeric).count() == toks.count()); if (type == QLatin1String("bool")) { retVal = QLatin1String("false"); } else if (isBasicNumericType || type.endsWith(QLatin1Char('*'))) { retVal = QLatin1String("0"); } else if (type.endsWith(QLatin1Char('&'))) { do { type.chop(1); } while (type.endsWith(QLatin1Char(' '))); retVal = QLatin1String("uic_temp_var"); out << indent << "static " << type << ' ' << retVal << ';' << endl; } else { retVal = type + QLatin1String("()"); } } out << indent << "qWarning(\"" << nameOfClass << "::" << fname << ": Not implemented yet\");" << endl; if (!retVal.isEmpty()) out << indent << "return " << retVal << ';' << endl; } out << '}' << endl; out << endl; } ++it; ++it2; ++it3; } } }
inline void BoW::create_universal_gmm(int N_cent, const string path_run_folders) { cout << "Calculating Universal GMM " << endl; cout << "# clusters: " << N_cent << endl; mat uni_features; for (uword pe=0; pe<peo_train.n_rows; ++pe) { mat mat_features_tmp; mat mat_features; for (uword act = 0 ; act < actions.n_rows; ++act) { for (uword sc = 1 ; sc <= 4; ++sc) { mat mat_features_video_i; std::stringstream ssName_feat_video; //ssName_feat_video << "./run"<< run <<"/features/train/feat_vec" << peo_train(pe) << "_" << actions(act) << "_d" << sc; ssName_feat_video << path_run_folders <<"/features_all_nor/feat_vec_" << peo_train(pe) << "_" << actions(act) << "_d" << sc; mat_features_video_i.load( ssName_feat_video.str() ); if ( mat_features_video_i.n_cols>0 ) { mat_features_tmp = join_rows( mat_features_tmp, mat_features_video_i ); } else { cout << "# vectors = 0 in " << ssName_feat_video.str() << endl; } } } cout << "mat_features_tmp.n_cols "<< mat_features_tmp.n_cols << endl; const uword N_max = 100000*4; // 4 sc. maximum number of vectors per action to create universal GMM //const uword N_max = 100000; //??? if (mat_features_tmp.n_cols > N_max) { ivec tmp1 = randi( N_max, distr_param(0,mat_features_tmp.n_cols-1) ); ivec tmp2 = unique(tmp1); uvec my_indices = conv_to<uvec>::from(tmp2); mat_features = mat_features_tmp.cols(my_indices); // extract a subset of the columns } else { mat_features = mat_features_tmp; } cout << "mat_features.n_cols "<< mat_features.n_cols << endl; if ( mat_features.n_cols>0 ) { uni_features = join_rows( uni_features, mat_features ); } else { cout << "# vectors = 0 in uni_features" << endl; } //uni_features = join_rows( uni_features, mat_features ); mat_features_tmp.reset(); mat_features.reset(); } cout << "r&c "<< uni_features.n_rows << " & " << uni_features.n_cols << endl; bool is_finite = uni_features.is_finite(); if (!is_finite ) { cout << "is_finite?? " << is_finite << endl; cout << uni_features.n_rows << " " << uni_features.n_cols << endl; getchar(); } cout << "universal GMM" << endl; gmm_diag gmm_model; gmm_diag bg_model; bool status_em = false; int rep_em=0; int km_iter = 10; double var_floor = 1e-10; bool print_mode = true; bool status_kmeans = false; int rep_km = 0; while (!status_kmeans) { arma_rng::set_seed_random(); status_kmeans = gmm_model.learn(uni_features, N_cent, eucl_dist, random_subset, km_iter, 0, var_floor, print_mode); //Only Kmeans bg_model = gmm_model; rep_km++; } cout <<"K-means was repeated " << rep_km << endl; means = gmm_model.means; //Saving statistics std::stringstream ss_means; ss_means << "./run"<< run <<"/visual_vocabulary/means_Ng" << N_cent << "_dim" <<dim << "_all_sc" << ".dat"; means.save( ss_means.str(), raw_ascii ); }
ScriptObject* TypeDescriber::describeTraits(Traitsp traits, uint32_t flags) { if (!(flags & INCLUDE_TRAITS)) return NULL; AvmCore* core = m_toplevel->core(); GC* gc = core->GetGC(); TraitsBindingsp tb = traits->getTraitsBindings(); TraitsMetadatap tm = traits->getTraitsMetadata(); ScriptObject* o = new_object(); ArrayObject* bases = NULL; ArrayObject* metadata = NULL; ArrayObject* interfaces = NULL; ArrayObject* methods = NULL; ArrayObject* accessors = NULL; ArrayObject* variables = NULL; ScriptObject* constructor = NULL; if (flags & INCLUDE_BASES) { metadata = new_array(); PoolObject* class_mdpool; const uint8_t* class_md = tm->getMetadataPos(class_mdpool); if (class_md) addDescribeMetadata(metadata, class_mdpool, class_md); } if (flags & INCLUDE_BASES) { bases = new_array(); for (Traitsp b = traits->base; b; b = b->base) pushstr(bases, describeClassName(b)); } if (flags & INCLUDE_INTERFACES) { interfaces = new_array(); // our TraitsBindings only includes our own interfaces, not any we might have inherited, // so walk the tree. there might be redundant interfaces listed in the inheritance, // so use a list to remove dupes List<Traitsp> unique(gc); for (Traitsp b = traits; b; b = b->base) { TraitsBindingsp tbi = b->getTraitsBindings(); for (uint32_t i = 0; i < tbi->interfaceCapacity; ++i) { Traitsp ti = tbi->getInterface(i); if (ti && ti->isInterface && unique.indexOf(ti) < 0) { unique.add(ti); pushstr(interfaces, describeClassName(ti)); } } } } // constructor if (flags & INCLUDE_CONSTRUCTOR) { AbstractFunction* initMethod = traits->init; if (initMethod && initMethod->param_count) { constructor = describeParams(initMethod); } } if (flags & (INCLUDE_ACCESSORS | INCLUDE_METHODS | INCLUDE_VARIABLES)) { // recover slot/method metadata and method-declarer information. // make a flattened set of bindings so we don't have to check for overrides as we go. // This is not terribly efficient, but doesn't need to be. MultinameHashtable* mybind = new (gc) MultinameHashtable(); addBindings(mybind, tb, flags); // Don't want interface methods, so post-process and wipe out any // bindings that were added for (uint32_t i = 0; i < tb->interfaceCapacity; ++i) { Traitsp ti = tb->getInterface(i); if (ti && ti->isInterface) { TraitsBindingsp tbi = ti->getTraitsBindings(); for (int32_t index = 0; (index = tbi->next(index)) != 0; ) { Stringp name = tbi->keyAt(index); Namespacep ns = tbi->nsAt(index); mybind->add(name, ns, BIND_NONE); } } } // yuck, replicate buggy behavior in FP9/10 List<Namespacep> nsremoval(gc); if (flags & HIDE_NSURI_METHODS) { for (uint32_t i = 0; i < tb->interfaceCapacity; ++i) { Traitsp ti = tb->getInterface(i); // already did interfaces, don't need to do them again if (ti && !ti->isInterface) { TraitsBindingsp tbi = ti->getTraitsBindings(); for (int32_t index = 0; (index = tbi->next(index)) != 0; ) { Namespacep ns = tbi->nsAt(index); if (ns->getURI()->length() > 0 && nsremoval.indexOf(ns) < 0) nsremoval.add(ns); } } } } for (int32_t index = 0; (index = mybind->next(index)) != 0; ) { Binding binding = mybind->valueAt(index); Stringp name = mybind->keyAt(index); Namespacep ns = mybind->nsAt(index); Stringp nsuri = ns->getURI(); TraitsMetadata::MetadataPtr md1 = NULL; TraitsMetadata::MetadataPtr md2 = NULL; PoolObject* md1pool = NULL; PoolObject* md2pool = NULL; // We only display public members -- exposing private namespaces could compromise security. if (ns->getType() != Namespace::NS_Public) continue; if ((flags & HIDE_NSURI_METHODS) && nsremoval.indexOf(ns) >= 0) continue; ScriptObject* v = new_object(); const BindingKind bk = AvmCore::bindingKind(binding); switch (bk) { case BKIND_CONST: case BKIND_VAR: { if (!(flags & INCLUDE_VARIABLES)) continue; const uint32_t slotID = AvmCore::bindingToSlotId(binding); const KVPair props[] = { { kstrid_access, strAtom(str(bk == BKIND_CONST ? kstrid_readonly : kstrid_readwrite)) }, { kstrid_type, strAtom(describeClassName(tb->getSlotTraits(slotID))) }, }; setpropmulti(v, props, elem_count(props)); if (!variables) variables = new_array(); pushobj(variables, v); md1 = tm->getSlotMetadataPos(slotID, md1pool); break; } case BKIND_METHOD: { if (!(flags & INCLUDE_METHODS)) continue; const uint32_t methodID = AvmCore::bindingToMethodId(binding); const AbstractFunction* af = tb->getMethod(methodID); Traitsp declaringTraits = af->declaringTraits; const KVPair props[] = { { kstrid_declaredBy, strAtom(describeClassName(declaringTraits)) }, { kstrid_returnType, strAtom(describeClassName(af->returnTraits())) }, { kstrid_parameters, objAtom(describeParams(af)) }, }; setpropmulti(v, props, elem_count(props)); if (!methods) methods = new_array(); pushobj(methods, v); md1 = tm->getMethodMetadataPos(methodID, md1pool); break; } case BKIND_GET: case BKIND_SET: case BKIND_GETSET: { if (!(flags & INCLUDE_ACCESSORS)) continue; const uint32_t methodID = AvmCore::hasGetterBinding(binding) ? AvmCore::bindingToGetterId(binding) : AvmCore::bindingToSetterId(binding); const AbstractFunction* af = tb->getMethod(methodID); Traitsp declaringTraits = af->declaringTraits; Traitsp accessorType = AvmCore::hasGetterBinding(binding) ? af->returnTraits() : af->paramTraits(1); static const uint8_t bk2str[8] = { uint8_t(kstrid_emptyString), // BKIND_NONE uint8_t(kstrid_emptyString), // BKIND_METHOD uint8_t(kstrid_emptyString), // BKIND_VAR uint8_t(kstrid_emptyString), // BKIND_CONST uint8_t(kstrid_emptyString), // BKIND_ITRAMP uint8_t(kstrid_readonly), // BKIND_GET uint8_t(kstrid_writeonly), // BKIND_SET uint8_t(kstrid_readwrite) // BKIND_GETSET }; const KVPair props[] = { { kstrid_declaredBy, strAtom(describeClassName(declaringTraits)) }, { kstrid_access, strAtom(str(StringId(bk2str[bk]))) }, { kstrid_type, strAtom(describeClassName(accessorType)) }, }; setpropmulti(v, props, elem_count(props)); if (AvmCore::hasGetterBinding(binding)) md1 = tm->getMethodMetadataPos(AvmCore::bindingToGetterId(binding), md1pool); if (AvmCore::hasSetterBinding(binding)) md2 = tm->getMethodMetadataPos(AvmCore::bindingToSetterId(binding), md2pool); if (!accessors) accessors = new_array(); pushobj(accessors, v); break; } case BKIND_NONE: break; } ArrayObject* vm = NULL; if ((flags & INCLUDE_METADATA) && (md1 || md2)) { vm = new_array(); addDescribeMetadata(vm, md1pool, md1); addDescribeMetadata(vm, md2pool, md2); } const KVPair props[] = { { kstrid_name, strAtom(name) }, { kstrid_uri, strAtom(nsuri->length() == 0 ? NULL : nsuri) }, { kstrid_metadata, objAtom(vm) }, }; setpropmulti(v, props, elem_count(props)); } } const KVPair props[] = { { kstrid_bases, objAtom(bases) }, { kstrid_interfaces, objAtom(interfaces) }, { kstrid_metadata, objAtom(metadata) }, { kstrid_accessors, objAtom(accessors) }, { kstrid_methods, objAtom(methods) }, { kstrid_variables, objAtom(variables) }, { kstrid_constructor, objAtom(constructor) }, }; setpropmulti(o, props, elem_count(props)); return o; }
QString ResourceLocator::rename(const QString& src, const QString& new_base, const QSet<QString>& lst) { QFileInfo fi(src), fi2(new_base); return unique(fi.path() + "/" + fi2.fileName(), lst); }
vector<int> xs; sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());
void extractEuclideanClusters ( PointCloud<PointXYZRGB >::Ptr cloud, pcl::PointCloud<pcl::Normal >::Ptr normals, pcl::search::KdTree<PointXYZRGB >::Ptr tree, float tolerance, std::vector<pcl::PointIndices > &clusters, double eps_angle, unsigned int min_pts_per_cluster = 1, unsigned int max_pts_per_cluster = (std::numeric_limits<int >::max) ()) { // \note If the tree was created over <cloud, indices>, we guarantee a 1-1 mapping between what the tree returns //and indices[i] float adjTolerance = 0; // Create a bool vector of processed point indices, and initialize it to false std::vector<bool > processed(cloud->points.size(), false); std::vector<int> nn_indices; std::vector<float> nn_distances; // Process all points in the indices vector std::cout << "Point size is " << cloud->points.size () << std::endl; for (size_t i = 0; i < cloud->points.size (); ++i) { if(processed[i]) continue; std::vector<int > seed_queue; int sq_idx = 0; seed_queue.push_back(i); processed[i] = true; int cnt = 0; while (sq_idx < (int)seed_queue.size()) { cnt++; // Search for sq_idx // adjTolerance = cloud->points[seed_queue[sq_idx]].distance * tolerance; adjTolerance = tolerance; if (!tree->radiusSearch(seed_queue[sq_idx], adjTolerance, nn_indices, nn_distances)) { sq_idx++; continue; } for(size_t j = 1; j < nn_indices.size (); ++j) // nn_indices[0] should be sq_idx { if (processed[nn_indices[j]]) // Has this point been processed before ? continue; processed[nn_indices[j]] = true; // [-1;1] double dot_p = normals->points[i].normal[0] * normals->points[nn_indices[j]].normal[0] + normals->points[i].normal[1] * normals->points[nn_indices[j]].normal[1] + normals->points[i].normal[2] * normals->points[nn_indices[j]].normal[2]; if ( fabs (acos (dot_p)) < eps_angle ) { processed[nn_indices[j]] = true; seed_queue.push_back (nn_indices[j]); } } sq_idx++; } // If this queue is satisfactory, add to the clusters if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster) { pcl::PointIndices r; r.indices.resize (seed_queue.size ()); for (size_t j = 0; j < seed_queue.size (); ++j) r.indices[j] = seed_queue[j]; sort (r.indices.begin (), r.indices.end ()); r.indices.erase (unique (r.indices.begin (), r.indices.end ()), r.indices.end ()); r.header = cloud->header; //ROS_INFO ("cluster of size %d data point\n ",r.indices.size()); clusters.push_back(r); } } }
void knockout_shadow_junctions(JunctionSet& junctions) { vector<uint32_t> ref_ids; for (JunctionSet::iterator i = junctions.begin(); i != junctions.end(); ++i) { ref_ids.push_back(i->first.refid); } sort(ref_ids.begin(), ref_ids.end()); vector<uint32_t>::iterator new_end = unique(ref_ids.begin(), ref_ids.end()); ref_ids.erase(new_end, ref_ids.end()); for(size_t i = 0; i < ref_ids.size(); ++i) { uint32_t refid = ref_ids[i]; Junction dummy_left(refid, 0, 0, true); Junction dummy_right(refid, 0xFFFFFFFF, 0xFFFFFFFF, true); pair<JunctionSet::iterator, JunctionSet::iterator> r; r.first = junctions.lower_bound(dummy_left); r.second = junctions.upper_bound(dummy_right); JunctionSet::iterator itr = r.first; while(itr != r.second && itr != junctions.end()) { if (itr->second.accepted) { Junction fuzzy_left = itr->first; Junction fuzzy_right = itr->first; fuzzy_left.left -= min_anchor_len; fuzzy_right.right += min_anchor_len; fuzzy_left.antisense = !itr->first.antisense; fuzzy_right.antisense = !itr->first.antisense; pair<JunctionSet::iterator, JunctionSet::iterator> s; s.first = junctions.lower_bound(fuzzy_left); s.second = junctions.upper_bound(fuzzy_right); JunctionSet::iterator itr2 = s.first; int junc_support = itr->second.supporting_hits; while(itr2 != s.second && itr2 != junctions.end()) { int left_diff = itr->first.left - itr2->first.left; int right_diff = itr->first.right - itr2->first.right; if (itr != itr2 && itr->first.antisense != itr2->first.antisense && (left_diff < min_anchor_len || right_diff < min_anchor_len)) { if (junc_support < itr2->second.supporting_hits) itr->second.accepted = false; } ++itr2; } } ++itr; } } }
ostream& operator<< (ostream &os_o, const BaseObject &obj) { shared_ptr<BaseObject> cur; shared_ptr<BaseObject> to_check; bool cur_turn = ~obj.cur_op[BaseObject::OP_DISPLAY]; vector<shared_ptr<BaseObject>> to_print; #define ADD_Q(x) if ((x)->cur_op[BaseObject::OP_DISPLAY] != cur_turn){ (x)->cur_op[BaseObject::OP_DISPLAY] = cur_turn; to_print.push_back(x); } cur = obj.my_lock; ADD_Q (cur); do { cur = to_print.front(); to_print.erase (to_print.begin()); cur->cur_op[BaseObject::OP_DISPLAY] = cur_turn; os_o << endl << cur->name << " x(" << cur->position.x << ") y(" << cur->position.y << ") z(" << cur->position.z << ")"; os_o << endl << "\tsubitem : " << cur->here->size(); if (to_check = cur->up) { os_o << endl << "\tup : " << to_check->name; ADD_Q (to_check); } if (to_check = cur->down) { os_o << endl << "\tdown : " << to_check->name; ADD_Q (to_check); } if (to_check = cur->left) { os_o << endl << "\tleft : " << to_check->name; ADD_Q (to_check); } if (to_check = cur->right) { os_o << endl << "\tright : " << to_check->name; ADD_Q (to_check); } if (to_check = cur->front) { os_o << endl << "\tfront : " << to_check->name; ADD_Q (to_check); } if (to_check = cur->back) { os_o << endl << "\tback : " << to_check->name; ADD_Q (to_check); } sort (to_print.begin(), to_print.end()); to_print.erase (unique (to_print.begin(), to_print.end()), to_print.end()); } while (!to_print.empty()); #undef ADD_Q return os_o; }
/// Removes the duplicates from a vector of strings /// /// Takes a std::vector of std::string and removes /// any duplicates from it in place /// /// @param[in,out] strs A std::vector of std::string void MathildaUtils::unique_string_vector(vector<std::string> &strs) { sort(strs.begin(), strs.end()); strs.erase(unique(strs.begin(), strs.end()), strs.end()); }
void BaseObject::insert (BaseObject *obj) { if (obj == NULL) return; vector<BaseObject *> to_add; shared_ptr<BaseObject> to_recalc; BaseObject *cur; to_add.push_back (obj); do { cur = to_add.back(); to_add.pop_back(); if (to_recalc = cur->up) { to_recalc->down.reset(); to_add.push_back (to_recalc->my_lock.get()); } if (to_recalc = cur->down) { to_recalc->up.reset(); to_add.push_back (to_recalc->my_lock.get()); } if (to_recalc = cur->front) { to_recalc->back.reset(); to_add.push_back (to_recalc->my_lock.get()); } if (to_recalc = cur->back) { to_recalc->front.reset(); to_add.push_back (to_recalc->my_lock.get()); } if (to_recalc = cur->left) { to_recalc->right.reset(); to_add.push_back (to_recalc->my_lock.get()); } if (to_recalc = cur->right) { to_recalc->left.reset(); to_add.push_back (to_recalc->my_lock.get()); } insertOne (cur); sort (to_add.begin(), to_add.end()); to_add.erase (unique (to_add.begin(), to_add.end()), to_add.end()); } while (!to_add.empty()); }
const vector<string>& Subtypes::getCreatureValuesById() { sort(subtypesCreature.begin(),subtypesCreature.end()); subtypesCreature.erase(unique(subtypesCreature.begin(),subtypesCreature.end()),subtypesCreature.end()); return subtypesCreature; }
/*! Creates a declaration (header file) for the form given in \a e \sa createFormImpl() */ void Ui3Reader::createFormDecl(const QDomElement &e) { QDomElement body = e; QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); QStringList typeDefs; QMap<QString, CustomInclude> customWidgetIncludes; /* We are generating a few QImage members that are not strictly necessary in some cases. Ideally, we would use requiredImage, which is computed elsewhere, to keep the generated .h and .cpp files synchronized. */ // at first the images QMap<QString, int> customWidgets; QStringList forwardDecl; QStringList forwardDecl2; for (n = e; !n.isNull(); n = n.nextSibling().toElement()) { if (n.tagName().toLower() == QLatin1String("customwidgets")) { QDomElement n2 = n.firstChild().toElement(); while (!n2.isNull()) { if (n2.tagName().toLower() == QLatin1String("customwidget")) { QDomElement n3 = n2.firstChild().toElement(); QString cl; while (!n3.isNull()) { QString tagName = n3.tagName().toLower(); if (tagName == QLatin1String("class")) { cl = n3.firstChild().toText().data(); if (m_options & CustomWidgetForwardDeclarations) forwardDecl << cl; customWidgets.insert(cl, 0); } else if (tagName == QLatin1String("header")) { CustomInclude ci; ci.header = n3.firstChild().toText().data(); ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global")); if (!ci.header.isEmpty()) forwardDecl.removeAll(cl); customWidgetIncludes.insert(cl, ci); } n3 = n3.nextSibling().toElement(); } } n2 = n2.nextSibling().toElement(); } } } // register the object and unify its name objName = registerObject(objName); QString protector = objName.toUpper() + QLatin1String("_H"); protector.replace(QLatin1String("::"), QLatin1String("_")); out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers QStringList globalIncludes, localIncludes; { QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass); if (it != customWidgetIncludes.end()) { if ((*it).location == QLatin1String("global")) globalIncludes += (*it).header; else localIncludes += (*it).header; } } QStringList::ConstIterator it; globalIncludes = unique(globalIncludes); for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include <" << header << '>' << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include \"" << header << '\"' << endl; } } out << endl; bool dbForm = false; registerDatabases(e); dbConnections = unique(dbConnections); if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // some typedefs, maybe typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) out << "typedef " << *it << ';' << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); for (i = 0; i < (int) nl.length(); i++) forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data()); forwardDecl = unique(forwardDecl); for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != objClass) { QString forwardName = *it; QStringList forwardNamespaces = forwardName.split(QLatin1String("::")); forwardName = forwardNamespaces.last(); forwardNamespaces.removeAt(forwardNamespaces.size()-1); QStringList::ConstIterator ns = forwardNamespaces.constBegin(); while (ns != forwardNamespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class " << forwardName << ';' << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) out << '}' << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); if (!fd.endsWith(QLatin1Char(';'))) fd += QLatin1Char(';'); out << fd << endl; } out << endl; Driver d; d.option().headerProtection = false; d.option().copyrightHeader = false; d.option().extractImages = m_extractImages; d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0; d.option().qrcOutputFile = m_qrcOutputFile; d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0; if (trmacro.size()) d.option().translateFunction = trmacro; DomUI *ui = generateUi4(e); d.uic(fileName, ui, &out); delete ui; createWrapperDeclContents(e); out << "#endif // " << protector << endl; }
/** * Push a new (unique) empty layer (where multiple definitions can be stored) * on top of an existing environment. * @param lenv the old environment * @return the new environment */ static Tree pushNewLayer(Tree lenv) { return tree(unique("ENV_LAYER"), lenv); }
/*Rotate *accessor that returns suggestions */ vector<int> Cluster::Rotate(vector<int> L, vector<int> S, int C, int num_results) { /*might have to make C a list if we are subclustering */ vector<int> id_list; int current_cluster = C % cluster_map.size(); sort(S.begin(), S.end() ); sort(L.begin(), L.end() ); vector<int> Scopy; if(! S.empty()) { //see cluster.h - toggle true for random results, default false if (! RANDOM) { Scopy = S; vector<int>::iterator u = unique(Scopy.begin(), Scopy.end()); Scopy.resize( u - Scopy.begin() ); } } //S print cout <<"Items Seen:"; for(vector<int>::iterator it = Scopy.begin(); it != Scopy.end(); ++it) { cout << *it << ", "; } cout <<endl; while( id_list.size() < num_results) { int result; //keep looping - if no results in cluster, we'll switch to another //and calculate similarity there while ( (result = _calc_Next(L, Scopy, current_cluster, lambda)) == 0 ) { current_cluster = (current_cluster + 1) % cluster_map.size(); } if (! binary_search(Scopy.begin(), Scopy.end(), result) ) { /* *To retrieve random results, *we erase the "memory" of previously seen items *inorder for them to be randomly generated. */ if(! RANDOM) { Scopy.push_back(result); } sort(Scopy.begin(), Scopy.end()); id_list.push_back( result ); sort(id_list.begin(), id_list.end()); cout << "doc: " << result <<endl; vector<int>::iterator u = unique(Scopy.begin(), Scopy.end()); Scopy.resize( u - Scopy.begin() ); } current_cluster = (current_cluster + 1) % cluster_map.size(); } return id_list; }