Пример #1
0
bool LoaderIDE::load(const std::string &filename, const PedStatsList &stats) {
    std::ifstream str(filename);

    if (!str.is_open()) return false;

    auto find_stat_id = [&](const std::string &name) {
        auto it =
            std::find_if(stats.begin(), stats.end(),
                         [&](const PedStats &a) { return a.name_ == name; });
        if (it == stats.end()) {
            return -1;
        }
        return it->id_;
    };

    SectionTypes section = NONE;
    while (!str.eof()) {
        std::string line;
        getline(str, line);
        line.erase(std::find_if(line.rbegin(), line.rend(),
                                std::not1(std::ptr_fun<int, int>(std::isspace)))
                       .base(),
                   line.end());

        if (!line.empty() && line[0] == '#') continue;

        if (line == "end") {
            section = NONE;
        } else if (section == NONE) {
            if (line == "objs") {
                section = OBJS;
            } else if (line == "tobj") {
                section = TOBJ;
            } else if (line == "peds") {
                section = PEDS;
            } else if (line == "cars") {
                section = CARS;
            } else if (line == "hier") {
                section = HIER;
            } else if (line == "2dfx") {
                section = TWODFX;
            } else if (line == "path") {
                section = PATH;
            }
        } else {
            // Remove ALL the whitespace!!
            line.erase(remove_if(line.begin(), line.end(), isspace),
                       line.end());

            std::stringstream strstream(line);
            std::string buff;

            switch (section) {
                default:
                    break;
                case OBJS:
                case TOBJ: {  // Supports Type 1, 2 and 3
                    auto objs =
                        std::unique_ptr<SimpleModelInfo>(new SimpleModelInfo);

                    getline(strstream, buff, ',');
                    objs->setModelID(atoi(buff.c_str()));

                    getline(strstream, objs->name, ',');
                    getline(strstream, objs->textureslot, ',');

                    getline(strstream, buff, ',');
                    objs->setNumAtomics(atoi(buff.c_str()));

                    for (int i = 0; i < objs->getNumAtomics(); i++) {
                        getline(strstream, buff, ',');
                        objs->setLodDistance(i, atof(buff.c_str()));
                    }

                    objs->determineFurthest();

                    getline(strstream, buff, ',');
                    objs->flags = atoi(buff.c_str());

                    // Keep reading TOBJ data
                    if (section == LoaderIDE::TOBJ) {
                        getline(strstream, buff, ',');
                        objs->timeOn = atoi(buff.c_str());
                        getline(strstream, buff, ',');
                        objs->timeOff = atoi(buff.c_str());
                    } else {
                        objs->timeOn = 0;
                        objs->timeOff = 24;
                    }

                    objects.emplace(objs->id(), std::move(objs));
                    break;
                }
                case CARS: {
                    auto cars =
                        std::unique_ptr<VehicleModelInfo>(new VehicleModelInfo);

                    getline(strstream, buff, ',');
                    cars->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, cars->name, ',');
                    getline(strstream, cars->textureslot, ',');

                    getline(strstream, buff, ',');
                    cars->vehicletype_ =
                        VehicleModelInfo::findVehicleType(buff);

                    getline(strstream, cars->handling_, ',');
                    getline(strstream, cars->vehiclename_, ',');
                    getline(strstream, buff, ',');
                    cars->vehicleclass_ =
                        VehicleModelInfo::findVehicleClass(buff);

                    getline(strstream, buff, ',');
                    cars->frequency_ = std::atoi(buff.c_str());

                    getline(strstream, buff, ',');
                    cars->level_ = std::atoi(buff.c_str());

                    getline(strstream, buff, ',');
                    cars->componentrules_ = std::atoi(buff.c_str());

                    switch (cars->vehicletype_) {
                        case VehicleModelInfo::CAR:
                            getline(strstream, buff, ',');
                            cars->wheelmodel_ = std::atoi(buff.c_str());
                            getline(strstream, buff, ',');
                            cars->wheelscale_ = std::atof(buff.c_str());
                            break;
                        case VehicleModelInfo::PLANE:
                            /// @todo load LOD
                            getline(strstream, buff, ',');
                            // cars->planeLOD_ = std::atoi(buff.c_str());
                            break;
                        default:
                            break;
                    }

                    objects.emplace(cars->id(), std::move(cars));
                    break;
                }
                case PEDS: {
                    auto peds = std::unique_ptr<PedModelInfo>(new PedModelInfo);

                    getline(strstream, buff, ',');
                    peds->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, peds->name, ',');
                    getline(strstream, peds->textureslot, ',');

                    getline(strstream, buff, ',');
                    peds->pedtype_ = PedModelInfo::findPedType(buff);

                    std::string behaviour;
                    getline(strstream, behaviour, ',');
                    peds->statindex_ = find_stat_id(behaviour);
                    getline(strstream, peds->animgroup_, ',');

                    getline(strstream, buff, ',');
                    peds->carsmask_ = std::atoi(buff.c_str());

                    objects.emplace(peds->id(), std::move(peds));
                    break;
                }
                case PATH: {
                    PathData path;

                    std::string type;
                    getline(strstream, type, ',');
                    if (type == "ped") {
                        path.type = PathData::PATH_PED;
                    } else if (type == "car") {
                        path.type = PathData::PATH_CAR;
                    }

                    std::string id;
                    getline(strstream, id, ',');
                    path.ID = atoi(id.c_str());

                    getline(strstream, path.modelName);

                    std::string linebuff, buff;
                    for (size_t p = 0; p < 12; ++p) {
                        PathNode node;

                        getline(str, linebuff);
                        std::stringstream buffstream(linebuff);

                        getline(buffstream, buff, ',');
                        switch (atoi(buff.c_str())) {
                            case 0:
                                node.type = PathNode::EMPTY;
                                break;
                            case 2:
                                node.type = PathNode::INTERNAL;
                                break;
                            case 1:
                                node.type = PathNode::EXTERNAL;
                                break;
                        }

                        if (node.type == PathNode::EMPTY) {
                            continue;
                        }

                        getline(buffstream, buff, ',');
                        node.next = atoi(buff.c_str());

                        getline(buffstream, buff, ',');  // "Always 0"

                        getline(buffstream, buff, ',');
                        node.position.x = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.position.y = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.position.z = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.size = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.other_thing = atoi(buff.c_str());

                        getline(buffstream, buff, ',');
                        node.other_thing2 = atoi(buff.c_str());

                        path.nodes.push_back(node);
                    }

                    auto &object = objects[path.ID];
                    auto simple = dynamic_cast<SimpleModelInfo *>(object.get());
                    simple->paths.push_back(path);

                    break;
                }
                case HIER: {
                    auto hier =
                        std::unique_ptr<ClumpModelInfo>(new ClumpModelInfo);

                    getline(strstream, buff, ',');
                    hier->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, hier->name, ',');
                    getline(strstream, hier->textureslot, ',');

                    objects.emplace(hier->id(), std::move(hier));
                    break;
                }
            }
        }
    }

    return true;
}
Пример #2
0
template<> string sinsp_fdinfo_t::tostring_clean()
{
	string m_tstr = m_name;
	m_tstr.erase(remove_if(m_tstr.begin(), m_tstr.end(), g_invalidchar()), m_tstr.end());
	return m_tstr;
}
Пример #3
0
void Job::run(){
    if (Print)
        cout << endl << "------ new run ------ iRip==" << iRip << endl << endl;  
    //
    int iTr=0,iTs=0,iVar,iV,iFRip, 
        i,ii,
        trsz=ds.pr->TrSzD, tssz=ds.pr->TsSzD, valdim=ds.LabelValSelSize; 
    double acc[trsz][tssz][FRip], mse[trsz][tssz][FRip], scc[trsz][tssz][FRip],
           featNum[FeatSelSize][FRip],
           *res,trends[valdim][trsz][FRip],actualLabel[valdim],ValidTrend[valdim]; 
    matvar_t *varnameC;
    //
    for (iVar=0; iVar<LabelSelSize; ++iVar){ 
        iV=LabelSelIdx[iVar]; // questa e` la variabile che vogliamo decodificare
        // -------------- cambio il nome del file in modo da coincidere con la variabile --------------------------------------
        string resFile_=resFile,VARNAME;            // cosi` lo scope e` locale in questo ciclo
        varnameC = Mat_VarGetCell(VARIABLEs,iV);    // recupero il nome di questa variabile
        VARNAME=(const char*)varnameC->data;        
        // segnalo dove sono a video
        if (Print)
            cout << endl << "------ iV=" << VARNAME << endl << endl;  
        // 
        resFile_+=VARNAME; resFile_+="-";           // riporto quale variabile sto esaminando nel filename
        resFile_+="nF_"; resFile_+=to_string(FeatSelSize); resFile_+="-"; // e quante features
        resFile_+="res.mat";    // aggiungo l'estensione 
        // elimino gli spazi
        resFile_.erase(remove_if(resFile_.begin(), 
                                 resFile_.end(),
                                 [](char x){return isspace(x);}),
                       resFile_.end());                              
        // --------------------------------------------------------------------------------------------------------------------
        //
        // ----------------------------  recupero l'andamento della label sul validation set ----------------------------------
        for (ii=0; ii<valdim; ++ii){
            i=ds.label_valid_selection[ii];
            actualLabel[ii]=labels[LabelSize[0]*iV+i]; // prendo l'i-esimo indice del del validation set della variabile iV
                                                       // LabelSize[0] e` il numero totale delle istanze
        }
        // ---------------------------------------------------------------------------------------------------------------------  
        //
        for (iTr=0; iTr<trsz; ++iTr){
            ds.assegnoTrainingSet(iTr);  
            for (iFRip=0; iFRip<FRip; ++iFRip){
                if (Print)
                    cout << endl << "------ iTr%=" << (double)iTr/trsz     
                         << endl << "------ iFRip%=" << (double)iFRip/FRip 
                         << endl << endl;  
                UpdateFeatureSelection(); // cambio, se devo, la selezione delle features
        //
        // -----------------------------------------  recupero gli indici delle features ---------------------------------------
                for (i=0; i<FeatSelSize; ++i) // recupero gli indici delle feature che ho usato
                    featNum[i][iFRip]=(double)(feature_sel[i]+1); // per metterla nel ws di matio
                                                                  // aggiungo 1.0 per come funziona l'indicizzazione su matlab
        // ---------------------------------------------------------------------------------------------------------------------  
        //
// per debug
if (0){
    cout << endl << "feat idx" << endl; 
    for (int i=0; i<FeatSelSize; ++i)
        cout << " " << feature_sel[i];
    cout << endl;    
}
                assegnato_svm=false; // devo riaddestrare per ogni Training Set o per ogni sottocampionamento delle features  
                TrainingFromAssignedProblem(iV); // addestro con lo stesso Training Set ma (forse) diverse Features
                predictValidationSet(ValidTrend,iV); // Test sul Validation Set

                // ------------------------------- recupero i trends sul Validation Set -----------------------------------------
                for (ii=0; ii<valdim; ++ii)
                    trends[ii][iTr][iFRip]=ValidTrend[ii]; 
                // --------------------------------------------------------------------------------------------------------------
                //
                for (iTs=0; iTs<tssz; ++iTs){
                    ds.assegnoTestSet(iTs);
                    predictTestSet(iV); 
                    // recupero le performance del modello
                    res = (double *)((matvar_t *)RES[1])->data; 
                    acc[iTr][iTs][iFRip]=res[0];
                    mse[iTr][iTs][iFRip]=res[1];
                    scc[iTr][iTs][iFRip]=res[2];
                }
            }
        }
        // -------------- salvo un file per ogni variabile | setto il workspace da salvare --------------------------------------
        int WsSize=12; 
        matvar_t *workspace[WsSize]; 
        size_t dims_3[3], dims_2[2], dims_1[1]; 
        dims_3[2]=trsz; dims_3[1]=tssz; dims_3[0]=FRip; 
        dims_2[1]=FeatSelSize; dims_2[0]=FRip;
        dims_1[0]=1;
        workspace[0] = Mat_VarCreate("acc",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,acc,0);
        workspace[1] = Mat_VarCreate("mse",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,mse,0);
        workspace[2] = Mat_VarCreate("scc",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,scc,0);
        workspace[3] = Mat_VarCreate("featIdx",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims_2,featNum,0);
        dims_2[1]=valdim; dims_2[0]=1;
        workspace[4] = Mat_VarCreate("actualLabel",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims_2,actualLabel,0);
        dims_3[2]=valdim; dims_3[1]=trsz; dims_3[0]=FRip; 
        workspace[5] = Mat_VarCreate("trends",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,trends,0);
        double FRip_ws[1], trsz_ws[1], tssz_ws[1], FeatSelSize_ws[1], validSz_ws[1]; 
        FRip_ws[0]=FRip; trsz_ws[0]=trsz; tssz_ws[0]=tssz; FeatSelSize_ws[0]=FeatSelSize; validSz_ws[0]=valdim; 
        workspace[6] = Mat_VarCreate("FeatSelectionRip",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,FRip_ws,0);
        workspace[7] = Mat_VarCreate("NumFeatures",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,FeatSelSize_ws,0);
        workspace[8] = Mat_VarCreate("TrSz",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,trsz_ws,0);
        workspace[9] = Mat_VarCreate("TsSz",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,tssz_ws,0);
        workspace[10] = Mat_VarCreate("ValidationSetSize",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,validSz_ws,0);
        string help ="CONTENUTO DEL MATFILE:\n";
               help+="{acc,mse,scc}\n";
               help+="\tdimensione RxTsxTr\n";
               help+="\t(accuratezza,mean squared error ed r2\n\toutput di libsvm)\n";
 
               help+="featIdx\n";
               help+="\tdimensione RxN\n";
               help+="\t(indice delle features usate per addestrare\n\t il modello ad ogni ricampionamento)\n";
              

               help+="actualLabel\n";
               help+="\tdimensione 1xV\n";
               help+="\t(valore della label corrispondente al validation set\n\tNB: salvo un file diverso per ogni label)\n";

               help+="trends\n";
               help+="\tdimensione RxTrxV\n";
               help+="\t(predizione della label, ne ho una diverso per ogni modello\n\tNB: ho un modello diverso per ogni\n\t +ricampionamento delle features\n\t +ricampionamento del training set)\n";

               help+="***LEGENDA***\n";
               help+="\tR=FeatSelectionRip\n";
               help+="\tTs=TsSz\n";
               help+="\tTr=TrSz\n";
               help+="\tN=NumFeatures\n";
               help+="\tV=ValidationSetSize\n";
        dims_2[1]=help.size(); dims_2[0]=1;
        workspace[11] = Mat_VarCreate("README",MAT_C_CHAR,MAT_T_UINT8,2,dims_2,(char*)help.c_str(),0);

        // Apro scrivo e chiudo il matfile
        mat_t *Out_MATFILE = Mat_CreateVer((const char*)resFile_.c_str(),NULL,MAT_FT_DEFAULT);	
        for (int iWS=0; iWS<WsSize; ++iWS)
            Mat_VarWrite(Out_MATFILE, workspace[iWS], MAT_COMPRESSION_NONE);
        Mat_Close(Out_MATFILE);
        // ----------------------------------------------------------------------------------------------------------------------
    }

    return; 
}	
Пример #4
0
void CUtil::SemanticFormat(string &statement)
{
    size_t idx;
    string left;
    string right;
    string eq = "==", ne = "!=", eqT = "==1", eqF = "==0", concat_op = "&&";

    int eq_len = eq.length();
    int ne_len = ne.length();
    int eq_pos = -1, ne_pos = -1;
    int tnum_len = string("1").length();
    int tstr_len = string("true").length();
    int fnum_len = string("0").length();
    int fstr_len = string("false").length();

    statement.erase(remove_if(statement.begin(), statement.end(), ::isspace), statement.end());

    // For loop handling: Currently "for" keyword is searched and upon encounter, is stripped from the statement
    // and the rest of the statement is recorded as a condition. We need to record specific condition within a
    // for loop, not the entire statement.
    if(statement.find(";", 0) != string::npos) {
    	int firstSC = statement.find(";", 0);
    	if(statement.find(";", firstSC + 1) != string::npos) {
    		int secondSC = statement.find(";", firstSC + 1);
    		if(firstSC != secondSC + 1) {
    			string condFOR = statement.substr(firstSC + 1, secondSC - firstSC - 1);
    			//distinct_cond_set.erase(it);
    			//it = distinct_cond_set.find(temp);
    			statement = condFOR;
    			//distinct_cond_set.insert(condFOR);
    		}
    	}
    }

    if(statement.find("concat_op") == string::npos){

        if(statement[0]=='!'){
            eq_pos = statement.find(eq);
            ne_pos = statement.find(ne);
            if(eq_pos != string::npos) {
                if(statement.substr(eq_pos + eq_len, tnum_len) == "1" || statement.substr(eq_pos + eq_len, tstr_len) == "true") {
                    statement = statement.substr(1, string::npos) += eqF;
                } else if(statement.substr(eq_pos + eq_len, fnum_len) == "0" || statement.substr(eq_pos + eq_len, fstr_len) == "false") {
                    statement = statement.substr(1, string::npos) += eqT;
                }
            } else if(ne_pos != string::npos) {
                if(statement.substr(ne_pos + ne_len, tnum_len) == "1" || statement.substr(ne_pos + ne_len, tstr_len) == "true") {
                    statement = statement.substr(1, string::npos) += eqT;
                } else if(statement.substr(ne_pos + ne_len, fnum_len) == "0" || statement.substr(ne_pos + ne_len, fstr_len) == "false") {
                    statement = statement.substr(1, string::npos) += eqF;
                }
            } else {
                statement = statement.substr(1, string::npos) += eqF;
            }
            return;
        }

        if (statement.find(eq) == string::npos && statement.find(ne) == string::npos){
            statement = statement + eqT;
            return ;
        }

        idx = statement.find(eq);
        if (idx != string::npos){

            left = statement.substr(0, idx);
            right = statement.substr(idx + eq_len, string::npos);

            if(left=="true" || left=="1") {
                statement = right + eqT;
            } else if(right=="true" || right=="1") {
                statement = left + eqT;
            }
            if(left=="false" || left=="0") {
                statement = right + eqF;
            } else if(right=="false" || right=="0"){
                statement = left + eqF;
            }
            return;
        }

        idx = statement.find(ne);
        if (idx != string::npos){

            left = statement.substr(0, idx);
            right = statement.substr(idx + ne_len, string::npos);

            if(left=="true" || left=="1") {
                statement = right + eqF;
            } else if (right=="true" || right=="1") {
                statement = left + eqF;
            }
            if(left=="false" || left=="0") {
                statement = right + eqT;
            } else if (right=="false" || right=="0"){
                statement = left + eqT;
            }
            return;
        }

    }else{

        string temp_statement = statement;
        statement = "";
        while(temp_statement.find(concat_op) != string::npos){
            idx = temp_statement.find(concat_op);
            left = temp_statement.substr(0, idx);
            right = temp_statement.substr(idx + concat_op.length(), string::npos);
            SemanticFormat(left);
            statement= statement + left + concat_op;
            temp_statement = temp_statement.substr(idx + concat_op.length(), string::npos);
        }
        statement = statement + right;
        cout << "get a && statement: "<< statement<<endl;
        return;
    }
}
Пример #5
0
void Allele::add(
        string& addToStart,
        string& addToEnd,
        vector<pair<int, string> >& cigarStart,
        vector<pair<int, string> >& cigarEnd,
        vector<short>& qaddToStart,
        vector<short>& qaddToEnd
    ) {

    // adjust the position
    for (vector<pair<int, string> >::iterator c = cigarStart.begin(); c != cigarStart.end(); ++c) {
        switch (c->second[0]) {
            case 'M':
            case 'X':
            case 'D':
            case 'N':
                position -= c->first;
                break;
            case 'I':
            default:
                break;
        }
    }

    // prepare to adjust cigar
    vector<pair<int, string> > cigarV = splitCigar(cigar);

    // adjust the cigar
    if (!cigarStart.empty()) {
        if (cigarStart.back().second == cigarV.front().second) {
            // merge
            cigarV.front().first += cigarStart.back().first;
            cigarStart.pop_back();
        }
    }
    cigarV.insert(cigarV.begin(), cigarStart.begin(), cigarStart.end());

    if (!cigarEnd.empty()) {
        if (cigarEnd.front().second == cigarV.back().second) {
            // merge
            cigarV.back().first += cigarEnd.front().first;
            cigarEnd.pop_back();
        } else {
            cigarV.insert(cigarV.end(), cigarEnd.begin(), cigarEnd.end());
        }
    }

    // adjust the alternateSequence
    alternateSequence.insert(0, addToStart);
    alternateSequence.append(addToEnd);

    // adjust the quality string
    baseQualities.insert(baseQualities.begin(), qaddToStart.begin(), qaddToStart.end());
    baseQualities.insert(baseQualities.end(), qaddToEnd.begin(), qaddToEnd.end());

    // reset the cigar
    cigarV.erase(remove_if(cigarV.begin(), cigarV.end(), isEmptyCigarElement), cigarV.end());
    cigar = joinCigar(cigarV);

    updateTypeAndLengthFromCigar();

    // reset referenceLength
    referenceLength = referenceLengthFromCigar();

}
Пример #6
0
void CDirectoryHistory::ClearSearchHistory()
{
  m_vecPathHistory.erase(remove_if(m_vecPathHistory.begin(), m_vecPathHistory.end(), IsMusicSearchUrl), m_vecPathHistory.end());
}
Пример #7
0
C Filter(C const & container, P pred) {
  C filtered(container);
  filtered.erase(remove_if(filtered.begin(), filtered.end(), pred), filtered.end());
  return filtered;
}
Пример #8
0
void DataflowAnalyzer::analyze(const CFG &cfg) {
    /*
     * Returns true if the given term does not cover given memory location.
     */
    auto notCovered = [this](const MemoryLocation &mloc, const Term *term) -> bool {
        return !dataflow().getMemoryLocation(term).covers(mloc);
    };

    /* Mapping of a basic block to the definitions reaching its end. */
    boost::unordered_map<const BasicBlock *, ReachingDefinitions> outDefinitions;

    /*
     * Running abstract interpretation until reaching a fixpoint several times in a row.
     */
    int niterations = 0;
    int nfixpoints = 0;

    while (nfixpoints++ < 3) {
        /*
         * Run abstract interpretation on all basic blocks.
         */
        foreach (auto basicBlock, cfg.basicBlocks()) {
            ReachingDefinitions definitions;

            /* Merge reaching definitions from predecessors. */
            foreach (const BasicBlock *predecessor, cfg.getPredecessors(basicBlock)) {
                definitions.merge(outDefinitions[predecessor]);
            }

            /* Remove definitions that do not cover the memory location that they define. */
            definitions.filterOut(notCovered);

            /* Execute all the statements in the basic block. */
            foreach (auto statement, basicBlock->statements()) {
                execute(statement, definitions);
            }

            /* Something has changed? */
            ReachingDefinitions &oldDefinitions(outDefinitions[basicBlock]);
            if (oldDefinitions != definitions) {
                oldDefinitions = std::move(definitions);
                nfixpoints = 0;
            }
        }

        /*
         * Some terms might have changed their addresses. Filter again.
         */
        foreach (auto &termAndDefinitions, dataflow().term2definitions()) {
            termAndDefinitions.second.filterOut(notCovered);
        }

        /*
         * Do we loop infinitely?
         */
        if (++niterations >= 30) {
            log_.warning(tr("%1: Fixpoint was not reached after %2 iterations.").arg(Q_FUNC_INFO).arg(niterations));
            break;
        }

        canceled_.poll();
    }

    /*
     * Remove information about terms that disappeared.
     * Terms can disappear if e.g. a call is deinstrumented during the analysis.
     */
    auto disappeared = [](const Term *term){ return term->statement()->basicBlock() == nullptr; };

    std::vector<const Term *> disappearedTerms;
    foreach (auto &termAndDefinitions, dataflow().term2definitions()) {
        termAndDefinitions.second.filterOut([disappeared](const MemoryLocation &, const Term *term) { return disappeared(term); } );
    }

    remove_if(dataflow().term2value(), disappeared);
    remove_if(dataflow().term2location(), disappeared);
    remove_if(dataflow().term2definitions(), disappeared);
}
Пример #9
0
void player_morale::remove_expired()
{
    remove_if( []( const morale_point & m ) -> bool {
        return m.is_expired();
    } );
}
Пример #10
0
void StringTools::trimString (std::string& string)
{
	trimStringKeepingAllBlanks(string);
	string.erase(remove_if(string.begin(), string.end(), isspace), string.end());
}
Пример #11
0
/*!
 \brief

 \fn Project::setFileName
 \param fileName
 \return Project
*/
Project& Project::setFileName(std::string const& fileName){
    m_fileName = fileName;
    m_fileName.erase(remove_if(m_fileName.begin(), m_fileName.end(), isspace), m_fileName.end());
    return *this;
}
Пример #12
0
//--------------------------------------------------------------
void testApp::update(){
		
	panel.update();
	
	
	bool bLearnBg			= panel.getValueB("B_LEARN_BG");
	int threshold			= panel.getValueI("THRESHOLD");
	int nDilations			= panel.getValueI("N_DILATIONS");
	int nErosions			= panel.getValueI("N_EROSION");
	int maxOperations		= MAX(nDilations, nErosions);
	int minBlobSize			= panel.getValueI("MIN_BLOB_SIZE");
	int maxBlobSize			= panel.getValueI("MAX_BLOB_SIZE");
	int bBlobsTofind		= panel.getValueI("N_BLOBS_TO_FIND");

	video.update();
	
	if (video.isFrameNew()){
		
		videoColorCvImage.setFromPixels(video.getPixels(), width, height);
		videoGrayscaleCvImage = videoColorCvImage;
		
		if (bLearnBg ){ 
			videoBgImage = videoGrayscaleCvImage;
			panel.setValueB("B_LEARN_BG", false);
		}
		
		if (ofGetElapsedTimef() < 1.5){
			videoBgImage = videoGrayscaleCvImage;
		}
		
		videoDiffImage.absDiff(videoGrayscaleCvImage, videoBgImage);
		videoDiffImage.threshold(threshold);
		
		for (int i = 0; i < maxOperations; i++){
			if (i < nErosions)	videoDiffImage.erode();
			if (i < nDilations)	videoDiffImage.dilate();
		}
		
		contourFinder.findContours(	videoDiffImage, minBlobSize,maxBlobSize,bBlobsTofind,false, true);
		
	}
	
	
	
	// let's track these blobs !
	
	// a) assume all trackers are *not* found this frame. 
	
	for (int i = 0; i < trackerObjects.size(); i++){
		trackerObjects[i].bFoundThisFrame = false;
	}
	
	// b) for all blobs this frame, let's see if we can match them to the trackers.  
	
	int nBlobsFoundThisFrame = contourFinder.nBlobs;
	
	// assume that none have been found:
	bool bAmIFoundThisFrame[nBlobsFoundThisFrame];
	
	if (nBlobsFoundThisFrame > 0){
	
		
		for (int i = 0; i < nBlobsFoundThisFrame; i++){
			bAmIFoundThisFrame[i] = false;
		}
		
		// now, look through every tracker, and see how far away they are from this blob.
		// find the minimum distance, and see if this is reasonable. 
		
		for (int i = 0; i < nBlobsFoundThisFrame; i++){
			
			float	minDistance = 100000;
			int		minIndex	= -1;
			
			for (int j = 0; j < trackerObjects.size(); j++){
				if (trackerObjects[j].bFoundThisFrame == false){
					
					float dx = trackerObjects[j].pos.x - contourFinder.blobs[i].centroid.x;
					float dy = trackerObjects[j].pos.y - contourFinder.blobs[i].centroid.y;
					float distance = sqrt(dx*dx + dy*dy);
					if (distance < minDistance){
						minDistance = distance;
						minIndex = j;
					}
				}
			}
			
			if (minIndex != -1 && minDistance < 100){		// 100 = just a guess.
				trackerObjects[minIndex].pos.x = contourFinder.blobs[i].centroid.x;
				trackerObjects[minIndex].pos.y = contourFinder.blobs[i].centroid.y;
				
				trackerObjects[minIndex].posSmooth.x = 0.99f * trackerObjects[minIndex].posSmooth.x + 
													   0.01f * trackerObjects[minIndex].pos.x;
				trackerObjects[minIndex].posSmooth.y = 0.99f * trackerObjects[minIndex].posSmooth.y + 
													   0.01f * trackerObjects[minIndex].pos.y;
				
				trackerObjects[minIndex].trail.push_back(trackerObjects[minIndex].posSmooth);
				
				trackerObjects[minIndex].whoThisFrame = i;
				trackerObjects[minIndex].bFoundThisFrame = true;
				trackerObjects[minIndex].nFramesActive ++;
				bAmIFoundThisFrame[i] = true;	// we got one !
			}
		}
	}
	
	// c) for all non found blobs, add a tracker. 
	
	if (nBlobsFoundThisFrame > 0){
		for (int i = 0; i < nBlobsFoundThisFrame; i++){
			if (bAmIFoundThisFrame[i] == false){
				
				tracker temp;
				temp.pos = contourFinder.blobs[i].centroid;
				temp.posSmooth = temp.pos;
				
				temp.trail.push_back(temp.pos);
			
				temp.nFramesActive = 0;
				temp.whoThisFrame = i;
				temp.bFoundThisFrame = true;
				temp.id = idCount;
				trackerObjects.push_back(temp);
				idCount ++;
			}
		}
	}
	
	// d) kill all trackers that haven't been found
	// remove_if sorts to the end via a boolean value, 
	// http://en.wikipedia.org/wiki/Erase-remove_idiom
	
	trackerObjects.erase( remove_if(trackerObjects.begin(), trackerObjects.end(), notFountThisFrame), trackerObjects.end() );
	
}
void CPolterFlame::update_schedule()
{
	inherited::update_schedule();

	//---------------------------------------------------------------------
	// Update Scanner
	
	if (m_object->g_Alive()) {
		
		// check the start of scanning
		if (!m_state_scanning && !m_object->EnemyMan.get_enemy()) {
			// check radius
			if (Actor()->Position().distance_to(m_object->Position()) < m_scan_radius) {
				// check timing
				if (m_scan_next_time < time()) {
					// start here
					m_state_scanning = true;

					// играть звук
					//m_scan_sound.play_at_pos(m_object, get_head_position(Actor()),sm_2D);
					::Sound->play_at_pos(m_scan_sound, 0, Actor()->Position());

					// постпроцесс
					Actor()->Cameras().AddPPEffector(xr_new<CMonsterEffector>(m_scan_effector_info, m_scan_effector_time, m_scan_effector_time_attack, m_scan_effector_time_release));
				}
				
			}
		} 
		// check stop of scanning (it currently scans)
		else {
			if (!m_scan_sound._feedback()) {
				// stop here
				m_state_scanning = false;
				
				// count next scan time
				m_scan_next_time = time() + Random.randI(m_scan_delay_min,m_scan_delay_max);
			}
		}
	}
	//---------------------------------------------------------------------


	// check all flames
	for (FLAME_ELEMS_IT it = m_flames.begin();it != m_flames.end();it++) {
		SFlameElement *elem = *it;
	
		// test switches to states
		switch(elem->state) {
		case ePrepare:	
			// check if time_out
			if (elem->time_started + m_time_fire_delay < time()) select_state(elem,eFire);
			break;
		case eFire:		
			if (elem->time_started + m_time_fire_play < time()) select_state(elem,eStop);
			else {
				
				// check if we need test hit to enemy
				if (elem->time_last_hit + m_hit_delay < time()) {
					// test hit
					collide::rq_result rq;
					if (Level().ObjectSpace.RayPick(elem->position, elem->target_dir, m_length, collide::rqtBoth, rq, NULL)) {
						if ((rq.O == elem->target_object) && (rq.range < m_length)) {
							float		hit_value;
							hit_value	= m_hit_value - m_hit_value * rq.range / m_length;

							NET_Packet			P;
							SHit				HS;
							HS.GenHeader		(GE_HIT, elem->target_object->ID());	//					u_EventGen		(P,GE_HIT, element->target_object->ID());
							HS.whoID			= (m_object->ID());						//					P.w_u16			(ID());
							HS.weaponID			= (m_object->ID());						//					P.w_u16			(ID());
							HS.dir				= (elem->target_dir);					//					P.w_dir			(element->target_dir);
							HS.power			= (hit_value);							//					P.w_float		(m_flame_hit_value);
							HS.boneID			= (BI_NONE);							//					P.w_s16			(BI_NONE);
							HS.p_in_bone_space	= (Fvector().set(0.f,0.f,0.f));			//					P.w_vec3		(Fvector().set(0.f,0.f,0.f));
							HS.impulse			= (0.f);								//					P.w_float		(0.f);
							HS.hit_type			= (ALife::eHitTypeBurn);				//					P.w_u16			(u16(ALife::eHitTypeBurn));

							HS.Write_Packet			(P);
							m_object->u_EventSend	(P);

							elem->time_last_hit	= time();
						}
					}
				}
			}
			break;
		case eStop:
			xr_delete(*it);
			break;
		}
	}

	// remove all flames in state stop
	
	// удалить все элементы, выполнение которых закончено
	FLAME_ELEMS_IT I = remove_if(m_flames.begin(), m_flames.end(), remove_predicate());
	m_flames.erase(I,m_flames.end());
	
	// check if we can create another flame
	if (m_object->g_Alive() && m_object->EnemyMan.get_enemy() && (m_flames.size() < m_count)) {
		// check aura radius and accessibility
		float dist = m_object->EnemyMan.get_enemy()->Position().distance_to(m_object->Position());
		if ((dist < m_pmt_aura_radius) && m_object->control().path_builder().accessible(m_object->EnemyMan.get_enemy()->Position())) {
			// check timing
			if (m_time_flame_started + m_delay < time()) {
				create_flame(m_object->EnemyMan.get_enemy());
			}
		}
	}

	

}
Пример #14
0
bool Database::parseFile(const std::string &fileName , const char delim)
{
    if (!FileSystem::fileExists( fileName))
        return false;
    
    FILE* file = fopen(fileName.c_str() , "r");
    
    if (!file)
        return false;
    
    char line[256];
    
    int count = 0;
    while (fgets(line, sizeof(line), file))
    {
        std::stringstream ss(line);
        std::string item = "";
        std::string val = "";
        
        if ( strncmp(line, "#", 1 ) != 0 ) // skipped if begin with '#' ( commantary )
        {
            
            std::getline(ss, item, delim);
            std::getline(ss, val, delim);
            
            if ( !StringOperations::isEmpty( item) && !StringOperations::isEmpty( val )) // acceptable pair item/value, ie. not empty
            {
                bool overwrite = true;
                
                
                if ( item.find("+") != std::string::npos )
                {
                    
                    
                    item.erase(item.end() -1);
                    
                    overwrite = false;
                }
                if (delim != ' ' )
                {
                    item.erase( remove_if(  item.begin(), item.end(), ::isspace ), item.end());
                    
                    /* trim value, ie remove leading & trailing spaces */
                    val = StringOperations::trim( val , " \t\n" );
                    
                    if (!StringOperations::contains(val, "\""))
                    {
                    }
                    
                    else // quoted token
                    {
                        // si un seul " trouvé et dans la premiere moité de la chaine, considérée comme premier,
                        // sinon considéré comme second
                        const std::string::size_type halfSize = val.size() / 2;
                        
                        std::string::size_type first  = 0;
                        
                        first = val.find( "\"", first );
                        
                        std::string::size_type second = first + 1 ;
                        
                        second = val.find( "\"", second );
                        
                        if ( second == std::string::npos)
                        {
                            const std::string::size_type pos = first;
                            if ( pos < halfSize)
                            {
                                val.append("\"");
                                second = val.size() -1;
                            }
                            else
                            {
                                second = pos;
                                first = 0;
                                val.insert(0, "\"");
                            }
                            
                        }
                        
                        val.erase( val.begin() + second  , val.end() );
                        val.erase( val.begin()           , val.begin() +  first +1 );
                        
                    }
                }
                
                if (val != "" ) // valid ( &nice ) pair
                {
                    if ( itemExists( item )) // existant
                    {
                        
                        
                        auto pos = findItemPosition( item );
                        std::string oldVal = getValueForItemName(item)->getString();
                        
                        if ( pos != _dataList.end() )
                        {
                            _dataList.erase( pos);
                            count--;
                            
                            if (!overwrite) // on écrase la valeur
                            {
                                
                                
                                val += " " + oldVal;
                                
                            }
                        }
                        
                    }
                    
                    count++;
                    insertValue ( item , Variant( val ) );
                }
            }
            
        }
        
    }
    
    if ( count != (int) _dataList.size() )
    {
        /*list size and iter count don't match */
        DEBUG_ASSERT( false );
        
    }
    
    fclose(file);
    
    return true;
}
Пример #15
0
/* This main function does a little testing. Like all good CS Majors, you should
 * test your code here. There is no substitute for testing and you should be
 * sure to test for all edge cases, like calling empty_deque on an empty deque.
 */
