当前位置: 首页>>代码示例>>C++>>正文


C++ Rule类代码示例

本文整理汇总了C++中Rule的典型用法代码示例。如果您正苦于以下问题:C++ Rule类的具体用法?C++ Rule怎么用?C++ Rule使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Rule类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: assert

bool State::isForbidden(Position p, Block b, const Test &test) const
{
    bool isForbidden = true;

    size_t count33 = 0;
    auto check33 = [&](Test t) {
        auto iter = std::find(t->position.cbegin(), t->position.cend(), p);
        assert(iter != t->position.cend());
        size_t i = iter - t->position.cbegin();
        assert(i < t->line.size());
        t->line[i] = b;

        size_t count = 0;
        for (size_t j = i+1; j < t->line.size(); ++j) {
            if (t->line[j] != b)
                break;
            ++count;
        }

        bool isS3 = false;

        if (isS3 == false  && count < 3 && i > 0 && t->line[i - 1] == SPACE) {
            auto attackable = check3(t, i);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }

        if (isS3 == false && count < 2 && i > 1 && t->line[i - 1] == b && t->line[i - 2] == SPACE) {
            auto attackable = check3(t, i - 1);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }

        if (isS3 == false && count == 0 && i > 2 && t->line[i - 1] == b && t->line[i - 2] == b && t->line[i - 3] == SPACE) {
            auto attackable = check3(t, i - 2);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }

        if (isS3 == false && count < 2 && i > 2 && t->line[i - 1] == SPACE && t->line[i - 2] == b && t->line[i - 3] == SPACE) {
            auto attackable = check3(t, i - 2);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }
        if (isS3 == false && count == 0 &&  i > 3 && t->line[i - 1] == SPACE && t->line[i - 2] == b && t->line[i - 3] == b && t->line[i  - 4] == SPACE) {
            auto attackable = check3(t, i - 3);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }
        if (isS3 == false && count == 0 && i > 3 && t->line[i - 1] == b && t->line[i - 2] == SPACE && t->line[i - 3] == b && t->line[i - 4] == SPACE) {
            auto attackable = check3(t, i - 3);
            if (attackable->rank == S_THREE) {
                isS3 = true;
            }
        }
        if (isS3) {
            ++count33;
        }
    };

    if (get(p) == SPACE) {
        isForbidden = false;
        auto vertical = getVertical(p);
        auto horizontal = getHorizontal(p);
        auto diagonalA = getDiagonalA(p);
        auto diagonalB = getDiagonalB(p);
        if (test) {
            if (vertical->position.front() == test->position.front()
                && vertical->position.back() == test->position.back()) {
                vertical = test;
            }
            else if (horizontal->position.front() == test->position.front()
                && horizontal->position.back() == test->position.back()) {
                horizontal = test;
            }
            else if (diagonalA->position.front() == test->position.front()
                && diagonalA->position.back() == test->position.back()) {
                diagonalA = test;
            }
            else if (diagonalB->position.front() == test->position.front()
                && diagonalB->position.back() == test->position.back()) {
                diagonalB = test;
            }
        }

        Rule *rule = b == BLACK ? Rule::getBlack() : Rule::getWhite();
        if (rule->getThreeAndThree() == false) {
            check33(vertical);
            check33(horizontal);
            if (diagonalA->line.size() > 0) {
                check33(diagonalA);
            }
            if (diagonalB->line.size() > 0) {
                check33(diagonalB);
            }
//.........这里部分代码省略.........
开发者ID:lockpick,项目名称:Omok,代码行数:101,代码来源:State.cpp

示例2:

void			Session::AddRule(const Rule & rule) {
	if (rule.GetIgnore())
		m_ignoreRules.push_back(rule);
	else
		m_matchRules.push_back(rule);
}
开发者ID:tjyang,项目名称:bbwin,代码行数:6,代码来源:EventLog.cpp

示例3: addRule

void RuleBase::addRule(Rule ruleParam)
{
    rule.append("\t\t\t"+ruleParam.getRule()+"\n");
}
开发者ID:rafael2k,项目名称:creatvdigital,代码行数:4,代码来源:rulebase.cpp

示例4: cnt

int Rule::removeItem(Rule *&TRule, const int SurfN)
/**
  Given an item as a surface name,
  remove the surface from the Rule tree.
  - If the found leaf is on a
  @param TRule :: Top rule to down search
  @param SurfN :: Surface key number to remove
  @return Number of instances removed
*/
{
  int cnt(0);
  Rule *Ptr = TRule->findKey(SurfN);
  while (Ptr) {
    Rule *LevelOne = Ptr->getParent(); // Must work
    Rule *LevelTwo = (LevelOne) ? LevelOne->getParent() : 0;

    if (LevelTwo) /// Not the top level
    {
      // Decide which of the pairs is to be copied
      Rule *PObj =
          (LevelOne->leaf(0) != Ptr) ? LevelOne->leaf(0) : LevelOne->leaf(1);
      //
      LevelOne->setLeaves(0, 0); // Delete from Ptr, and copy
      const int side = (LevelTwo->leaf(0) != LevelOne) ? 1 : 0;
      LevelTwo->setLeaf(PObj, side);
    } else if (LevelOne) // LevelOne is the top rule
    {
      // Decide which of the pairs is to be copied
      Rule *PObj =
          (LevelOne->leaf(0) != Ptr) ? LevelOne->leaf(0) : LevelOne->leaf(1);

      PObj->setParent(0); /// New Top rule
      TRule = PObj;
      LevelOne->setLeaves(0, 0); // Delete from Ptr, and copy
      // Note we now need to delete this
      delete LevelOne;
    } else // Basic surf object
    {
      SurfPoint *SX = dynamic_cast<SurfPoint *>(Ptr);
      SX->setKeyN(0);
      SX->setKey(0);
      return cnt + 1;
    }
    delete Ptr;
    // delete LevelOne; // Shouldn't delete now we're deleting in setLeaf.
    Ptr = TRule->findKey(SurfN);
    cnt++;
  }
  return cnt;
}
开发者ID:mkoennecke,项目名称:mantid,代码行数:50,代码来源:Rules.cpp

示例5: while

void process_on_cpu_callable::operator ()(Nids *nids)
{
    vector<int> ac_rules;
    vector<int> matched_rules;
    Packet *packet;
    try {
        while (true) {
            nids->packets_queue_sem.wait();

            if (nids->threads_exit)
                break;

            {
                boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(nids->packets_queue_mutex);
                if (nids->packets_queue.size() <= 0)
                    continue;

                packet = nids->packets_queue.front();
                nids->packets_queue.pop();
            }

            bool found = false;

            matched_rules.clear();
            nids->analyze_header(packet, matched_rules);
            if (matched_rules.size() > 0) {
                bool ac_analyze_needed = false;

                //cout << "number of rules matched to packet header: " << matched_rules.size() << endl;
                ac_rules.clear();
                int k = 0;
                for (vector<int>::iterator it = matched_rules.begin(); it != matched_rules.end(); ++it) {
                    Rule *r = nids->rules[*it];

                    // payload analyzing is not needed, rule doesn't contain content or pcre options
                    if (r->get_content().size() <= 0 && nids->regex_dfa_offset[*it] == -1) {
                        boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(nids->analyzing_result_mutex);
                        nids->analyzing_result.push_back(*it);
                        found = true;
                        continue;
                    }

                    if (r->get_content().size() > 0) {
                        ac_analyze_needed = true;
                        ac_rules.push_back(*it);
                    }

                    if (nids->regex_dfa_offset[*it] != -1) {
                        ++k;
                        if (nids->analyze_payload_regex(packet, nids->regex_dfa_offset[*it])) {
                            boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(nids->analyzing_result_mutex);
                            nids->analyzing_result.push_back(*it);
                            found = true;
                        }
                    }
                }

                cout << "regex analyzed: " << k << " times" << endl;

                if (ac_analyze_needed) {
                    vector<int> result;
                    nids->analyze_payload_ac(packet, result);
                    if (result.size() > 0) {
                        for (vector<int>::iterator it = result.begin(); it != result.end(); ++it) {
                            if (find(ac_rules.begin(), ac_rules.end(), *it) != ac_rules.end()) {
                                boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(nids->analyzing_result_mutex);
                                nids->analyzing_result.push_back(*it);
                                found = true;
                            }
                        }
                    }
                }
            }

            if (found)
                nids->process_result_sem.post();

        }
    } catch (boost::thread_interrupted e) {
        BOOST_LOG_TRIVIAL(info) << "thread interrupted" << endl;
    }

    nids->threads_finished_sem.post();
    BOOST_LOG_TRIVIAL(trace) << "capture thread finished successfully" << endl;
}
开发者ID:xeppaka,项目名称:ganids,代码行数:85,代码来源:nids.cpp

示例6: floor

/**
 * @brief GUI::updateForLoadedIndex updates the information throughout GUI based on the active GUI
 * @param fileChosen
 */
void GUI::updateForLoadedIndex(QString fileChosen)
{
    if(granularityIndexMap->count(truncateVal) == 1)
    {
        evCont->updateIndexInfo(granularityIndexMap->at(truncateVal));
        return;
    }

    vector<XYPair*> *sPoints = pInstance->getActiveStableRegionPoints();


    if(fileChosen != NULL)
    {
        for(vector<XYPair*>::iterator i = sPoints->begin(); i != sPoints->end(); ++i)
        {
            set<Rule*> *allRules_nr = pInstance->getRulesForStableRegionPoint((*i),false,false);
            set<Rule*> *uRules = pInstance->getRulesForStableRegionPoint((*i),true,true);
            set<Rule*> *allRules = pInstance->getRulesForStableRegionPoint((*i),false,true);

            stableRegionRulesALL_NR->insert(std::pair<XYPair*,set<Rule*>*>((*i), allRules_nr));
            stableRegionRulesALL->insert(std::pair<XYPair*,set<Rule*>*>((*i), allRules));
            stableRegionRulesUNIQUE->insert(std::pair<XYPair*,set<Rule*>*>((*i), uRules));
        }
    }



    vector<Nugget*> *stableRegionPoints = new vector<Nugget*>;
    vector<Nugget*> truncatedRegions;


    Nugget *s;

    set<Rule*> *uRules;
    set<Rule*> *allRules;
    set<Rule*> *allRulesNR;

    
    float sup;
    float conf;
    
    int maxRulesU = 0;
    int minRulesU = std::numeric_limits<int>::max();
    int maxRulesA = 0;
    int minRulesA = std::numeric_limits<int>::max();

    int maxRulesU_nr = 0;
    int minRulesU_nr = std::numeric_limits<int>::max();
    int maxRulesA_nr = 0;
    int minRulesA_nr = std::numeric_limits<int>::max();

    
    float minConf = 1;
    float minSup = 1;
    float maxSup = 0;
    float maxConf = 0;
    
    float truncateSup;
    float truncateConf;
    float lastSup = -1;
    float lastConf = -1;
    Nugget* lastS;

    //Runtime granularity control
    //Combine the regions into truncateVal number of bins, to make them more easily visible

    //First iterate through and truncate values
    for(std::vector<XYPair*>::size_type i = 0; i != sPoints->size(); i++)
    {
        conf = sPoints->at(i)->getY();
        sup = sPoints->at(i)->getX();

        set<Rule*> *uniqueRulesCur;
        set<Rule*> *uniqueRulesCurNR;

        uRules = (*stableRegionRulesUNIQUE)[sPoints->at(i)];
        uniqueRulesCur = new set<Rule*>(uRules->begin(), uRules->end());
        uniqueRulesCurNR = new set<Rule*>(uRules->begin(), uRules->end());

        uniqueRulesLists->push_back(*uniqueRulesCur);


        allRules = (*stableRegionRulesALL)[sPoints->at(i)];
        allRulesNR = (*stableRegionRulesALL_NR)[sPoints->at(i)];

        truncateSup = floor(sup * truncateVal) / truncateVal;
        truncateConf = floor(conf * truncateVal) / truncateVal;

        //Create a temporary region with the truncated parameters
        s = new Nugget (colorMappings, truncateSup, truncateConf, allRules, uniqueRulesCur, allRulesNR, uniqueRulesCurNR);
        truncatedRegions.push_back(s);
    }


    //Resort the regions list, since the truncation breaks the original sorting
    std::sort(truncatedRegions.begin(),truncatedRegions.end() ,compP);
//.........这里部分代码省略.........
开发者ID:jdb175,项目名称:SPHINX,代码行数:101,代码来源:GUI.cpp

示例7: s

void
Configuration::readRules(QList<Rule> &rules, int *rules_version_return) {
    // IMPROVE constants.h
    // So wrong by the API specifications, but so right by the end results (no, I don't like doing it this way)
    QSettings s("ProfileMatic", "rules");
    // QSettings s("ajalkane", "ProfileMatic");
    Rule defaultRule = Rule::createDefaultRule();
    int rules_version = s.value("rulesVersion", 0).toInt();
    if (rules_version_return != 0) {
        *rules_version_return = rules_version;
    }
    int size = s.beginReadArray("rules");
    for (int i = 0; i < size; ++i) {
        s.setArrayIndex(i);

        Rule r;
        // r.ruleActive = s.value("ruleActive").toBool();

        _assignRuleId(r, s.value("ruleId"));
        r.setRuleName(s.value("ruleName").toString());
        QList<int> daysList;
        _readIntList(s, "days", "dayId", daysList);
        r.setDays(QSet<int>::fromList(daysList));

        QList<int> locationCells;
        _readIntList(s, "locationCells", "cellId", locationCells);
        r.setLocationCells(QSet<int>::fromList(locationCells));

        QList<QString> wlans;
        _readStringList(s, "wlans", "wlanName", wlans);
        r.setWlan(QSet<QString>::fromList(wlans));

        bool wlanTimeoutOk = false;
        int wlanTimeout = s.value("wlanTimeout").toInt(&wlanTimeoutOk);
        if (wlanTimeoutOk) {
            r.setWlanTimeout(wlanTimeout);
        }

        QString timeStartStr = s.value("timeStart").toString();
        QString timeEndStr = s.value("timeEnd").toString();
        r.setTimeStart(QTime::fromString(timeStartStr));
        r.setTimeEnd(rules_version == 0
                     ? r.getTimeStart().addSecs(60)
                     : QTime::fromString(timeEndStr));
        r.setProfile(s.value("profile").toString());
        r.setRestoreProfile(s.value("restoreProfile", false).toBool());
        bool profileVolumeOk = false;
        int profileVolume = s.value("profileVolume").toInt(&profileVolumeOk);
        if (profileVolumeOk) {
            r.setProfileVolume(profileVolume);
        }

        bool flightModeOk = false;
        int flightMode = s.value("flightMode").toInt(&flightModeOk);
        if (flightModeOk) {
            r.setFlightMode(flightMode);
        }
        r.setRestoreFlightMode(s.value("restoreFlightMode", false).toBool());

        bool powerSavingModeOk = false;
        int powerSavingMode = s.value("powerSavingMode").toInt(&powerSavingModeOk);
        if (powerSavingModeOk) {
            r.setPowerSavingMode(powerSavingMode);
        }
        r.setRestorePowerSavingMode(s.value("restorePowerSavingMode", false).toBool());

        bool blueToothModeOk = false;
        int blueToothMode = s.value("blueToothMode").toInt(&blueToothModeOk);
        if (blueToothModeOk) {
            r.setBlueToothMode(blueToothMode);
        }

        QList<PresenceRule *> presenceRules;
        _readPresenceRuleList(s, presenceRules);
        r.setPresenceRules(presenceRules);

        qDeleteAll(presenceRules);
        presenceRules.clear();

        r.setPresenceStatusMessage(s.value("presenceStatusMessage").toString());
        r.setRestorePresence(s.value("restorePresence", r.getRestorePresence()).toBool());
        r.setPresenceChangeType((Rule::PresenceChangeType) s.value("presenceChangeType", (int) Rule::CustomPresenceType).toInt());

        // Make sure default rule is always last, and is created if it does not exist
        if (!r.isDefaultRule()) {
            rules << r;
        } else {
            defaultRule.actionsFrom(r);
        }
        qDebug("Configuration: index %d, ruleId: %s, ruleName: %s", i, qPrintable(r.getRuleId()), qPrintable(r.getRuleName()));
    }
    rules << defaultRule;
    s.endArray();

    // Write rules to finalize conversion
    if (rules_version == 0) {
        qDebug("Writing rules after conversion");
        writeRules(rules);
    }
}
开发者ID:fmayet,项目名称:profilematic,代码行数:100,代码来源:configuration.cpp

示例8: getInstantiation

int Submodel::convertTimeAndExtentWith(const ASTNode* tcf, const ASTNode* xcf, const ASTNode* klmod)
{
  if (tcf==NULL && xcf==NULL) return LIBSBML_OPERATION_SUCCESS;
  Model* model = getInstantiation();
  if (model==NULL) {
    //getInstantiation sets its own error messages.
    return LIBSBML_OPERATION_FAILED;
  }
  ASTNode* tcftimes = NULL;
  ASTNode* tcfdiv = NULL;
  if (tcf != NULL) {
    tcftimes = new ASTNode(AST_TIMES);
    tcftimes->addChild(tcf->deepCopy());
    tcfdiv = new ASTNode(AST_DIVIDE);
    tcfdiv->addChild(tcf->deepCopy());
  }
  ASTNode* rxndivide = NULL;
  if (klmod != NULL) {
    rxndivide = new ASTNode(AST_DIVIDE);
    ASTNode rxnref(AST_NAME);
    rxndivide->addChild(rxnref.deepCopy());
    rxndivide->addChild(klmod->deepCopy());
  }
  List* allelements = model->getAllElements();
  for (unsigned int el=0; el<allelements->getSize(); el++) {
    SBase* element = static_cast<SBase*>(allelements->get(el));
    assert(element != NULL);
    ASTNode* ast1 = NULL;
    ASTNode* ast2 = NULL;
    Constraint* constraint = NULL;
    Delay* delay = NULL;
    EventAssignment* ea = NULL;
    InitialAssignment* ia = NULL;
    KineticLaw* kl = NULL;
    Priority* priority = NULL;
    RateRule* rrule = NULL;
    Rule* rule = NULL;
    Submodel* submodel = NULL;
    Trigger* trigger = NULL;
    string cf = "";
    //Reaction math will be converted below, in the bits with the kinetic law.  But because of that, we need to handle references *to* the reaction:  even if it has no kinetic law, the units have changed, and this needs to be reflected by the flattening routine.
    if (rxndivide != NULL && element->getTypeCode()==SBML_REACTION && element->isSetId()) {
      rxndivide->getChild(0)->setName(element->getId().c_str());
      for (unsigned int sube=0; sube<allelements->getSize(); sube++) {
        SBase* subelement = static_cast<SBase*>(allelements->get(sube));
        subelement->replaceSIDWithFunction(element->getId(), rxndivide);
      }
    }

    //Submodels need their timeConversionFactor and extentConversionFactor attributes converted.  We're moving top-down, so all we need to do here is fix the conversion factor attributes themselves, pointing them to new parameters if need be.
    if ((tcf !=NULL || xcf != NULL) && element->getTypeCode()==SBML_COMP_SUBMODEL) {
      submodel = static_cast<Submodel*>(element);
      if (tcf != NULL) {
        if (submodel->isSetTimeConversionFactor()) {
          createNewConversionFactor(cf, tcf, submodel->getTimeConversionFactor(), model);
          submodel->setTimeConversionFactor(cf);
        }
        else {
          submodel->setTimeConversionFactor(tcf->getName());
        }
      }
      if (xcf != NULL) {
        if (submodel->isSetExtentConversionFactor()) {
          createNewConversionFactor(cf, xcf, submodel->getExtentConversionFactor(), model);
          submodel->setExtentConversionFactor(cf);
        }
        else {
          submodel->setExtentConversionFactor(xcf->getName());
        }
      }
    }
    if (tcf==NULL) {
      if (klmod !=NULL && element->getTypeCode()==SBML_KINETIC_LAW) {
        kl = static_cast<KineticLaw*>(element);
        if (kl->isSetMath()) {
          ast1 = new ASTNode(AST_TIMES);
          ast1->addChild(klmod->deepCopy());
          ast1->addChild(kl->getMath()->deepCopy());
          kl->setMath(ast1);
          delete ast1;
        }
      }
    }
    else {
      // All math 'time' and 'delay' csymbols must still be converted.
      // Also, several constructs are modified directly.
      switch(element->getTypeCode()) {
        //This would be a WHOLE LOT SIMPLER if there was a 'hasMath' class in libsbml.  But even so, it would have to
        // handle the kinetic laws, rate rules, and delays separately.
      case SBML_KINETIC_LAW:
        //Kinetic laws are multiplied by 'klmod'.
        kl = static_cast<KineticLaw*>(element);
        ast1 = kl->getMath()->deepCopy();
        convertCSymbols(ast1, tcfdiv, tcftimes);
        if (klmod !=NULL) {
          kl = static_cast<KineticLaw*>(element);
          if (kl->isSetMath()) {
            ast2 = new ASTNode(AST_TIMES);
            ast2->addChild(klmod->deepCopy());
            ast2->addChild(ast1);
//.........这里部分代码省略.........
开发者ID:0u812,项目名称:roadrunner-backup,代码行数:101,代码来源:Submodel.cpp

示例9: main


//.........这里部分代码省略.........
		if (!buffer.compare("GOAL STATE")) {
			while (1) {
				getline(inputFile, inputBuffer);
				if (inputBuffer.size() == 0) break;
				buffer.clear();
				for (i = 0; i < inputBuffer.length(); i++) {
					if (inputBuffer[i] == '(')
					{
						tempName.clear();
						while (i < inputBuffer.length()) {
							i++;
							if (inputBuffer[i] == ')') break;
							else  tempName.push_back(inputBuffer[i]);

						}
					}
					else buffer.push_back(inputBuffer[i]);
				}
				if (!buffer.compare("ON_TABLE")) {
					for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
						if (!(*blockIter).name.compare(tempName)) {
							(*blockIter).onTable = true;
							(*blockIter).isOn = "TABLE";
						}
					}
				}
				if (!buffer.compare("CLEAR")) {
					for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
						if (!(*blockIter).name.compare(tempName)) {
							(*blockIter).clear = true;
						}
					}
				}
				if (!buffer.compare("ON")) {
					string tempName2;
					for (i = 0; i < tempName.length(); i++) {
						if (tempName.front() == ',') {
							tempName.erase(0, 1);
							break;
						}
						else {

							tempName2.push_back(tempName.front());
							tempName.erase(0, 1);
						}

					}
					
					for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
						if (!(*blockIter).name.compare(tempName)) {
							(*blockIter).isOn=tempName2;
						}
					}

				}

				if (!buffer.compare("HE")) {
					goalState.holding = "HE";
				}

				if (!buffer.compare("HOLDING")) {
					for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
						if (!(*blockIter).name.compare(tempName)) {
							(*blockIter).held = true;
							goalState.holding = (*blockIter).name;
						}
					}
				}
			}
			goalState.blockList = blockList;
		}

	}

		int min = 1000; //making no assumptings about the minimum s
	list<Rule*> currentPath;
	list<Rule*> bestPath;
	printState(startState);
	printState(goalState);

	State currentState = startState;

	backTrackStart(currentState, goalState, min, currentPath, bestPath);
	
	bool test = compareStates(startState, goalState);

	//print path: iterate, print rule, apply rule, print state

	Rule newRule;
	newRule.pickUpFlag=true;
	newRule.currentBlock=&(startState.blockList.front());

	newRule.printRule();
	newRule.applyRule(startState);
	printState(startState);
	test = compareStates(currentState,startState);
	
	return 0;

}
开发者ID:Rumsey-,项目名称:AI4,代码行数:101,代码来源:AI4.cpp

示例10: backTrack

void backTrack(Rule* currentRule, State &currentState, State &goalState, int &globalMin, list<Rule*> &currentPath, list<Rule*> &bestPath, list<State> &statePath) {

	list<Rule*> rulesList; //the rules which apply from this node
	Rule* ruleCurrent;
	int currentMin = 0;
	currentRule->applyRule(currentState);
	
	list<State>::iterator stateIter;
	currentRule->printRule();
	printState(currentState);

	currentPath.push_back(currentRule);
	

	for (stateIter=statePath.begin(); stateIter!=statePath.end(); stateIter++) {
		if (compareStates(currentState, (*stateIter))) {
			statePath.push_back(currentState);
			return;
		}
	}

	statePath.push_back(currentState);
	


	//if applying the current rule puts us over the current minimum, 
	//there is no need to explore further nodes from this branch 

	if (currentPath.size() > globalMin) {
		return;
	} 
	//however, if it is less than the global and we're in the goal, a new best is found
	if (compareStates(currentState,goalState)) {
		globalMin = currentPath.size();
		bestPath = currentPath;
		return;
	}

	//check the current state against all other states that the current application of rules has resulted in
	//this is to prevent the duplication or looping of states

	

	list<Block>::iterator blockIter;
	//find the applicable rules

	if (currentState.holding != NULL) { //if a block is being held, only rules where the block is put down apply
		for (blockIter = currentState.blockList.begin(); blockIter != currentState.blockList.end(); blockIter++) {
			//if the block is clear the held block can be put down here
			if ((*blockIter).clear) {
				Rule* newRule = new Rule;
				newRule->currentBlock = currentState.holding;
				newRule->onBlock = &(*blockIter);
				newRule->pickUpFlag = false;//putting down not picking up
				rulesList.push_back(newRule);
			}
		}
		//the block could always also be put on the table
		Rule* newRule = new Rule;
		newRule->currentBlock = currentState.holding;
		newRule->onBlock = NULL; //not putting it on a block but the table
		newRule->pickUpFlag = false; //putting down
		rulesList.push_back(newRule);

	}
	//otherwise, pick up a block
	else {
		for (blockIter = currentState.blockList.begin(); blockIter != currentState.blockList.end(); blockIter++) {
			//if the block is clear it can be picked up
			if ((*blockIter).clear) {
				(*blockIter).clear = false; //no longer clear, since it's picked up
				Rule* newRule = new Rule;
				newRule->currentBlock = &(*blockIter); //picking up the clear block that is found
				newRule->onBlock = NULL;
				newRule->pickUpFlag = true;//putting down not picking up
				rulesList.push_back(newRule);
			}
		}
	}
	
	

	

	//while there are rules to apply to this node, it does them and begins recursion
	while (rulesList.size() != 0) {
		ruleCurrent = rulesList.front();
		rulesList.pop_front();
		backTrack(ruleCurrent, currentState, goalState, globalMin, currentPath, bestPath, statePath);
		int foo = currentPath.size();
		currentPath.pop_back();
		foo = statePath.size();
		statePath.pop_back();
		ruleCurrent->undoRule(currentState);
	}

	return;

}
开发者ID:Rumsey-,项目名称:AI4,代码行数:99,代码来源:AI4.cpp

示例11: printProgram

void ProgramGrounder::ground() {

	//Create the dependency graph
	statementDependency->createDependencyGraph(predicateTable);

	// Create the component graph and compute an ordering among components.
	// Components' rules are classified as exit or recursive.
	// An rule occurring in a component is recursive if there is a predicate belonging
	// to the component in its positive body, otherwise it is said to be an exit rule.
	vector<vector<Rule*>> exitRules;
	vector<vector<Rule*>> recursiveRules;
	vector<unordered_set<index_object>> componentPredicateInHead;
	statementDependency->createComponentGraphAndComputeAnOrdering(exitRules, recursiveRules, componentPredicateInHead);

	if (Options::globalOptions()->isPrintRewrittenProgram())
		printProgram(exitRules, recursiveRules);

	// Ground each module according to the ordering:
	// For each component, each rule is either recursive or exit,
	// Exit rules are grounded just once, while recursive rules are grounded until no more knowledge is derived
	for (unsigned int component = 0; component < exitRules.size(); component++) {

#if DEBUG == 1
		cout<<"Component: "<<component;
		cout<<"\tExit rules: "<<exitRules[component].size();
		cout<<"\tRecursive rules: "<<recursiveRules[component].size()<<endl;
#endif

		// Ground exit rules
		for (Rule* r : exitRules[component]){
			inizializeSearchInsertPredicate(r);
			groundRule(r);
#ifdef DEBUG_RULE_TIME
			Timer::getInstance()->print();
#endif
		}

		// Ground recursive rules
		if (recursiveRules[component].size() > 0) {
			unsigned int n_rules = recursiveRules[component].size();
			bool found_something = false;

			// First iteration
			for (unsigned int i = 0; i < n_rules; i++) {
				Rule *rule=recursiveRules[component][i];
				inizializeSearchInsertPredicate(rule,componentPredicateInHead[component]);
				if(groundRule(rule))
					found_something=true;
			}
			while (found_something) {
				found_something = false;

				// Since in the first iteration search is performed in facts and no facts tables,
				// while in the next iteration search is performed in the delta table, it is needed
				// to keep track if the current iteration is the first or not.
				for (unsigned int i = 0; i < n_rules; i++) {
					Rule* r = recursiveRules[component][i];
					//If no more knowledge is derived the grounding of this component can stop
#if DEBUG == 1
					r->print();
#endif

					inizializeRecursiveCombinationPredicate(r,componentPredicateInHead[component]);
					for(unsigned i=0;i<pow(2,predicate_combination.size())-1;i++){
						computeRecursiveCombinationPredicate();
						nextSearchInsertPredicate(r,componentPredicateInHead[component]);
						if (groundRule(r)){
							found_something = true;
						}
					}
				}

				for (unsigned int i = 0; i < n_rules; i++)
					// Move the content of the delta table in the no fact table,
					// and fill delta with the content of the next delta table.
					swapInDelta(recursiveRules[component][i]);

			}
		}
	}

	// Constraints are grounded at the end
	for (unsigned int i = 0; i < statementDependency->getConstraintSize(); i++)
		if (statementDependency->getConstraint(i)->getSizeBody() > 0){
			Rule *rule=statementDependency->getConstraint(i);
			inizializeSearchInsertPredicate(rule);
			groundRule(rule);
		}

	//Print and simplify the rule
//	evaluator.printAndSimplify(predicateExtTable);


}
开发者ID:dave90,项目名称:Dlv_safe2,代码行数:94,代码来源:ProgramGrounder.cpp

示例12: convertToMask_

bool
Rules::isAllow(std::string resource, unsigned long idUser, unsigned long idOwner) {

	if (resource.size() < 1 || resource.empty()) {
		return false;
	}

	// Конвертируем в маску
	std::vector <unsigned long> mask = convertToMask_(resource);

	unsigned int i, currentMask, ruleSize;
	std::vector<Rule *>::iterator it;
	Rule * rule;

	// Перебираем правила
	for (it = rules_.begin(); it != rules_.end(); it++) {

		rule = (*it);

		currentMask = 0;
		ruleSize    = rule->get().size(); // Если правило заканчивается на * - мы подменяем размер

		// Ищем совпадение с маской
		for (i = 0; i < ruleSize; i++) {

			if (mask.size() == currentMask) {
				break;
			}

			if (currentMask >= 0 && i != currentMask) {
				break;
			}

			switch (rule->get().at(i)) {

				// 42 - символ * - заменяет любую строку
				case 42:

					/*
					 * Если есть совпадение и правило заканчивается на *
					 * очевидно, что дальше искать смысла нет.
					 *
					 * Например:
					 *
					 *   правило - view:*
					 *   маска   - view:wall:comment
					 *
					 * Очевидно, что в данном случае мы уже все разрешили
					 */

					if (i + 1 == rule->get().size()) {

						currentMask = mask.size();
						ruleSize    = currentMask;

						continue;

					}

					currentMask++;

				break;

				// 94 - символ ^ - разрешает только если idUser == idOwner
				case 94:

					if (idOwner != idUser) {
						continue;
					}

					currentMask++;

				break;

				default:

					if (mask[i] == rule->get().at(i)) {

						currentMask++;
						continue;

					}

					break;
			}

		}

		if (currentMask == mask.size() && currentMask == ruleSize) {
			return rule->isAllow();
		}

	}

	return false;

}
开发者ID:AlexeyParhomenko,项目名称:x-acl,代码行数:97,代码来源:Rules.cpp

示例13: while

void RuleOptionsDialog::loadFWObject(FWObject *o)
{
    obj = o;
    firewall = o;
    // use Firewall::cast to match both Firewall and Cluster
    while (!Firewall::cast(firewall)) firewall = firewall->getParent();
    platform = firewall->getStr("platform").c_str();
    string version = firewall->getStr("version");

    // build a map for combobox so visible combobox items can be localized
    QStringList route_options = getRouteOptions_pf_ipf(platform);
    QStringList route_load_options = getRouteLoadOptions_pf(platform);
    QStringList classify_options_ipfw = getClassifyOptions_ipfw(platform);

    Rule      *rule = dynamic_cast<Rule*>(o);
    FWOptions *ropt = rule->getOptionsObject();
    PolicyRule *policy_rule = PolicyRule::cast(rule);

    int wid=0;
    if (platform=="iptables") wid=1;
    if (platform=="ipf")      wid=2;
    if (platform=="pf")       wid=3;
    if (platform=="ipfw")     wid=4;
    if (platform=="pix" || platform=="fwsm")      wid=5;
    if (platform=="iosacl" || platform=="procurve_acl")   wid=6;
	if (platform=="junosacl") wid=7;

    m_dialog->wStack->widget(wid)->raise();
    m_dialog->wStack->setCurrentWidget(m_dialog->wStack->widget(wid));

    QStringList  logLevels=getLogLevels( obj->getStr("platform").c_str() );
    m_dialog->ipt_logLevel->clear();
    m_dialog->ipt_logLevel->addItems(getScreenNames(logLevels));
    m_dialog->ipf_logLevel->clear();
    m_dialog->ipf_logLevel->addItems(getScreenNames(logLevels));
    m_dialog->pix_logLevel->clear();
    m_dialog->pix_logLevel->addItems(getScreenNames(logLevels));

    QStringList logFacilities=getLogFacilities( obj->getStr("platform").c_str());
    m_dialog->ipf_logFacility->clear();
    m_dialog->ipf_logFacility->addItems(getScreenNames(logFacilities));
    QStringList limitSuffixes=getLimitSuffixes( obj->getStr("platform").c_str());
    m_dialog->ipt_limitSuffix->clear();
    m_dialog->ipt_limitSuffix->addItems(getScreenNames(limitSuffixes));

    m_dialog->ipt_hashlimit_suffix->clear();
    m_dialog->ipt_hashlimit_suffix->addItems(getScreenNames(limitSuffixes));

    fillInterfaces(m_dialog->ipt_iif);
    fillInterfaces(m_dialog->ipt_oif);
    fillInterfaces(m_dialog->ipf_route_opt_if);
    fillInterfaces(m_dialog->pf_route_opt_if);


    data.clear();

    if (platform=="iptables")
    {
        data.registerOption(m_dialog->ipt_logPrefix, ropt,  "log_prefix");
        data.registerOption(m_dialog->ipt_logLevel, ropt,
                             "log_level", logLevels);
        data.registerOption(m_dialog->ipt_nlgroup, ropt,  "ulog_nlgroup");

        data.registerOption(m_dialog->ipt_limit, ropt,  "limit_value");
        data.registerOption(m_dialog->ipt_limitSuffix, ropt,
                             "limit_suffix", limitSuffixes);
        data.registerOption(m_dialog->ipt_limit_not, ropt,  "limit_value_not");
        data.registerOption(m_dialog->ipt_burst, ropt,  "limit_burst");

        data.registerOption(m_dialog->ipt_connlimit, ropt,  "connlimit_value");
        data.registerOption(m_dialog->ipt_connlimit_above_not, ropt,
                            "connlimit_above_not");
        data.registerOption(m_dialog->ipt_connlimit_masklen, ropt,
                            "connlimit_masklen");

        data.registerOption(m_dialog->ipt_hashlimit, ropt,  "hashlimit_value");
        data.registerOption(m_dialog->ipt_hashlimit_suffix, ropt,
                            "hashlimit_suffix");
        data.registerOption(m_dialog->ipt_hashlimit_burst, ropt,
                            "hashlimit_burst");
        data.registerOption(m_dialog->cb_srcip, ropt,  "hashlimit_mode_srcip");
        data.registerOption(m_dialog->cb_dstip, ropt,  "hashlimit_mode_dstip");
        data.registerOption(m_dialog->cb_srcport, ropt,
                            "hashlimit_mode_srcport");
        data.registerOption(m_dialog->cb_dstport, ropt,
                            "hashlimit_mode_dstport");
        data.registerOption(m_dialog->ipt_hashlimit_dstlimit, ropt,
                            "hashlimit_dstlimit");
        data.registerOption(m_dialog->ipt_hashlimit_name, ropt,
                            "hashlimit_name");
        data.registerOption(m_dialog->ipt_hashlimit_size, ropt,
                            "hashlimit_size");
        data.registerOption(m_dialog->ipt_hashlimit_max, ropt,
                            "hashlimit_max");
        data.registerOption(m_dialog->ipt_hashlimit_expire, ropt,
                            "hashlimit_expire");
        data.registerOption(m_dialog->ipt_hashlimit_gcinterval, ropt,
                            "hashlimit_gcinterval");

        // in v3.0 attribute "assume fw is part of any" used to be a
//.........这里部分代码省略.........
开发者ID:sirius,项目名称:fwbuilder,代码行数:101,代码来源:RuleOptionsDialog.cpp

示例14: Rule

int
Rules::AddRule(RawMessageAddRule *messageRule, Rule** rule)
{
    *rule = NULL;
    int result;
    Rule *workRule = new Rule();
    if(workRule == NULL)
    {
        IOLog("can't create Rule");
        return -1;
    }

    if(workRule->Init(messageRule) == false)
    {
        delete workRule;
        return -1;
    }

    IOLockLock(lock);

    Rule *prev = NULL;
    Rule* current = this->root;
    while (current)
    {
        result = workRule->Compare(current);
        if(result == 0)
        {
            workRule->Release();
            current->Retain();
            *rule = current;
            result = 1;//rule exist
            break;
        }
        if(result > 0)
        {
            //insert before c
            workRule->next = current;
            workRule->prev = current->prev;

            current->prev = workRule;

            if(workRule->prev)
                workRule->prev->next = workRule;
            else
                this->root = workRule;//prev is root, replace

            //get rule id
            workRule->Retain();
            *rule = workRule;
            result = 0;

            clock_get_uptime(&lastChangedTime);
            break;
        }

        prev = current;
        current = current->next;
    }

    if(current == NULL)
    {
        if(prev)
            prev->next = workRule;
        else
            this->root = workRule;

        //get rule id
        workRule->Retain();
        *rule = workRule;
        result = 0;
    }

//unlock:
    IOLockUnlock(lock);
    return result;
}
开发者ID:heavilessrose,项目名称:yafw4osx,代码行数:76,代码来源:rule.cpp

示例15: typeid

/**
 * Growth phase of a rule induction
 * @param rule rule to be built
 * @param covered set of examples covered by current rule
 * @param uncoveredPositives set of examples not covered by current set of rules
 * @param ruleQualityMeasure rule quality measure
 */
void SequentialCoveringWithPreferences::growRule(Rule& rule, SetOfExamples& covered, SetOfExamples uncoveredPositives, RuleQualityMeasure& ruleQualityMeasure, bool useSpecifiedOnly, KnowledgeRule* knowRule)
{
    Precision prec;
    ElementaryCondition bestCondition;
    double decClass = rule.getDecisionClass();
    RuleEvaluationResult rer;
    double coveredCount = 0, prevCoveredCount = 0;
    bool isEntropy = typeid (ruleQualityMeasure) == typeid (NegConditionalEntropy);
    bool shouldBreak = false, unspecifiedChecked = false, checkUnspecified = true;

    while (uncoveredPositives.size() > 0)
    {
        bestCondition = findBestCondition(rule, decClass, covered, uncoveredPositives, ruleQualityMeasure, isEntropy,  useSpecifiedOnly, knowRule);

        unspecifiedChecked = false;
        checkUnspecified = true;
        shouldBreak = false;
        while(!unspecifiedChecked || checkUnspecified)
        {
			if(bestCondition.getAttributeIndex() == -1)
				shouldBreak = true;

			//checking stop criterion
			if(!shouldBreak)
			{
				rer = RuleQualityMeasure::EvaluateCondition(covered, bestCondition, decClass);
				if (rer.n == 0)
				{
					rule.addCondition(bestCondition);
					shouldBreak = true;
					checkUnspecified = false;
					unspecifiedChecked = true;
				}
				coveredCount = rer.p + rer.n;
				if(coveredCount == prevCoveredCount)
					shouldBreak = true;
			}

			//if it wasn't possible to find best condition from specified, then if conditions are "expandable"
			//and "useSpecifiedOnly" (global, not this method parameter) is not true, try to use other conditions
			if(!unspecifiedChecked && shouldBreak && knowledge->getAllowedConditions()[decClass].isExpandable() && !knowledge->isUseSpecifiedOnly() && useSpecifiedOnly)
			{
	        	bestCondition = findBestCondition(rule, decClass, covered, uncoveredPositives, ruleQualityMeasure, isEntropy, false, knowRule);
	        	shouldBreak = false;
			}
			else
				checkUnspecified = false;

			unspecifiedChecked = true;
        }

        if(shouldBreak)
        	break;

        covered = getCoveredExamples(bestCondition, covered);
        uncoveredPositives = getCoveredExamples(bestCondition, uncoveredPositives);
        prevCoveredCount = coveredCount;
        rule.addCondition(bestCondition);
        //rule.addConditionAndOptimize(bestCondition);
        //cout << "Added condition: " << bestCondition.toString(covered.getDataSet()) << endl;
    }
}
开发者ID:rforge,项目名称:crules,代码行数:69,代码来源:SequentialCoveringWithPreferences.cpp


注:本文中的Rule类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。