int main(void) {

	    printf("\n\n**SYDNEY'S TEST CASES**");

    printf("\nTEST CASE 01: PUSHING BACK\n");
    printf("Creating deque...\n");
    deque* abcd = create_deque();

    struct person* abbie = create_person("Abbie", 20);
    struct person* brian = create_person("Brian", 27);
    struct person* charlie = create_person("Charlie", 36);
    struct person* daniel = create_person("Daniel", 15);

    // end result of adding should look like this:
    // (abbie) -> (brian) -> (charlie) -> (daniel)
    push_back(abcd, abbie);
    assert(abcd->size == 1);
    assert(front(abcd) == abbie);
    assert(back(abcd) == abbie);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    printf("Successfully added Abbie, 20 \n\n");
    // (abbie)
    push_back(abcd, brian);
    assert(abcd->size == 2);
    assert(front(abcd) == abbie);
    assert(back(abcd) == brian);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    printf("Successfully added Brian, 27 \n\n");
    // (abbie) -> (brian)
    push_back(abcd, charlie); // push on back Charlie
    assert(abcd->size == 3);
    assert(front(abcd) == abbie);
    assert(back(abcd) == charlie);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    assert(get(abcd, 2) == charlie);
    printf("Successfully added Charlie, 36 \n\n");
    // (abbie) -> (brian) -> (charlie)
    push_back(abcd, daniel); // push on back Daniel
    assert(abcd->size == 4);
    assert(front(abcd) == abbie);
    assert(back(abcd) == daniel);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    assert(get(abcd, 2) == charlie);
    assert(get(abcd, 3) == daniel);
    printf("Successfully added Daniel, 15 \n\n");
    // (abbie) -> (brian) -> (charlie) -> (daniel)
    printf("Everyone added successfully!\n");

    printf("Emptying deque...\n");
    empty_deque(abcd, free_person);
    assert(abcd != NULL);
    assert(abcd->size == 0);
    assert(front(abcd) == NULL);
    assert(back(abcd) == NULL);


    printf("\n\nTEST CASE 02: PUSHING FRONT\n");

    abbie = create_person("Abbie", 20);
    brian = create_person("Brian", 27);
    charlie = create_person("Charlie", 36);
    daniel = create_person("Daniel", 15);

    push_front(abcd, daniel);
    assert(abcd->size == 1);
    assert(front(abcd) == daniel);
    assert(back(abcd) == daniel);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == daniel);
    printf("Successfully added Daniel, 15 \n\n");
    // (daniel)
    push_front(abcd, charlie);
    assert(abcd->size == 2);
    assert(front(abcd) == charlie);
    assert(back(abcd) == daniel);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == charlie);
    assert(get(abcd, 1) == daniel);
    printf("Successfully added Charlie, 36 \n\n");
    // (charlie) -> (daniel)
    push_front(abcd, brian);
    assert(abcd->size == 3);
    assert(front(abcd) == brian);
    assert(back(abcd) == daniel);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == brian);
    assert(get(abcd, 1) == charlie);
    assert(get(abcd, 2) == daniel);
    printf("Successfully added Brian, 27 \n\n");
    // (brian) -> (charlie) -> (daniel)
    push_front(abcd, abbie);
    assert(abcd->size == 4);
    assert(front(abcd) == abbie);
    assert(back(abcd) == daniel);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    assert(get(abcd, 2) == charlie);
    assert(get(abcd, 3) == daniel);
    printf("Successfully added Abby, 20 \n\n");
    // (abbie) -> (brian) -> (charlie) -> (daniel)
    printf("Everyone added successfully!\n");

    printf("\n\nTEST CASE 3: REMOVE IF\n");
    printf("This should check if a node being removed is:\n");
    printf("  1) a head only\n");
    printf("  2) a tail only\n");
    printf("  3) both a head and tail\n");
    printf("  4) neither a head nor tail\n\n");

    printf("Initial config:\n");
    traverse(abcd, print_person);
    printf("\n");

    remove_if(abcd, is_age_15, free_person); // should remove Daniel
    assert(front(abcd) == abbie);
    assert(back(abcd) == charlie);
    assert(abcd->size == 3);
    assert(front(abcd) == abbie);
    assert(back(abcd) == charlie);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    assert(get(abcd, 2) == charlie);
    printf("Removed person who is tail only successfully.\n\n");
    // (abbie) -> (brian) -> (charlie)
    remove_if(abcd, is_age_20, free_person); // should remove Abbie
    assert(front(abcd) == brian);
    assert(back(abcd) == charlie);
    assert(abcd->size == 2);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == brian);
    assert(get(abcd, 1) == charlie);
    printf("Removed person who is head only successfully.\n\n");
    // (brian) -> (charlie)
    remove_if(abcd, is_age_27, free_person); // removes Brian to test a different edge case
    // (charlie)
    remove_if(abcd, is_age_36, free_person); // should Remove Charlie
    assert(abcd->size == 0);
    assert(front(abcd) == NULL);
    assert(back(abcd) == NULL);
    traverse(abcd, print_person);
    // <empty>
    printf("Removed person who is both a head and tail successfully.\n\n");
    printf("Resetting deque...\n");

    abbie = create_person("Abbie", 20);
    brian = create_person("Brian", 27);
    charlie = create_person("Charlie", 36);
    daniel = create_person("Daniel", 15);

    push_back(abcd, abbie);
    push_back(abcd, brian);
    push_back(abcd, charlie);
    push_back(abcd, daniel);
    // (abbie) -> (brian) -> (charlie) -> (daniel)
    printf("Updated config:\n");
    traverse(abcd, print_person);
    printf("\n");

    remove_if(abcd, is_age_36, free_person);
    assert(abcd->size == 3);
    traverse(abcd, print_person);
    assert(get(abcd, 0) == abbie);
    assert(get(abcd, 1) == brian);
    assert(get(abcd, 2) == daniel);
    //
    printf("Removed person that is neither a head nor tail successfully.\n");
    printf("Success!\n");

    empty_deque(abcd, free_person);
    free(abcd);

    printf("\n\nMake sure to write more test cases as well in test.c!\n"
        "Also test using valgrind. Half credit will be given to\n"
        "functions with memory leaks or memory errors.\n");

	return 0;
}
Пример #16
0
tERROR
CProxySessionManager::ProxyMain(SOCKET Server, SOCKET Server_v6, SOCKET CrService, SOCKET CrService_v6 )
{
    int RetVal = 0;
    DWORD dwCount;    
    CProxySession* Session;
    fd_set fds;
    TIMEVAL Timeout = { 1, 0 }; // 1 second Timeout

    SOCKET MySock = INVALID_SOCKET;

    while(true)
    {
        FD_ZERO(&fds);
        
        if ( Server != INVALID_SOCKET )
            FD_SET(Server, &fds);
        if ( Server_v6 != INVALID_SOCKET )
            FD_SET(Server_v6, &fds);
        if ( CrService != INVALID_SOCKET )
            FD_SET(CrService, &fds);
        if ( CrService_v6 != INVALID_SOCKET )
            FD_SET(CrService_v6, &fds);        

        // ѕолучаем набор дескрипторов, у которых мы ожидаем какой-либо активности.
        dwCount = GetDescriptors( &fds );

        CKAHCR::SetWatchdogTimeout( ( SESSION_LIST_REFRESH_TIMEOUT / 1000 ) * 2);
        
        // выгрызаем из набора дескриптор с событием.
        RetVal = select( 0, &fds, NULL, NULL, &Timeout );

        // KLSTD_TRACE1( KLMC_TRACELEVEL, "CProxySessionManager::ProxyMain : select return %d\n", RetVal );

        CKAHCR::SetWatchdogTimeout( ( SESSION_LIST_REFRESH_TIMEOUT / 1000 ) * 2);

        // проверка на выгрузку
        if ( WAIT_OBJECT_0 == WaitForSingleObject( m_hStopEvent, 0 ))
        {
            // global stop event
            KLSTD_TRACE0( KLMC_TRACELEVEL, "CProxySessionManager::ProxyMain => Received m_hStopEvent\n" );
            break;
        }

        if ( WAIT_OBJECT_0 == WaitForSingleObject( m_hRequestSessionStop, 0 ))
        {
            KLSTD_TRACE0( KLMC_TRACELEVEL, "CProxySessionManager::ProxyMain => Received m_hRequestSessionStop\n" );

            ProcessPseudoStop();
            continue;
        }

        if ( RetVal == SOCKET_ERROR )
        {
            KLSTD_TRACE2( KLMC_TRACELEVEL, "CProxySessionManager::ProxyMain => select returned %d. err = %d\n", RetVal, WSAGetLastError() );

            break;
        }

        // обработка новых подключений к слушающим сокетам
        if ( FD_ISSET(Server, &fds) )
        {
            FD_CLR( Server, &fds );
            ProcessNewConnection( Server );
            continue;
        }

        if ( FD_ISSET(Server_v6, &fds) )
        {
            FD_CLR( Server_v6, &fds );
            ProcessNewConnection( Server_v6 );
            continue;
        }

        if ( FD_ISSET(CrService, &fds) )
        {
            FD_CLR( CrService, &fds );
            ProcessNewConnection( CrService );
            continue;
        }

        if ( FD_ISSET(CrService_v6, &fds) )
        {
            FD_CLR( CrService_v6, &fds );
            ProcessNewConnection( CrService_v6 );
            continue;
        }
        
        // обработка "сп¤щих" клиентов.
        Session = GetClient( &fds );

        if ( Session )
        {            
            if ( !Session->StartClient() )
            {
                KLSTD_TRACE1( KLMC_TRACELEVEL, "CProxySessionManager::ProxyMain: Unable To restart Client %x \n", Session );
                Sleep( 1000 );
                AddClient( Session );
            }
        }
        else
        {
            // timeout 
            m_SessionList.erase( remove_if( m_SessionList.begin(), m_SessionList.end(),CDoneSession()), m_SessionList.end());
        }
    }

    if ( Server != INVALID_SOCKET )
        closesocket( Server );

    if ( Server_v6 != INVALID_SOCKET )
        closesocket( Server_v6 );

    if ( CrService != INVALID_SOCKET )
        closesocket( CrService );

    if ( CrService_v6 != INVALID_SOCKET )
        closesocket( CrService_v6 );

    return errOK;
}
Пример #17
0
void Point2PhantomNode::MakeResult(vector<FeatureGraphNode> & res, size_t maxCount)
{
  vector<OsrmMappingTypes::FtSeg> segments;

  sort(m_candidates.begin(), m_candidates.end(), [](Candidate const & r1, Candidate const & r2)
       {
         return (r1.m_dist < r2.m_dist);
       });

  size_t const n = min(m_candidates.size(), maxCount);
  segments.resize(n);

  for (size_t j = 0; j < n; ++j)
  {
    OsrmMappingTypes::FtSeg & seg = segments[j];
    Candidate const & c = m_candidates[j];

    seg.m_fid = c.m_fid;
    seg.m_pointStart = c.m_segIdx;
    seg.m_pointEnd = c.m_segIdx + 1;
  }

  OsrmFtSegMapping::OsrmNodesT nodes;
  m_routingMapping.m_segMapping.GetOsrmNodes(segments, nodes);

  res.clear();
  res.resize(maxCount);

  for (size_t j = 0; j < maxCount; ++j)
  {
    if (!segments[j].IsValid())
      continue;

    auto it = nodes.find(segments[j].Store());
    if (it == nodes.cend())
      continue;

    FeatureGraphNode & node = res[j];

    if (!m_direction.IsAlmostZero())
    {
      // Filter income nodes by direction mode
      OsrmMappingTypes::FtSeg const & node_seg = segments[j];
      FeatureType feature;
      Index::FeaturesLoaderGuard loader(m_index, m_routingMapping.GetMwmId());
      loader.GetFeatureByIndex(node_seg.m_fid, feature);
      feature.ParseGeometry(FeatureType::BEST_GEOMETRY);
      m2::PointD const featureDirection = feature.GetPoint(node_seg.m_pointEnd) - feature.GetPoint(node_seg.m_pointStart);
      bool const sameDirection = (m2::DotProduct(featureDirection, m_direction) > 0);
      if (sameDirection)
      {
        node.node.forward_node_id = it->second.first;
        node.node.reverse_node_id = INVALID_NODE_ID;
      }
      else
      {
        node.node.forward_node_id = INVALID_NODE_ID;
        node.node.reverse_node_id = it->second.second;
      }
    }
    else
    {
      node.node.forward_node_id = it->second.first;
      node.node.reverse_node_id = it->second.second;
    }

    node.segment = segments[j];
    node.segmentPoint = m_candidates[j].m_point;
    node.mwmId = m_routingMapping.GetMwmId();

    CalculateWeights(node);
  }
  res.erase(remove_if(res.begin(), res.end(),
                      [](FeatureGraphNode const & f)
                      {
                        return !f.mwmId.IsAlive();
                      }),
            res.end());
}
Пример #18
0
/* This main function does a little testing
   Like all good CS Majors you should test
   your code here. There is no substitute for testing
   and you should be sure to test for all edge cases
   e.g., calling remove_front on an empty list.
*/
int main(void)
{
	/* Now to make use of all of this stuff */
	list* llist = create_list();

  	/* What does an empty list contain?  Lets use our handy traversal function */
  	printf("TEST CASE 1\nAn Empty list should print nothing here:\n");
  	traverse(llist, print_student);
	printf("\n");

 	/* Lets add a student and then print */
 	push_front(llist, create_student("Mahmoud", "Joudeh", 20));
 	printf("TEST CASE 2\nA List with one student should print that student:\n");
	
	traverse(llist, print_student);
 	printf("\n");

 	/* Lets remove that student and then print */
 	remove_front(llist, free_student);
 	printf("TEST CASE 3\nAnother Empty list should print nothing here:\n");
 	
	traverse(llist, print_student);
 	printf("\n");

 	/* Lets add two elements and then print */
 	push_front(llist, create_student("Alex", "Ikonomidis", 19));
 	push_front(llist, create_student("Andrew", "Kim", 21));
 	printf("TEST CASE 4\nA List with two students should print those two students:\n");
 	traverse(llist, print_student);
 	printf("\n");

	/* Lets copy this list */
	list* llist2 = copy_list(llist, copy_student);
	
	printf("TEST CASE 5\nA copied list should print out the same two students:\n");
 	traverse(llist, print_student);
 	printf("\n");

  	/* Lets kill the list */
  	empty_list(llist, free_student);
 	printf("TEST CASE 6\nAfter freeing all nodes the list should be empty:\n");
 	traverse(llist, print_student);
	printf("\n");
	empty_list(llist2, free_student);
	free(llist);
	free(llist2);
 	/* YOU ARE REQUIRED TO MAKE MORE TEST CASES THAN THE ONES PROVIDED HERE */
 	/* You will get points off if you do not you should at least test each function here */

	/*Sample Tests*/
	llist = create_list();
	printf("\n4 Elements added\n ");
	push_front(llist, create_student("Abra", "Cadabra",14));
	push_front(llist, create_student("bing", "google", 10));
	push_front(llist, create_student("costa", "rica", 10));
	push_front(llist, create_student("Delta", " ", 17));
	//push_front(llist, NULL);
	traverse(llist, print_student);
	printf("\n");
		
	
	printf("Removed %d elements of age 10\n", remove_if(llist, age_is_ten, free_student));
	traverse(llist, print_student);
	remove_front(llist, free_student);
	list* list2 = copy_list(llist, copy_student);
	remove_front(llist, free_student);
	remove_back(list2, free_student);
	printf("\nEmptying list \n");
	traverse(llist, print_student_simple);
	
	i = 0;
	printf("\n500 elements being added\n");
	while(i++ < 500)
	{
			
			push_front(llist, create_student("sdflj", "sdlfs", rand()%10));

	}

	printf("\nis Empty? %d\n", is_empty(llist));
	printf("\n");
	//traverse(llist, print_student);
	
	
	
	i = 0;
	
	printf("\nRemoving 500 elements until empty\n");
	while(!is_empty(llist)){

		remove_front(llist, free_student);
	
		//practice(llist);
	}
	printf("\nis Empty? %d\n", is_empty(llist));
	
	empty_list(llist, free_student);

	remove_if(llist, trueVal, free_student);
	
	traverse(llist, print_student);	
	
	printf("\n");
	printf("\nEmptiness\n");
	remove_back(llist, free_student);
	
	traverse(llist, print_student);
	
	traverse(list2, print_student);
	
	
 	/* Testing over clean up*/
	empty_list(llist, free_student);
	empty_list(list2, free_student);
 	free(llist);
	free(list2);
	
	printf("\nAdding random numbers to the list\n");
	llist = create_list();
	i = 0;
	while (i < sizeof(numeros)/sizeof(numeros[0]))
		push_back(llist, create_student("a", "ab", numeros[i++]));

	traverse(llist, print_student_simple);
	printf("\n");

	printf("\nRemoving numbers in a random order\n");
	i = 0;
	while( i < sizeof(_numeros)/sizeof(_numeros[0]))
	{
		int total = remove_if(llist, randomizer, free_student);
		printf("size is %d after %d removes of %d: ", size(llist),  total, _numeros[i]);
		traverse(llist, print_student_simple);
		printf("\n");
		i++;
	}
	printf("\nEmpty size: \n");
	printf("list of size %d: ", size(llist));traverse(llist, print_student_simple);

	printf("\nTesting push_back and remove_if\n");
	push_back(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_if(llist, age_is_ten, free_student);
	traverse(llist, print_student_simple); printf("\n");
	empty_list(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");
	printf("\nTesting push_front and remove_if\n");
	push_front(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_if(llist, age_is_ten, free_student);
	traverse(llist, print_student_simple); printf("\n");
	empty_list(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");
	
	printf("\nTesting push_back and remove_if\n");
	push_back(llist, create_student("a", "b", 10));
	traverse(llist, print_student_simple); printf("\n");
	remove_if(llist, age_is_ten, free_student);
	traverse(llist, print_student_simple); printf("\n");
		
	printf("\nTesting push_front and remove_if\n");
	push_front(llist, create_student("a", "b", 10));
	traverse(llist, print_student_simple); printf("\n");
	remove_if(llist, age_is_ten, free_student);
	traverse(llist, print_student_simple); printf("\n");
	
	
	printf("\nTesting push_back and remove_front\n");
	push_back(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_front(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");
	
	printf("\nTesting push_back and remove_back\n");
	push_back(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_back(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");

	printf("\nTesting push_front and remove_front\n");
	push_front(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_front(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");

	printf("\nTesting push_front and remove_back\n");
	push_front(llist, create_student("a", "b", 9));
	traverse(llist, print_student_simple); printf("\n");
	remove_back(llist, free_student);
	traverse(llist, print_student_simple); printf("\n");
	
	printf("\nEVERYTHING WORKS!!!\n");
	
	i = 0;
	printf("\n Testing return value of remove_if on empty list\n");
	while(i++ < 6)
		printf("%d ",remove_if(llist, trueVal, free_student));

	printf("\n Testing return value of remove_front on empty list\n");
	i = 0;
	while(i++ < 6)
		printf("%d ", remove_front(llist, free_student));

	printf("\n Testing return value of remove_back on empty list\n");
	i = 0;
	while(i++ < 6)
		printf("%d ", remove_back(llist, free_student));

	printf("\n Testing return value of remove_if on filled list\n");
	i = 0;
	while(i++ < 6)
		push_back(llist, create_student("a", "b", 3));
	i = 0;
	while(i++ < 6)
		printf("%d ",remove_if(llist, trueVal, free_student));
	
	printf("\n Testing return value of remove_front on filled list\n");
	i = 0;
	while(i++ < 6)
		push_back(llist, create_student("a", "b", 3));
	i = 0;
	while(i++ < 6)
		printf("%d ",remove_front(llist,free_student));

	printf("\n Testing return value of remove_back on filled list\n");
	i = 0;
	while(i++ < 6)
		push_back(llist, create_student("a", "b", 3));
	i = 0;
	while(i++ < 6)
		printf("%d ",remove_back(llist,free_student));
	
	printf("\nTesting size: ");
	i = 0;
	while(i++ < 6)
		push_back(llist, create_student("a", "b", 3));
	
	printf("\nsize %d: ", size(llist));
	printf("\nEmptying it: ");
	empty_list(llist, free_student);
	printf("\tsize %d: ", size(llist));

	i = 0;
	while(i++ < 6)
		push_back(llist, create_student("a", "b", numeros[i]));
	printf("\nTesting copy method, values getting squared\n");
	printf("\n");
	list2 = copy_list(llist, copy_student0);
	traverse(llist, print_student_simple);
	printf("\n");
	traverse(list2, print_student_simple);
	printf("\n");

	printf("\nTesting front and back methods:\n");
	printf("Front: ");print_student(front(llist));
	printf("\nBack: ");print_student(back(llist));
	printf("\n_Front: ");print_student(front(list2));
	printf("\n_Back: ");print_student(back(list2));

	printf("\nTesting remove_front and remove_back together\n");
	i = 0;
	while (i++ < 6)
	{
		remove_back(llist, free_student);
		printf("\n");
		traverse(llist, print_student_simple);
		remove_front(list2, free_student);
		printf("\n");
		traverse(list2, print_student_simple);
	}

	printf("\nEmptying the list\n");
	while(i++ < 9)
		empty_list(llist, free_student);

	printf("\nAdding a null element\n");
	push_back(llist, NULL);
	traverse(llist, print_student_simple);

	list *list3 = create_list();
	empty_list(list3, free_student_nulls);
	
	print_student_simple(front(list3));
	traverse(list3, print_student_simple);

	empty_list(llist, free_student_nulls);
	empty_list(list2, free_student);
	push_back(llist, create_student("one", "two", 5));
	push_back(list2, create_student("one", "two", 10));
	
	printf("\nTesting front and back methods with one element\n");
	printf("Front: ");print_student_simple(front(llist));
	printf("\nBack: ");print_student_simple(back(llist));
	printf("\n_Front: ");print_student_simple(front(list2));
	printf("\n_Back: ");print_student_simple(back(list2));
	
	empty_list(llist, free_student_nulls);
	empty_list(list2, free_student_nulls);
	printf("\nTesting front and back methods with empty list\n");
	printf("Front: ");print_student_simple(front(llist));
	printf("\nBack: ");print_student_simple(back(llist));
	printf("\n_Front: ");print_student_simple(front(list2));
	printf("\n_Back: ");print_student_simple(back(list2));
	printf("\nAll Empty List : \"");
	traverse(llist, print_student_simple);
	traverse(list2, print_student_simple);
	printf("\"\n");
	empty_list(list3, free_student);
	printf("\nYAY\n");
	free(llist);
	free(list2);
	
	free(list3);
	//cd /mnt/hgfs/B/Current\ Projects/HW\ 11\ \(2110\)/
  	return 0;
}
Пример #19
0
std::string& filterChars(std::string& s, const std::string& allowed) {
    s.erase(remove_if(s.begin(), s.end(), [&allowed](const char& c) {
        return allowed.find(c) == std::string::npos;
    }), s.end());
    return s;
}
Пример #20
0
void FieldDescription::parseComment(std::string comment) {
    std::string ret_str ;

    bool units_found = false ;
    bool io_found = false ;
    bool chkpnt_io_found = false ;
    unsigned int chkpnt_io ;

    if ( comment.empty() ) {
        // If the comment is empty default all I/O enabled.
        io = 15 ;
        return ;
    }

    if ( debug_level >= 5 ) {
        std::cout << "comment before " << comment << std::endl ;
    }

    // remove open comment chars
    comment = get_regex_field(comment , "^(//|/\\*)(.*)" , 2) ;
    //std::cout << "1. " << comment << std::endl ;

    // remove optional doxygen comment chars
    // Note: I had to use [ \t\n\r] for \s because the Mac don't understand!
    comment = get_regex_field(comment , "^((\\*|!)<)?[ \t\n\r]*(.*)" , 3) ;
    //std::cout << "2. " << comment << std::endl ;

    // remove optional doxygen keyword
    comment = get_regex_field(comment , "(\\\\\\w+[ \t\n\r]*)?(.*)" , 2) ;
    //std::cout << "3. " << comment << std::endl ;

    ret_str = get_regex_field(comment , "@?trick_chkpnt_io[\\({]([^\\)}]+)[\\)}]" , 1) ;
    if ( ! ret_str.empty()) {
        chkpnt_io = io_map[ret_str] ;
        //std::cout << "go for trick_chkpnt_io " <<  io << std::endl ;
        chkpnt_io_found = true ;
        comment = get_regex_field(comment , "(.*)@?trick_chkpnt_io[\\({]([^\\)}]+)[\\)}]" , 1) +
         get_regex_field(comment , "@?trick_chkpnt_io[\\({]([^\\)}]+)[\\)}](.*)" , 2) ;
    }

    ret_str = get_regex_field(comment , "@?trick_io[\\({]([^\\)}]+)[\\)}]" , 1) ;
    if ( ! ret_str.empty()) {
        io = io_map[ret_str] ;
        //std::cout << "go for trick_io " <<  io << std::endl ;
        io_found = true ;
        comment = get_regex_field(comment , "(.*)@?trick_io[\\({]([^\\)}]+)[\\)}]" , 1) +
         get_regex_field(comment , "@?trick_io[\\({]([^\\)}]+)[\\)}](.*)" , 2) ;
    }

    /*
       Units can include parenthesis now.  We need to match the parenthesis in
       trick_units() to get the whole units string.
     */
    std::size_t tu_string = comment.find("trick_units") ;
    if ( tu_string != std::string::npos ) {
        std::size_t ustart = tu_string + std::string("trick_units").length() ;
        std::size_t uend = ustart + 1 ;
        std::stack<char> parens ;
        parens.push( comment[ustart]);
        while ( ! parens.empty() and (uend < comment.length())) {
            switch ( comment[uend] ) {
                case '(':
                    parens.push('(') ;
                    break ;
                case ')':
                    if (parens.top() == '(') {
                        parens.pop() ;
                    }
                    break ;
                case '}':
                    if (parens.top() == '{') {
                        parens.pop() ;
                    }
                    break ;
            }
            uend++ ;
        }
        if ( parens.empty() ) {
            units = comment.substr(ustart + 1 , uend - ustart - 2) ;
            units_found = true ;
            // If we have "@trick_units" include the "@" sign for erasure.
            if ( tu_string > 0 and comment[tu_string-1] == '@' ) {
                tu_string -= 1 ;
            }
            comment.erase(tu_string , uend - tu_string) ;
        } else {
            std::cout << "unmatched parenthesis for trick_units" << std::endl ;
        }
    }

    if ( ! io_found ) {
        // Note: I had to use [ \t\n\r] for \s because the Mac don't understand!
        ret_str = get_regex_field(comment , "^[ \t\n\r]*(\\*io|\\*oi|\\*i|\\*o|\\*\\*)" , 1) ;
        //std::cout << "3. " << ret_str << std::endl ;
        if ( ! ret_str.empty()) {
            io = io_map[ret_str] ;
            //std::cout << "stand-alone io " <<  io << std::endl ;
            io_found = true ;
            comment = get_regex_field(comment , "^[ \t\n\r]*(\\*io|\\*oi|\\*i|\\*o|\\*\\*)[ \t\n\r]*(.*)" , 2) ;
        }
    }

    //std::cout << "3. " << comment << std::endl ;
    if ( ! units_found ) {
        ret_str = get_regex_field(comment , "^[ \t\n\r]*\\(([^\\)]*)\\)" , 1) ;
        if ( ! ret_str.empty()) {
            units = ret_str ;
            //std::cout << "stand-alone units " << units << std::endl ;
            units_found = true ;
            comment = get_regex_field(comment , "^[ \t\n\r]*\\(([^\\)]*)\\)(.*)" , 2) ;
        } else {
            ret_str = get_regex_field(comment , "^[ \t\n\r]*([^ \t\n\r)]*)" , 1) ;
            if ( ! ret_str.empty()) {
                units = ret_str ;
                //std::cout << "stand-alone units " << units << " " << comment << std::endl ;
                units_found = true ;
                comment = get_regex_field(comment , "^[ \t\n\r]*([^ \t\n\r)]*)(.*)" , 2) ;
            }
        }
    }


    // Test if we have valid units.  We need to have found a units string and an io spec not zero
    // Possible todo is to create a map of valid units so we don't have to retest each string.
    if ( units_found and io != 0 and (valid_units.find(units) == valid_units.end())) {
        // remove spaces
        units.erase(remove_if(units.begin(), units.end(), isspace), units.end());
        if ( !units.compare("--") ) {
            units = "1" ;
        } else {
            // map old unit names to new names
            std::string new_units = map_trick_units_to_udunits(units) ;
            if ( units.compare(new_units) ) {
                if ( ! units_truth_is_scary ) {
                    std::cout << "\033[33mUnits converted from [" << units << "] to [" << new_units << "] "
                     << file_name << ":" << line_no << "\033[0m" << std::endl ;
                }
                units = new_units ;
            }
            ut_unit * test_units = ut_parse(u_system, units.c_str() , UT_ASCII) ;
            if ( test_units == NULL ) {
                // If the units are invalid write an error message and change the units to "1"
                std::cout << "\033[31mBad units specification [" << units << "] " << file_name << ":" << line_no
                 << "\033[0m" << std::endl ;
                units = "1" ;
            } else {
                // If the units are valid, free the memory allocated by new_units.
                ut_free(test_units) ;
                valid_units.insert(units) ;
            }
        }
    }

    if ( io == 4 ) {
        std::cout << "\033[33mWarning: " << file_name << ": line " << line_no << ": " <<
         "\"--\" is not a valid trick_io value. Setting to *io (3)\033[0m" << std::endl ;
        io = 3 ;
    }

    if ( chkpnt_io_found == true ) {
        // If a checkpoint I/O spec is found add it to the io field.
        io |= (chkpnt_io << 2 ) ;
    } else {
        // else duplicated the io field to the chkpnt io field.
        io |= (io << 2 ) ;
    }

    // The rest of the comment is the description of the variable.

    // remove the c comment end marker.
    comment = get_regex_field(comment , "(.*)\\*/" , 1) ;

    // posix c regular expressions are terrible. the regexes above will leave "@" signs because
    // the regular expressions are so greedy.
    comment = get_regex_field(comment , "^[ \t\n\r@]+(.*)" , 1) ;

    // remove leading and trailing whitespace
    comment = trim(comment) ;

    // escape special characters, convert tabs and newlines to spaces, remove multiple spaces.
    std::ostringstream ss ;
    bool is_space = false ;
    for (std::string::iterator it = comment.begin(); it != comment.end(); it++) {
        switch (*it) {
            case '\\': ss << "\\\\"; is_space = false ; break;
            case '"': ss << "\\\""; is_space = false ; break;
            case '\b': ss << "\\b"; is_space = false ; break;
            case '\f': ss << "\\f"; is_space = false ; break;
            case '\n':
            case '\r':
            case '\t':
            case ' ': if ( ! is_space ) ss << " "; is_space = true ; break;
            default: ss << *it; is_space = false ; break;
        }
    }

    description = ss.str() ;

}
Пример #21
0
bool devicelist::isStage(std::string name) {
    std::transform(name.begin(),name.end(),name.begin(),::toupper);
    name.assign(name.begin(), remove_if(name.begin(), name.end(), &ispunct));
    if(
        //nanoX
        name == "NANOX" || name == "NANOSX" ||
        /*
        name == "NANOX200" || name == "NANOX200SG" || name == "NANOX200CAP" ||
        name == "NANOX400" || name == "NANOX400SG" || name == "NANOX400CAP" ||
        name == "NANOSX400" || name == "NANOSX400CAP" || name == "NANOSX400CAPDIG" ||
        name == "NANOSX800" || name == "NANOSX800CAP" || name == "NANOSX800CAPDIG" ||
        name == "NANOX240SG45" || name == "NANOX240SG45°"||
        */

        //X positionierer
        name == "PX" || name == "PU" ||
        /*
        name == "PX38" || name == "PX38SG" ||
        name == "PX50" || name == "PX50CAP" ||
        name == "PX100" || name == "PX100SG" ||
        name == "PX200" || name == "PX200SG" || name == "PX200CAP" ||
        name == "PX300" || name == "PX300SG" || name == "PX300CAP" ||
        name == "PX400" || name == "PX400SG" || name == "PX400CAP" ||
        name == "PX500" || name == "PX1500" ||
        name == "PU40"  || name == "PU40SG"  ||
        name == "PU90" || name == "PU90SG" ||
        name == "PU100" || name == "PU100SG" ||
        name == "PU65HR" ||
        */

        //Z Positionierer
        name == "PZ" ||
        /*
        name == "PZ10" ||
        name == "PZ16" || name == "PZ16CAP" ||
        name == "PZ38" || name == "PZ38SG" || name == "PZ38CAP" |
        name == "PZ100" || name == "PZ100SG" || name == "PZ100CAP" ||
        name == "PZ250" || name == "PZ250SG" ||
        name == "PZ300" || name == "PZ300AP" || name == "PZ100CAPAP" ||
        name == "PZ400" || name == "PZ400SG" || name == "PZ400OEM" || name == "PZ400SGOEM" ||
        name == "PZ200" || name == "PZ200OEM" || name == "PZ200SGOEM" ||
        name == "PZ8D12" || name == "PZ8D12SG" ||
        name == "PZ20D12" || name == "PZ20D12SG" ||
        */
        //MIPOS
        name == "MIPOS" || name == "NANOMIPOS" ||
        /*
        name == "MIPOS20" || name == "MIPOS20SG"||
        name == "MIPOS100" || name == "MIPOS100UD" || name == "MIPOS100SG" || name == "MIPOS100SGUD" ||
        name == "MIPOS100PL" || name == "MIPOS100PLSG" || name == "MIPOS100PLCAP" ||
        name == "MIPOS250" || name == "MIPOS250SG" || name == "MIPOS250CAP" ||
        name == "MIPOS5500" || name == "MIPOS500UD" || name == "MIPOS500SG" || name == "MIPOS500SGUD" ||
        name == "NANOMIPOS400" || name == "NANOMIPOS400CAP" ||
        name == "MIPOSN10/2" || name == "MIPOSN10/2CAP" ||
        name == "MIPOS16-158"
        */
        //Stapelaktoren
        name == "N" ||
        name == "P" || name == "PA" || name == "PHL" || name == "PAHL" ||
        name == "R" || name == "RA" ||
        name == "PAT" || name == "PS" ||
        name == "HP" || name == "HPA"
    )
    {
        return true;
    }
    return false;
}
Пример #22
0
int main(int argc, char* argv[])
{
	printf("Welcome!! I'm a ploynomail calculator\n");
	
	//string strCommand;		//명령줄 buffer
/*
	if(argc > 1)	//파일로 읽기.
	{
		FILE * fp = fopen(argv[1],"rt");
		char c;
		while( (c = getc(fp)) != -1 )
			str.append(1,c);
	}
	else			//명령줄로 읽기.
	*/
	
	int state = S_NORMAL;

	while(state != S_EXIT)
	{
		printf("> ");
		char buf[255];
		gets(buf);
		string str(buf);
		//입력 받은 모든 공백을 제거한다.
		str.erase(remove_if(str.begin(), str.end() , IsSpace) , str.end());
		
		int i = 0;
		
		//exit 체크
		int nFind;
		nFind = str.find(GetOperator(EXIT));
		if (nFind != -1)
		{
			state = S_EXIT;
			break;
		}
		
		//assing 체크
		nFind = str.find(GetOperator(ASSING));
		
		POLY poly;

		if (nFind != -1)	//type 문
		{			
			poly.id.append(str.begin(),nFind);
			if(CheckIdValid(poly.id) == false)
				continue;
			i+= nFind+sizeof(GetOperator(ASSING));
		}
		//이름이 없을 경우 id.empty() == true


		//state = S_OPERATOR;
		TERMS& termVector = poly.terms;

		while( i < str.size() )
		{
			TERM term;
			//실제 다항식 계산.
			string strOperand,strOperator;

			int readNum,value;
			int result = GetNumber(str.c_str()+i,&readNum,&value);
			if(result == RETURN_ERROR)
				break;
			else if(result == true)
			{
				while(IsDigit(str[i]))
					strOperand.append(1,str[i++]);
				term.coefficient = atoi(strOperand.c_str());
			}
			else
				term.coefficient = 1;

			strOperand.erase();
			if(IsLetter(str[i]))
			{
				
			}

			termVector.push_back(term);
			
		}
		
		sort(termVector.begin(),termVector.end(),BinaryTerm);


	}

	printf("Press any key to continue");
	char t;
	scanf("%c",&t);
	return 0;
}
Пример #23
0
// adjusts the allele to have a new start
// returns the ref/alt sequence obtained by subtracting length from the left end of the allele
void Allele::subtract(
        int subtractFromRefStart,
        int subtractFromRefEnd,
        string& substart,
        string& subend,
        vector<pair<int, string> >& cigarStart,
        vector<pair<int, string> >& cigarEnd,
        vector<short>& qsubstart,
        vector<short>& qsubend
    ) {

    substart.clear();
    subend.clear();
    cigarStart.clear();
    cigarEnd.clear();
    qsubstart.clear();
    qsubend.clear();

    // prepare to adjust cigar
    list<pair<int, string> > cigarL = splitCigarList(cigar);

    // walk the cigar string to determine where to make the left cut in the alternate sequence
    int subtractFromAltStart = 0;
    if (subtractFromRefStart) {
        int refbpstart = subtractFromRefStart;
        pair<int, string> c;
        while (!cigarL.empty()) {
            c = cigarL.front();
            cigarL.pop_front();
            char op = c.second[0];
            switch (op) {
                case 'M':
                case 'X':
                case 'N':
                    refbpstart -= c.first;
                    subtractFromAltStart += c.first;
                    break;
                case 'I':
                    subtractFromAltStart += c.first;
                    break;
                case 'D':
                    refbpstart -= c.first;
                    break;
                default:
                    break;
            }

            cigarStart.push_back(c);

            if (refbpstart < 0) {
                // split/adjust the last cigar element
                cigarL.push_front(c);
                cigarL.front().first = -refbpstart;
                cigarStart.back().first += refbpstart;
                switch (op) {
                    case 'M':
                    case 'X':
                    case 'N':
                    case 'I':
                        subtractFromAltStart += refbpstart;
                        break;
                    case 'D':
                    default:
                        break;
                }
                break; // we're done
            }
        }
    }


    int subtractFromAltEnd = 0;
    // walk the cigar string to determine where to make the right cut in the alternate sequence
    if (subtractFromRefEnd) {
        int refbpend = subtractFromRefEnd;
        pair<int, string> c;
        while (!cigarL.empty() && refbpend > 0) {
            c = cigarL.back();
            cigarL.pop_back();
            char op = c.second[0];
            switch (op) {
                case 'M':
                case 'X':
                case 'N':
                    subtractFromAltEnd += c.first;
                    refbpend -= c.first;
                    break;
                case 'I':
                    subtractFromAltEnd += c.first;
                    break;
                case 'D':
                    refbpend -= c.first;
                    break;
                default:
                    break;
            }

            cigarEnd.insert(cigarEnd.begin(), c);

            if (refbpend < 0) {
                // split/adjust the last cigar element
                cigarL.push_back(c);
                cigarL.back().first = -refbpend;
                cigarEnd.front().first += refbpend;
                switch (op) {
                    case 'M':
                    case 'X':
                    case 'I':
                    case 'N':
                        subtractFromAltEnd += refbpend;
                        break;
                    case 'D':
                    default:
                        break;
                }
                break; // drop out of loop, we're done
            }
        }
    }

    // adjust the alternateSequence
    substart = alternateSequence.substr(0, subtractFromAltStart);
    subend = alternateSequence.substr(alternateSequence.size() - subtractFromAltEnd, subtractFromAltEnd);
    alternateSequence.erase(0, subtractFromAltStart);
    alternateSequence.erase(alternateSequence.size() - subtractFromAltEnd, subtractFromAltEnd);

    // adjust the quality string
    qsubstart.insert(qsubstart.begin(), baseQualities.begin(), baseQualities.begin() + subtractFromAltStart);
    qsubend.insert(qsubend.begin(), baseQualities.begin() + baseQualities.size() - subtractFromAltEnd, baseQualities.end());
    baseQualities.erase(baseQualities.begin(), baseQualities.begin() + subtractFromAltStart);
    baseQualities.erase(baseQualities.begin() + baseQualities.size() - subtractFromAltEnd, baseQualities.end());

    // reset the cigar
    cigarL.erase(remove_if(cigarL.begin(), cigarL.end(), isEmptyCigarElement), cigarL.end());
    cigar = joinCigarList(cigarL);

    // reset the length
    length = alternateSequence.size();

    // update the type specification
    updateTypeAndLengthFromCigar();

    // adjust the position
    position += subtractFromRefStart; // assumes the first-base of the alleles is reference==, not ins

    //referenceLength -= subtractFromRefStart;
    //referenceLength -= subtractFromRefEnd;

    referenceLength = referenceLengthFromCigar();

}
Пример #24
0
void GreedyPosTagger::processVertex(LinguisticGraphVertex vx,AnalysisGraph* anagraph) const
{
  LinguisticGraph* graph=anagraph->getGraph();
  LinguisticGraphVertex startVx=anagraph->firstVertex();
  LinguisticGraphVertex endVx=anagraph->lastVertex();

  PTLOGINIT;
  if (vx==startVx || vx==endVx)
  {
    return;
  }
  MorphoSyntacticData* data=get(vertex_data,*graph,vx);
  Token* token=get(vertex_token,*graph,vx);
  if (data==0)
  {
    LERROR << "MorphoSyntacticData of vertex " << vx << " is NULL !";
    return;
  }
  LDEBUG << "process vertex : " << vx << " : " 
    << Common::Misc::limastring2utf8stdstring(token->stringForm());

  MorphoSyntacticData* posdata=new MorphoSyntacticData(*data);
  put(vertex_data,*graph,vx,posdata);
  
  set<LinguisticCode> micros=posdata->allValues(*m_microAccessor);
  LinguisticCode selectedMicro;


  if (micros.size()==0)
  {
    LWARN << "Token " 
      << Common::Misc::limastring2utf8stdstring(token->stringForm()) 
      << " has no possible dicowords ! build a DicoWord with category 0";
    selectedMicro=0;
  }
  else if (micros.size()==1)
  {
    // no choice, put this category
    selectedMicro=*(micros.begin());
    LDEBUG << "GreedyPosTagging : only one choice : " << selectedMicro;
  }
  else
  {
    // choose the most probable dicoWord
    set<LinguisticCode>::iterator dwItr,dwMaxTri,dwMaxBi;
    float maxTri=0;
    float maxBi=0;
    LinguisticCode cat1(0),cat2(0);

    LinguisticGraphInEdgeIt inItr,inItrEnd;
    boost::tie(inItr,inItrEnd)=in_edges(vx,*graph);
    for (;inItr!=inItrEnd;inItr++)
    {
      LinguisticGraphVertex predVx=source(*inItr,*graph);
      MorphoSyntacticData* m2=get(vertex_data,*graph,predVx);
      if (predVx==startVx && m2!=0 && !m2->empty())
      {
        cat2=m_microCatPonctuForte;
      }
      else
      {
        
        cat2=m_microAccessor->readValue(m2->begin()->properties);

        LinguisticGraphInEdgeIt inItr2,inItr2End;
        boost::tie(inItr2,inItr2End)=in_edges(vx,*graph);
        for (;inItr2!=inItr2End;inItr2++)
        {
          LinguisticGraphVertex predpredVx=source(*inItr2,*graph);
          MorphoSyntacticData* m1=get(vertex_data,*graph,predpredVx);
          if (predpredVx==startVx && m1!=0 && !m1->empty())
          {
            cat1=m_microCatPonctuForte;
          }
          else
          {
            cat1=m_microAccessor->readValue(m1->begin()->properties);
          }
          // search better trigram
          for (dwItr=micros.begin();dwItr!=micros.end();dwItr++)
          {
            float p=m_trigramMatrix->freq(cat1,cat2,*dwItr);
            if (p>maxTri)
            {
              maxTri=p;
              dwMaxTri=dwItr;
            }
          }
        }
      }
      if (maxTri==0)
      {
        // no trigram has been found, search bigram
        for (dwItr=micros.begin();dwItr!=micros.end();dwItr++)
        {
          float p=m_bigramMatrix->freq(cat1,*dwItr);
          if (p>maxBi)
          {
            maxBi=p;
            dwMaxBi=dwItr;
          }
        }

      }


    }

    if (maxTri!=0)
    {
      // choose best trigram
      LDEBUG << "found trigram : choose " << *dwMaxTri << " (p=" << maxTri << ")";
      selectedMicro=*dwMaxTri;
    }
    else if (maxBi!=0)
    {
      // choose best bigram
      LDEBUG << "found bigram : choose " << *dwMaxBi << " (p=" << maxBi << ")";
      selectedMicro=*dwMaxBi;
    }
    else
    {
      // no trigram nor bigram has been found
      // choose better probability as source in bigram then as target in bigram
      LWARN << "Found no trigram nor bigram (" << cat1 << "," << cat2 << ") ! try heuristics to find a microcategory";
      for (dwItr=micros.begin();dwItr!=micros.end();dwItr++)
      {
        float p=m_bigramMatrix->freq(m_microCatPonctuForte,*dwItr);
        if (p>maxBi)
        {
          maxBi=p;
          dwMaxBi=dwItr;
        }
      }
      if (maxBi!=0)
      {
        LDEBUG << "found bigram with ponctu forte : choose " << *dwMaxBi <<  " (p=" << maxBi << ")";
        selectedMicro=*dwMaxBi;
      }
      else
      {
        selectedMicro=*(micros.begin());
        LDEBUG << "choose first : " << selectedMicro;
      }
    }
  }
  
  // filter linguisticelement
  CheckDifferentPropertyPredicate cdpp(m_microAccessor,selectedMicro);
  posdata->erase(remove_if(posdata->begin(),posdata->end(),cdpp),posdata->end());
  
}
Пример #25
0
void List<Type>::remove(const Type &value)
{
    // remove elements that are equal to [value]
    remove_if(IsEqualTo(value));
}
void AuthTokenTable::RemoveEntriesSupersededBy(const Entry& entry) {
    entries_.erase(remove_if(entries_, [&](Entry& e) { return entry.Supersedes(e); }),
                   entries_.end());
}
Пример #27
0
void Delaunay::Triangulate(const vertexSet& vertices, triangleSet& output)
{
	if (vertices.size() < 3) return;	// nothing to handle

	// Determine the bounding box.
	cvIterator itVertex = vertices.begin();

	REAL xMin = itVertex->GetX();
	REAL yMin = itVertex->GetY();
	REAL xMax = xMin;
	REAL yMax = yMin;

	++itVertex;		// If we're here, we know that vertices is not empty.
	for (; itVertex != vertices.end(); itVertex++)
	{
		xMax = itVertex->GetX();	// Vertices are sorted along the x-axis, so the last one stored will be the biggest.
		REAL y = itVertex->GetY();
		if (y < yMin) yMin = y;
		if (y > yMax) yMax = y;
	}

	REAL dx = xMax - xMin;
	REAL dy = yMax - yMin;

	// Make the bounding box slightly bigger, just to feel safe.
	REAL ddx = dx * 0.01F;
	REAL ddy = dy * 0.01F;

	xMin -= ddx;
	xMax += ddx;
	dx += 2 * ddx;

	yMin -= ddy;
	yMax += ddy;
	dy += 2 * ddy;

	// Create a 'super triangle', encompassing all the vertices. We choose an equilateral triangle with horizontal base.
	// We could have made the 'super triangle' simply very big. However, the algorithm is quite sensitive to
	// rounding errors, so it's better to make the 'super triangle' just big enough, like we do here.
	vertex vSuper[3];

	vSuper[0] = vertex(xMin - dy * sqrt3 / 3.0F, yMin);	// Simple highschool geometry, believe me.
	vSuper[1] = vertex(xMax + dy * sqrt3 / 3.0F, yMin);
	vSuper[2] = vertex((xMin + xMax) * 0.5F, yMax + dx * sqrt3 * 0.5F);

	triangleSet workset;
	workset.insert(triangle(vSuper));

	for (itVertex = vertices.begin(); itVertex != vertices.end(); itVertex++)
	{
		// First, remove all 'completed' triangles from the workset.
		// A triangle is 'completed' if its circumcircle is entirely to the left of the current vertex.
		// Vertices are sorted in x-direction (the set container does this automagically).
		// Unless they are part of the 'super triangle', copy the 'completed' triangles to the output.
		// The algorithm also works without this step, but it is an important optimalization for bigger numbers of vertices.
		// It makes the algorithm about five times faster for 2000 vertices, and for 10000 vertices,
		// it's thirty times faster. For smaller numbers, the difference is negligible.
		tIterator itEnd = remove_if(workset.begin(), workset.end(), triangleIsCompleted(itVertex, output, vSuper));

		edgeSet edges;

		// A triangle is 'hot' if the current vertex v is inside the circumcircle.
		// Remove all hot triangles, but keep their edges.
		itEnd = remove_if(workset.begin(), itEnd, vertexIsInCircumCircle(itVertex, edges));
		workset.erase(itEnd, workset.end());	// remove_if doesn't actually remove; we have to do this explicitly.

		// Create new triangles from the edges and the current vertex.
		for (edgeIterator it = edges.begin(); it != edges.end(); it++)
			workset.insert(triangle(it->m_pV0, it->m_pV1, & (* itVertex)));
	}

	// Finally, remove all the triangles belonging to the 'super triangle' and move the remaining
	// triangles tot the output; remove_copy_if lets us do that in one go.
	tIterator where = output.begin();
	remove_copy_if(workset.begin(), workset.end(), inserter(output, where), triangleHasVertex(vSuper));
}
Пример #28
0
void episode_game::update()
{
	// main character
	if( (_character.get()!=NULL) && (_character.get()->is_dead()) )
	{
		_character.get()->stop();
		
		// add an explosion
		_character_explosion = new explosion();
		_character_explosion->x_y(_character.get()->x(),_character.get()->y());
		_character_explosion->start();
		
		_collision_system.remove(_character);
		
		_character.reset();
	}
	if(_character_explosion!=NULL)
	{
		_character_explosion->update();
		if(_character_explosion->is_dead())
		{
			_character_explosion->stop();
			delete _character_explosion;
			_character_explosion = NULL;
			
			// end of game
			_current_episode_status = ENDED;
		}
	}
		
	// enemies
	
	if( (rand()%TIME_STEP>480))
	{
		add_enemies(1);
	}
	
	auto ite = _enemies.begin();
	while(ite!=_enemies.end())
	{
		enemy_ptr ptr = *(ite++);
		enemy *obj = ptr.get();
		
		if(_kill_all_enemies)
		{
			obj->set_dead(true);
		}
		// enemy is dead: remove it
		if(obj->is_dead())
		{
			double x = ptr.get()->x();
			double y = ptr.get()->y();
			
			obj->stop();
			
			_collision_system.remove(ptr);
			
			_enemies.erase(remove_if(_enemies.begin(),_enemies.end(),ptr_contains(ptr.get())));
			
			// add an explosion
			_explosions.push_back(NULL);
			_explosions.back() = new explosion();
			_explosions.back()->x_y(x,y);
			_explosions.back()->start();
			
			ite--;
			continue;
		}
		
		obj->update();
	}
	
	if(_kill_all_enemies)
	{
		_kill_all_enemies = false;
		_kill_all_enemies_enable = false;
		_add_bomb = false;
		delete _bomb;
		_bomb = NULL;
	}
	
	// character bullets
	
	if(_character.get()!=NULL)
	{
		while(_add_bullets>0)
		{
			bullet_ptr obj_ptr = make_shared<bullet>();
			obj_ptr.get()->x_y(_character.get()->cx(),_character.get()->yh());
			obj_ptr.get()->start();
		
			_bullets.push_back(obj_ptr);
			_collision_system.add(obj_ptr);
		
			_add_bullets--;
		}
	}
	
	auto itb = _bullets.begin();
	while(itb!=_bullets.end())
	{
		bullet_ptr ptr = *(itb);
		bullet *obj = ptr.get();
		
		// is bullet dead
		if(obj->is_dead())
		{ 
			obj->stop();
			_collision_system.remove(ptr);
			_bullets.erase(remove_if(_bullets.begin(),_bullets.end(),ptr_contains(ptr.get())));
			
			continue;
		}
		itb++;
		
		obj->update();
	}
	
	// energy
	_energy->update();
	
	// bomb
	if( (_add_bomb) && (_kill_all_enemies_enable) )
	{
		_add_bomb = false;
		
		_bomb = new bomb();
		_bomb->x_y(_character.get()->x(),_character.get()->y());
		_bomb->start();
	}
	if(_bomb!=NULL)
	{
		_bomb->update();
	}
	
	// explosions
	
	auto it = _explosions.begin();
	while(it!=_explosions.end())
	{
		(*it)->update();
		
		if((*it)->is_dead())
		{
			(*it)->stop();
			delete *it;
			_explosions.erase(it);
			--it;
		}
		++it;
	}
	
	if(_character.get()!=NULL)
	{
		_character.get()->update();
	}
}
Пример #29
0
  void OutputCSTBonds(ostream &ofs, OBMol &mol, string prefix)
  {
    string bond_type;

    /* ---- Write povray-description of all bonds---- */
    for(unsigned int i = 0; i < mol.NumBonds(); ++i)
      {

        double x1,y1,z1,x2,y2,z2; /* Start and stop coordinates of a bond       */
        double dist;              /* Distance between (x1|y1|z1) and (x2|y2|z2) */
        double phi,theta;         /* Angles between (x1|y1|z1) and (x2|y2|z2)   */
        double dy;                /* Distance between (x1|0|z1) and (x2|0|z2)   */

        /* ---- Get a pointer to ith atom ---- */
        OBBond *bond = mol.GetBond(i);

        /* ---- Assign start of bond i ---- */
        x1 = (bond -> GetBeginAtom()) -> GetX();
        y1 = (bond -> GetBeginAtom()) -> GetY();
        z1 = (bond -> GetBeginAtom()) -> GetZ();

        /* ---- Assign end of bond i ---- */
        x2 = (bond -> GetEndAtom()) -> GetX();
        y2 = (bond -> GetEndAtom()) -> GetY();
        z2 = (bond -> GetEndAtom()) -> GetZ();

        /* ---- Calculate length of bond and (x1|0|z1) - (x2|0|z2) ---- */
        dist = sqrt(SQUARE(x2-x1) + SQUARE(y2-y1) + SQUARE(z2-z1));
        dy = sqrt(SQUARE(x2-x1) + SQUARE(z2-z1));

        /* ---- Calculate Phi and Theta ---- */
        phi = (double) 0.0;
        theta = (double) 0.0;
        if (fabs(dist) >= EPSILON)
          phi = acos((y2-y1)/dist);
        if (fabs(dy) >= EPSILON)
          theta = acos((x2-x1)/dy);

        /* ---- Begin of description of bond i (for a capped sticks model) ---- */
        ofs << "#declare " << prefix << "_bond" << i << " = object {" << endl;
        ofs << "\t  union {" << endl;

        /* ---- Begin of Start-Half of Bond (i) ---- */
        ofs << "\t   object {" << endl << "\t    bond_" << bond -> GetBondOrder()  << "\n";

        /* ---- Add a pigment - statement for start-atom of bond ---- */
        bond_type = bond->GetBeginAtom() -> GetType();
        bond_type.erase(remove_if(bond_type.begin(), bond_type.end(), bind1st(equal_to<char>(), '.')), bond_type.end());
        ofs << "\t    pigment{color Color_"
            << bond_type
            << "}" << endl;

        /* ---- Scale bond if needed ---- */
        if (fabs((double) 2.0 * dist) >= EPSILON)
          {

            /* ---- Print povray scale-statement (x-Axis) ---- */
            ofs << "\t    scale <" << (double) 0.5 * dist << ",1.0000,1.0000>" << endl;

          }

        /* ---- Rotate (Phi) bond if needed ---- */
        if (fabs(RAD2DEG(-phi) + (double) 90.0) >= EPSILON)
          {

            /* ---- Rotate along z-axis ---- */
            ofs << "\t    rotate <0.0000,0.0000,"
                << RAD2DEG(-phi) + (double) 90.0
                << ">" << endl;

          }

        /* ---- Check angle between (x1|0|z1) and (x2|0|z2) ---- */
        if (theta >= EPSILON)
          {

            /* ---- Check direction ---- */
            if ((z2 - z1) >= (double) 0.0)
              {

                /* ---- Rotate along y-Axis (negative) ---- */
                ofs << "\t    rotate <0.0000,"
                    << RAD2DEG((double) -1.0 *theta) << ",0.0000>"
                    << endl;

              }
            else
              {

                /* ---- Rotate along y-Axis (positive) ---- */
                ofs << "\t    rotate <0.0000," << RAD2DEG(theta) << ",0.0000>" << endl;

              }

          }

        /* ---- Translate bond to start ---- */

        ofs << "\t    translate " << prefix << "_pos_" << bond -> GetBeginAtomIdx() << endl;

        /* ---- End of description of Start-Bond ---- */
        ofs << "\t   }" << endl;

        /* ---- Begin of End-Half of Bond i ---- */
        ofs << "\t   object {" << endl << "\t    bond_" << bond -> GetBondOrder() << endl;

        /* ---- Add a pigment - statement for end-atom of bond i ---- */
        bond_type = bond->GetEndAtom() -> GetType();
        bond_type.erase(remove_if(bond_type.begin(), bond_type.end(), bind1st(equal_to<char>(), '.')), bond_type.end());

        ofs << "\t    pigment{color Color_"
            << bond_type
            << "}" << endl;

        /* ---- Scale bond if needed ---- */
        if (fabs((double) 2.0 * dist) >= EPSILON)
          {

            /* ---- Print povray scale-statement (x-Axis) ---- */
            ofs << "\t    scale <" << (double) 0.5 * dist << ",1.0000,1.0000>" << endl;

          }

        /* ---- Rotate (Phi) bond if needed ---- */
        if (fabs(RAD2DEG(-phi) + (double) 270.0) >= EPSILON)
          {

            /* ---- Rotate along z-axis (oposite to start half) ---- */
            ofs << "\t    rotate <0.0000,0.0000,"
                << (RAD2DEG(-phi) + (double) 90.0) + (double) 180.0
                << ">" << endl;

          }

        /* ---- Check angle between (x1|0|z1) and (x2|0|z2) ---- */
        if (fabs(theta) >= EPSILON)
          {

            /* ---- Check direction ---- */
            if ((z2 - z1) >= (double) 0.0)
              {

                /* ---- Rotate along y-Axis (negative) (oposite orientation) ---- */
                ofs << "\t    rotate <0.0000,"
                    << RAD2DEG((double) -1.0 * theta)
                    << ",0.0000>"
                    << endl;

              }
            else
              {

                /* ---- Rotate along y-Axis (positive) (oposite orientation) ---- */
                ofs << "\t    rotate <0.0000," << RAD2DEG(theta) << ",0.0000>" << endl;

              }

          }

        /* ---- Translate bond to end ---- */
        ofs << "\t    translate " << prefix << "_pos_" << bond -> GetEndAtomIdx() << endl;

        /* ---- End of description of End-Bond ---- */
        ofs << "\t   }" << endl;

        /* ---- End of description of bond i ---- */
        ofs << "\t  }" << endl << "\t }" << endl << endl;

      }

  }
Пример #30
0
int main()
{
  std::ifstream dictionary;
  dictionary.open("/Users/zangxiaoxue/step_google/STEP_GOOGLE/dictionary.txt", std::ios::in);
  if(!dictionary.is_open())
  {
    std::cout << "Unable to open dictionay." << std::endl;
    return -1;
  }
  std::string read_line;
  while(!dictionary.eof())
  {
    std::getline(dictionary, read_line);
      std::transform (read_line.begin (), read_line.end (), read_line.begin (), tolower);
      std::string read_word= read_line;
      std::sort(read_line.begin(), read_line.end());
      std::map<char, int> freq;
      for(auto& c: read_line)
      {
          if( freq.find(c) == freq.end())
              freq[c] = 1;
          else
              ++freq[c];
      }

      std::string input;
      for(auto& c: freq)
      {
          input += c.first;
          input += (c.second + '0');
      }
    //std::cout << read_line << std::endl;
      buildTree(first, input, read_word);
  }
  std::cout << "finish loading." << std::endl;
  std::string text;
  if (text.empty()){
  std::cout << "please input words." <<std::endl;
  std::getline(std::cin, text);
  }
    std::transform (text.begin (), text.end (), text.begin (), tolower);
  text.erase(remove_if(text.begin(), text.end(), isspace), text.end());
  std::sort(text.begin(), text.end());
  //std::cout << text << std::endl;
  std::map<char, int> freq;
  for(auto& c: text)
  {
    if( freq.find(c) == freq.end())
        freq[c] = 1;
    else
        ++freq[c];
  }
  std::string input;
  for(auto& c: freq)
  {
      input += c.first;
      input += (c.second + '0');
  }
    auto result = isWordinTree(first, input);
    if (!result){std::cout << "no result found!" << std::endl;}
}