Ejemplo n.º 1
0
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);
            }
            if (count33 > 1) {
                isForbidden = true;
            }
        }
    }
    return isForbidden;
}
Ejemplo n.º 2
0
void			Session::AddRule(const Rule & rule) {
	if (rule.GetIgnore())
		m_ignoreRules.push_back(rule);
	else
		m_matchRules.push_back(rule);
}
Ejemplo n.º 3
0
void RuleBase::addRule(Rule ruleParam)
{
    rule.append("\t\t\t"+ruleParam.getRule()+"\n");
}
Ejemplo n.º 4
0
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;
}
Ejemplo n.º 5
0
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;
}
Ejemplo n.º 6
0
/**
 * @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);


    //Now merge any redundant regions created by the truncation, so that we don't lose any rules
    for(std::vector<Nugget*>::size_type i = 0; i != truncatedRegions.size(); i++)
    {

        conf = truncatedRegions[i]->confidence;
        sup = truncatedRegions[i]->support;

        //Get useful parameter interval
        minConf = std::max(0.0f, std::min(conf-1/truncateVal, minConf));
        maxConf = std::min(1.0f, std::max(conf, maxConf));
        minSup = std::max(0.0f,  std::min(sup-1/truncateVal, minSup));
        maxSup = std::min(1.0f, std::max(sup, maxSup));

        //now combine regions within same bin by checking against last values
        if(sup != lastSup || conf != lastConf)
        {
            //If this is a distinct region, add it to the list
            lastS = truncatedRegions[i];
            stableRegionPoints->push_back(lastS);
        }
        else
        {
            //Otherwise just merge it into the last region

            //But first we handle redundancies
            set<Rule*> *rulesToAdd = new set<Rule*>;
            for(set<Rule*>::iterator j = truncatedRegions[i]->uniqueRules->begin(); j != truncatedRegions[i]->uniqueRules->end(); ++j)
            {
                Rule *rule = *j;

                //if the rule has a dominating point, it can only be added as a rule if its dominating point's support or confidence
                //do not fall within this truncated region. Otherwise, its dominant point should be added instead later on.
                if ((rule->getDominantPointSimple() == NULL) && (rule->getDominantPointStrict() == NULL))
                {
                    rulesToAdd->insert(rule);
                }
                else if((rule->getDominantPointSimple() == NULL) && (rule->getDominantPointStrict() != NULL))
                {
                    if (rule->getDominantPointStrict()->getX() <= sup-1/truncateVal || rule->getDominantPointStrict()->getY() <= conf-1/truncateVal) rulesToAdd->insert(rule);
                }
                else if ((rule->getDominantPointSimple() != NULL) && (rule->getDominantPointStrict() == NULL))
                {
                    if ((rule->getDominantPointSimple()->getX() <= sup-1/truncateVal) || (rule->getDominantPointSimple()->getY() <= conf-1/truncateVal)) rulesToAdd->insert(rule);
                }
                else  if (((rule->getDominantPointSimple()->getX() <= sup-1/truncateVal) || (rule->getDominantPointSimple()->getY() <= conf-1/truncateVal))
                          && ((rule->getDominantPointStrict()->getX() <= sup-1/truncateVal) || (rule->getDominantPointStrict()->getY() <= conf-1/truncateVal))){
                    rulesToAdd->insert(rule);
                }
            }


            lastS->uniqueRules->insert(truncatedRegions[i]->uniqueRules->begin(), truncatedRegions[i]->uniqueRules->end());
            lastS->uniqueRules_nr->insert(rulesToAdd->begin(), rulesToAdd->end());

            if(truncatedRegions[i]->allRules->size() > lastS->allRules->size())
            {
                lastS->allRules = truncatedRegions[i]->allRules;
            }

            if(truncatedRegions[i]->allRules_nr->size() > lastS->allRules_nr->size())
            {
                lastS->allRules_nr = truncatedRegions[i]->allRules_nr;
            }

            //And now delete it, since it has no purpose
            delete truncatedRegions[i];
        }
        lastSup = sup;
        lastConf = conf;

        //get min and max rules
        maxRulesU = std::max((int)lastS->uniqueRules->size(), maxRulesU);
        minRulesU = std::min((int)lastS->uniqueRules->size(), minRulesU);
        maxRulesA = std::max((int)lastS->allRules->size(), maxRulesA);
        minRulesA = std::min((int)lastS->allRules->size(), minRulesA);

        maxRulesU_nr = std::max((int)lastS->uniqueRules_nr->size(), maxRulesU_nr);
        minRulesU_nr = std::min((int)lastS->uniqueRules_nr->size(), minRulesU_nr);
        maxRulesA_nr = std::max((int)lastS->allRules_nr->size(), maxRulesA_nr);
        minRulesA_nr = std::min((int)lastS->allRules_nr->size(), minRulesA_nr);

    }


    IndexUpdateEvent newIndexLoaded;
    newIndexLoaded.allInterval = pair<int,int>(minRulesA, maxRulesA);
    newIndexLoaded.allInterval_nr = pair<int,int>(minRulesA_nr, maxRulesA_nr);
    newIndexLoaded.confInterval = pair<double,double>(minConf, maxConf);
    newIndexLoaded.supInterval = pair<double,double>(minSup, maxSup);
    newIndexLoaded.stableRegions = stableRegionPoints;
    newIndexLoaded.uniqueInterval = pair<int,int>(minRulesU, maxRulesU);
    newIndexLoaded.uniqueInterval_nr = pair<int,int>(minRulesU_nr, maxRulesU_nr);
    newIndexLoaded.attributes = pInstance->getAttributes();

    granularityIndexMap->insert(std::pair<float,IndexUpdateEvent>(truncateVal, newIndexLoaded));
    evCont->updateIndexInfo(newIndexLoaded);

    if(fileChosen != NULL)
    {
        this->setWindowTitle(QString("PARAS GUI - ").append(fileChosen));
        this->close->setEnabled(true);
    }
}
Ejemplo n.º 7
0
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);
    }
}
Ejemplo n.º 8
0
void QosProcessor_Test::testAddDeleteRules()
{


    ruleDB_t *new_rules = NULL;

    try
    {

        const string ruleFile = DEF_SYSCONFDIR "/example_rules1.xml";

        log->log(ch, "starting testAddRules rules_file:%s", ruleFile.c_str());

        new_rules = rulem->parseRules(ruleFile);

        log->log(ch, "numRules %d", (int) new_rules->size() );

        qosProcessorPtr->checkRules(new_rules, evnt);

        log->log(ch, "numRules %d", (int) new_rules->size() );

        ruleDBIter_t it;
        for (it = new_rules->begin(); it != new_rules->end(); ++it)
        {
            Rule *rule = *it;
            log->log(ch, "Rule %s.%s - Status:%d", rule->getSetName().c_str(), rule->getRuleName().c_str(), (int) rule->getState());
        }

		cout << "after checking the rules" << endl;

        qosProcessorPtr->addRules(new_rules, evnt);

        for (it = new_rules->begin(); it != new_rules->end(); ++it)
        {
            Rule *rule = *it;
            log->log(ch, "Rule %s.%s - Status:%d", rule->getSetName().c_str(), rule->getRuleName().c_str(), (int) rule->getState());
            CPPUNIT_ASSERT( rule->getState() == RS_ACTIVE );
        }

		cout << "after adding the rules" << endl;

        qosProcessorPtr->delRules(new_rules, evnt);

        for (it = new_rules->begin(); it != new_rules->end(); ++it)
        {
            Rule *rule = *it;
            log->log(ch, "Rule %s.%s - Status:%d", rule->getSetName().c_str(), rule->getRuleName().c_str(), (int) rule->getState());
            CPPUNIT_ASSERT( rule->getState() == RS_DONE );
        }

		cout << "after deleting the rules" << endl;

        // Release the memory created.
        for (it = new_rules->begin(); it != new_rules->end(); ++it)
        {
            Rule *rule = *it;
            saveDelete(rule);
        }

        saveDelete(new_rules);

        log->log(ch, "ending testAddRules");

    }
    catch (Error &e)
    {
        cout << "Error:" << e.getError() << endl;
    }


}
Ejemplo n.º 9
0
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);
            kl->setMath(ast2);
            delete ast2;
          }
        }
        else {
          kl->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_DELAY:
        //Delays are multiplied by the time conversion factor.
        delay = static_cast<Delay*>(element);
        if (delay->isSetMath()) {
          ast1 = delay->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          tcftimes->addChild(ast1);
          delay->setMath(tcftimes);
          tcftimes->removeChild(1);
        }
        break;
      case SBML_RATE_RULE:
        //Rate rules are divided by the time conversion factor.
        rrule = static_cast<RateRule*>(element);
        if (rrule->isSetMath()) {
          ast1 = rrule->getMath()->deepCopy();
          tcfdiv->insertChild(0, rrule->getMath()->deepCopy());
          rrule->setMath(tcfdiv);
          tcfdiv->removeChild(0);
        }
        //Fall through to:
      case SBML_ASSIGNMENT_RULE:
      case SBML_ALGEBRAIC_RULE:
        //Rules in general need csymbols converted.
        rule = static_cast<Rule*>(element);
        if (rule->isSetMath()) {
          ast1 = rule->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          rule->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_EVENT_ASSIGNMENT:
        //Event assignments need csymbols converted.
        ea = static_cast<EventAssignment*>(element);
        if (ea->isSetMath()) {
          ast1 = ea->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          ea->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_INITIAL_ASSIGNMENT:
        //Initial assignments need csymbols converted.
        ia = static_cast<InitialAssignment*>(element);
        if (ia->isSetMath()) {
          ast1 = ia->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          ia->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_CONSTRAINT:
        //Constraints need csymbols converted.
        constraint = static_cast<Constraint*>(element);
        if (constraint->isSetMath()) {
          ast1 = constraint->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          constraint->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_PRIORITY:
        //Priorities need csymbols converted.
        priority = static_cast<Priority*>(element);
        if (priority->isSetMath()) {
          ast1 = priority->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          priority->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_TRIGGER:
        //Triggers need csymbols converted.
        trigger = static_cast<Trigger*>(element);
        if (trigger->isSetMath()) {
          ast1 = trigger->getMath()->deepCopy();
          convertCSymbols(ast1, tcfdiv, tcftimes);
          trigger->setMath(ast1);
          delete ast1;
        }
        break;
      default:
        //Do nothing!  If we wanted to call a plugin routine, this would be the place.  The only other alternative is to #ifdef some code in here that deals with the math-containing package objects explicitly.  Which might be the best option, all told.
        break;
      }
    }
  }

  delete allelements;

  return LIBSBML_OPERATION_SUCCESS;
}
Ejemplo n.º 10
0
Archivo: AI4.cpp Proyecto: Rumsey-/AI4
int main(int argc, char* argv[])
{
	if (argc != 2) {
		cout << "Usage: hw4 input.txt" << endl;
		return -1;
	}

	ifstream inputFile(argv[1]);
	//check valid inputfile
	if (!inputFile.is_open()) {
		cout << "Unable to open file" << endl;
		return -1;
	}

	string inputBuffer;
	string buffer;
	string tempName;

	list<Block> blockList;
	list<Block>::iterator blockIter;

	State startState;
	startState.holding=NULL;
	State goalState;
	goalState.holding=NULL;

	int i, j;

	while (getline(inputFile, inputBuffer)) {
		buffer.clear();
		for (i = 0; i < inputBuffer.length(); i++) {
			if (inputBuffer[i] == ':') break;
			else buffer.push_back(inputBuffer[i]);
		}
		if (!buffer.compare("BLOCKS")) {
			getline(inputFile, inputBuffer);

			istringstream iss(inputBuffer); //creating a stringstream from the gotten line

			vector<string> tokens;
			copy(istream_iterator<string>(iss), //tokenize the gotten line using istream_iterator
				istream_iterator<string>(),
				back_inserter(tokens));

			//build block list here
			for (i = 0; i < tokens.size(); i++) {
				buffer = tokens[i];
				tempName.clear();
				for (j = 0; j < buffer.length (); j++) {
					if (buffer[j] == ',') break;
					else  tempName.push_back(buffer[j]);
					
				}
				Block newBlock;
				newBlock.name = tempName;
				blockList.push_back(newBlock);

			}
		}

		//build initial state
		if (!buffer.compare("INITIAL 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;
						}
					}
				}
				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).onTable=false;
						}
					}

					(*blockIter).isOn=tempName2;

				}

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

				if (!buffer.compare("HOLDING")) {
					for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
						if (!(*blockIter).name.compare(tempName)) {
							(*blockIter).held = true;
							startState.holding = (*blockIter).name;
						}
					}
				}
			}
			startState.blockList = blockList;
		}
		for (blockIter = blockList.begin(); blockIter != blockList.end(); blockIter++) {
			(*blockIter).clear = false;
			(*blockIter).held = false;
			(*blockIter).onTable = false;
		}
		//build goal state
		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;

}
Ejemplo n.º 11
0
Archivo: AI4.cpp Proyecto: Rumsey-/AI4
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;

}
Ejemplo n.º 12
0
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);


}
Ejemplo n.º 13
0
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;

}
Ejemplo n.º 14
0
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
        // checkbox and therefore stored as boolean in the rule
        // options. Old "on" maps to the new "on", which means old "True"
        // maps to "1". Old "off" maps to "use global" though.
        string old_val = ropt->getStr("firewall_is_part_of_any_and_networks");
        if (old_val == "True") ropt->setStr("firewall_is_part_of_any_and_networks", "1");
        if (old_val == "False") ropt->setStr("firewall_is_part_of_any_and_networks", "");

        QStringList threeStateMapping;
        threeStateMapping.push_back(QObject::tr("Follow global setting"));
        threeStateMapping.push_back("");

        threeStateMapping.push_back(QObject::tr("On"));
        threeStateMapping.push_back("1");

        threeStateMapping.push_back(QObject::tr("Off"));
        threeStateMapping.push_back("0");

        data.registerOption(m_dialog->ipt_assume_fw_is_part_of_any, ropt,
                            "firewall_is_part_of_any_and_networks",
                            threeStateMapping);
        data.registerOption(m_dialog->ipt_stateless, ropt,  "stateless");

        data.registerOption(m_dialog->ipt_mark_connections, ropt,
                            "ipt_mark_connections");

        data.registerOption(m_dialog->classify_str, ropt, "classify_str");

        // Route
        data.registerOption(m_dialog->ipt_iif, ropt, "ipt_iif" );
        data.registerOption(m_dialog->ipt_oif, ropt, "ipt_oif" );
        data.registerOption(m_dialog->ipt_gw, ropt, "ipt_gw" );
        data.registerOption(m_dialog->ipt_continue, ropt, "ipt_continue" );
        data.registerOption(m_dialog->ipt_tee, ropt, "ipt_tee");

        FWObject *o = policy_rule->getTagObject();
        m_dialog->iptTagDropArea->setObject(o);
        m_dialog->iptTagDropArea->update();
    }


    if (platform=="ipf")
    {
        data.registerOption(m_dialog->ipf_logFacility, ropt,
                            "ipf_log_facility", logFacilities);
        data.registerOption(m_dialog->ipf_logLevel, ropt,
                            "log_level", logLevels);
        data.registerOption(m_dialog->ipf_masq_icmp, ropt,
                            "ipf_return_icmp_as_dest");
        data.registerOption(m_dialog->ipf_stateless, ropt,  "stateless");
        data.registerOption(m_dialog->ipf_keep_frags, ropt,  "ipf_keep_frags");

        // Route
        data.registerOption(m_dialog->ipf_route_option, ropt,
                            "ipf_route_option", route_options);
        data.registerOption(m_dialog->ipf_route_opt_if, ropt,
                            "ipf_route_opt_if");
        data.registerOption(m_dialog->ipf_route_opt_addr, ropt,
                            "ipf_route_opt_addr");
    }

    if (platform=="pf")
    {
        bool ge_4_5 = XMLTools::version_compare(version, "4.5")>=0;

        m_dialog->pf_no_sync->setEnabled(ge_4_5);
        m_dialog->pf_pflow->setEnabled(ge_4_5);
        
        data.registerOption(m_dialog->pf_logPrefix, ropt,
                            "log_prefix");
        data.registerOption(m_dialog->pf_stateless, ropt,
                            "stateless");
        data.registerOption(m_dialog->pf_keep_state, ropt,
                            "pf_keep_state");
        data.registerOption(m_dialog->pf_no_sync, ropt,
                            "pf_no_sync");
        data.registerOption(m_dialog->pf_pflow, ropt,
                            "pf_pflow");
        data.registerOption(m_dialog->pf_sloppy_tracker, ropt,
                            "pf_sloppy_tracker");
        data.registerOption(m_dialog->pf_rule_max_state, ropt,
                            "pf_rule_max_state");
        data.registerOption(m_dialog->pf_source_tracking, ropt,
                            "pf_source_tracking");
        data.registerOption(m_dialog->pf_max_src_nodes, ropt,
                            "pf_max_src_nodes");
        data.registerOption(m_dialog->pf_max_src_states, ropt,
                            "pf_max_src_states");
        data.registerOption(m_dialog->pf_max_src_conn, ropt,
                            "pf_max_src_conn");
        data.registerOption(m_dialog->pf_overload_table, ropt,
                            "pf_max_src_conn_overload_table");
        data.registerOption(m_dialog->pf_flush, ropt,
                            "pf_max_src_conn_flush");
        data.registerOption(m_dialog->pf_global, ropt,
                            "pf_max_src_conn_global");
        data.registerOption(m_dialog->pf_max_src_conn_rate_num, ropt,
                            "pf_max_src_conn_rate_num");
        data.registerOption(m_dialog->pf_max_src_conn_rate_seconds, ropt,
                            "pf_max_src_conn_rate_seconds");
        data.registerOption(m_dialog->pf_modulate, ropt,
                            "pf_modulate_state");
        data.registerOption(m_dialog->pf_synproxy, ropt,
                            "pf_synproxy");

        // Tag
        FWObject *o = policy_rule->getTagObject();
        m_dialog->pfTagDropArea->setObject(o);
        m_dialog->pfTagDropArea->update();

        // Classify
        data.registerOption(m_dialog->pf_classify_str, ropt, "pf_classify_str");

        // Route
        data.registerOption(m_dialog->pf_fastroute, ropt, "pf_fastroute");
        data.registerOption(m_dialog->pf_route_load_option, ropt,
                            "pf_route_load_option", route_load_options);
        data.registerOption(m_dialog->pf_route_option, ropt, "pf_route_option",
                            route_options);
        data.registerOption(m_dialog->pf_route_opt_if, ropt, "pf_route_opt_if");
        data.registerOption(m_dialog->pf_route_opt_addr, ropt, "pf_route_opt_addr");
    }

    if (platform=="ipfw")
    {
        data.registerOption(m_dialog->ipfw_stateless, ropt, "stateless");

/* #2367 */
        // Classify
        data.registerOption(m_dialog->ipfw_classify_method, ropt,
                            "ipfw_classify_method", classify_options_ipfw);
        data.registerOption(m_dialog->usePortNum, ropt, "ipfw_pipe_queue_num");
    }

    if (platform=="iosacl" || platform=="procurve_acl")
    {
        data.registerOption(m_dialog->iosacl_add_mirror_rule,
                            ropt, "iosacl_add_mirror_rule");
    }

    if (platform=="pix" || platform=="fwsm")
    {
        string vers = "version_" + version;
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
        if (Resources::platform_res[platform.toAscii().constData()]->getResourceBool(
              "/FWBuilderResources/Target/options/" +
              vers + "/pix_rule_syslog_settings"))
#else
        if (Resources::platform_res[platform.toLatin1().constData()]->getResourceBool(
              "/FWBuilderResources/Target/options/" +
              vers + "/pix_rule_syslog_settings"))
#endif
        {
            m_dialog->pix_disable_rule_log->setEnabled(true);
            m_dialog->pix_logLevel->setEnabled(true);
            m_dialog->pix_log_interval->setEnabled(true);

            data.registerOption(m_dialog->pix_disable_rule_log, ropt,
                                "disable_logging_for_this_rule");
            data.registerOption(m_dialog->pix_logLevel, ropt,
                                "log_level",logLevels);
            data.registerOption(m_dialog->pix_log_interval, ropt,
                                "log_interval");
        } else
        {
            m_dialog->pix_disable_rule_log->setEnabled(false);
            m_dialog->pix_logLevel->setEnabled(false);
            m_dialog->pix_log_interval->setEnabled(false);
        }

    }

    if (platform=="junosacl")
    {
        data.registerOption(m_dialog->counterLineEdit, ropt, "counter_name");
    }



    init = true;
    data.loadAll();

    m_dialog->pf_max_src_nodes->setEnabled(
        m_dialog->pf_source_tracking->isChecked());
    m_dialog->pf_max_src_states->setEnabled(
        m_dialog->pf_source_tracking->isChecked());


    connlimitAboveLabelChange();
    limitLabelChange();

    //apply->setEnabled(false);
    init=false;
}
Ejemplo n.º 15
0
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;
}
/**
 * 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;
    }
}
Ejemplo n.º 17
0
bool RuleSet::FixRules() {
  isFixed = true;
  for (int i=0; i<nRules; i++) {
    Rule *r = rules[i]; 
    if (r->Id() && r->Id()->RuleNo() < 0) {
      Message(MSG_WARNING, "help rule", r->Name(), "is not defined");
      isFixed = false;
    } else 
      r->ResolveHelpRules();
    for (RuleTerm *rt = r->FirstRuleTerm(); rt; rt = rt->Next())
      if (rt->GetJump() && rt->GetJump()->GetId()->GetRuleIndex() <= i) {
	Message(MSG_WARNING, r->Name(), "jumps backwards");
	isFixed = false;
      }
    if (!r->IsHelpRule()) {
      if (!r->CategoryName()) {
	Message(MSG_WARNING, "rule", r->Name(), "has no category");
	//isFixed = false;
      } else {
	Category *cat = FindCategory(r->CategoryName());
	if (!cat) {
	  Message(MSG_WARNING, "category", r->CategoryName(), "never declared");
	  isFixed = false;
	} else 
	  for (RuleTerm *rt = r->FirstRuleTerm(); rt; rt = rt->Next())
	    rt->category = cat;
      }
      if (r->FirstRuleTerm() && !r->FirstRuleTerm()->IsScrutinizing() &&
	  r->FirstRuleTerm()->GetInfo()) {
	Message(MSG_WARNING, r->Name(), ", only scrutinizing rules can have info");
	isFixed = false;
      }
    }
  }
  return isFixed;
}
/**
 * Generates list of rules for given decision class
 * @param examples training set on which the induction is based
 * @param rqmGrow rule qualisty measure used in growth phase
 * @param rqmPrune rule qualisty measure used in pruning phase
 * @param decClass decision class value
 * @return ist of rules for the decision class
 */
list<Rule> SequentialCoveringWithPreferences::generateRulesForClass(SetOfExamples& examples, RuleQualityMeasure& rqmGrow, RuleQualityMeasure& rqmPrune, double decClass)
{
    list<Rule> ruleSet;
    SetOfExamples uncoveredPositives(examples.getExamplesForDecAtt(decClass));
    P = uncoveredPositives.getSumOfWeights();
    N = examples.getSumOfWeights() - P;
    double apriori = P / (P + N);
    Precision precision;
    vector<list<ElementaryCondition> >::iterator itVec;

    SetOfConditions& allowedConditions = knowledge->getAllowedConditions()[decClass];

    bool useSpecifiedOnly = allowedConditions.getConditions().size() > 0;
    int rulesFromSpecifiedConditionsCount = 0;

    //insert specified rules to ruleset and compute uncoveredPositives
    Rule* tempRule;
    for(list<KnowledgeRule>::iterator it = knowledge->getAllowedRules()[decClass].begin(); it != knowledge->getAllowedRules()[decClass].end(); it++)
    {
    	tempRule = getRuleFromKnowledgeRule(*it, true);	//create rule with only fixed and required conditions to compute uncoveredPositives

    	if(tempRule->getConditions().size() > 0)
    	{
			SetOfExamples covered(getCoveredExamples(*tempRule, examples));
			uncoveredPositives = uncoveredPositives - covered;
    	}

    	delete tempRule;

    	tempRule = getRuleFromKnowledgeRule(*it, false);

    	tempRule->setConfidenceDegree(rqmPrune.EvaluateRuleQuality(examples, *tempRule));
		ruleSet.push_back(*tempRule);

    	delete tempRule;
    }

    //try to improve specified rules
    list<KnowledgeRule>::iterator itKnowRule = knowledge->getAllowedRules()[decClass].begin();
    for(list<Rule>::iterator itRule = ruleSet.begin(); itRule != ruleSet.end() && uncoveredPositives.size() > 0; itRule++, itKnowRule++)
	{
    	if(!itKnowRule->getConditions().isExpandable())
    		continue;	//if not expandable, don't try to improve it

    	SetOfExamples covered(examples);
    	Rule rule(*itRule);

    	//temporarily add conditions from rule to "allowed conditions" so their "fixed" and "required" properties are respected
    	allowedConditions.getConditions().insert(allowedConditions.getConditions().end(), itKnowRule->getConditions().getConditions().begin(),
    			itKnowRule->getConditions().getConditions().end());

    	growRule(rule, covered, uncoveredPositives, rqmGrow, useSpecifiedOnly, &(*itKnowRule));
    	pruneRule(rule, examples, rqmPrune);

        covered = getCoveredExamples(rule, examples);

        if(precision.EvaluateRuleQuality(covered, *itRule) <= apriori && rulesFromSpecifiedConditionsCount >= allowedConditions.getRulesAtLeast())
        {
        	//if adding new rule from the specified conditions will give worse precision than apriori
        	//then if not "useSpecifiedOnly", start using also other conditions
        	if(useSpecifiedOnly && !knowledge->isUseSpecifiedOnly())
        		useSpecifiedOnly = false;
        }
        else
        {
			uncoveredPositives = uncoveredPositives - covered;
			rule.setConfidenceDegree(rqmPrune.EvaluateRuleQuality(examples, rule));
			*itRule = rule;
			if(useSpecifiedOnly)
				rulesFromSpecifiedConditionsCount++;
        }

        //remove temporarily added conditions
        list<KnowledgeCondition>::iterator remBegin = allowedConditions.getConditions().end();
        for(unsigned int i = 0; i < itKnowRule->getConditions().getConditions().size(); i++) remBegin--;
        allowedConditions.getConditions().erase(remBegin, allowedConditions.getConditions().end());
	}

    //create new rules
    if(knowledge->getAllowedRules()[decClass].size() == 0 || !knowledge->isUseSpecifiedOnly())
    {
		while (uncoveredPositives.size() > 0)
		{
			SetOfExamples covered(examples);
			Rule rule;
			rule.setDecisionClass(decClass);
			growRule(rule, covered, uncoveredPositives, rqmGrow, useSpecifiedOnly);
			pruneRule(rule, examples, rqmPrune);
			covered = getCoveredExamples(rule, examples);

			if(precision.EvaluateRuleQuality(covered, rule) <= apriori && rulesFromSpecifiedConditionsCount >= allowedConditions.getRulesAtLeast())
			{
				//if adding new rule from the specified conditions will give worse precision than apriori
				//then if not "useSpecifiedOnly", start using also other conditions
				if(useSpecifiedOnly && !knowledge->isUseSpecifiedOnly())
					useSpecifiedOnly = false;
				else
					break;
			}
			else
			{
				uncoveredPositives = uncoveredPositives - covered;
				rule.setConfidenceDegree(rqmPrune.EvaluateRuleQuality(examples, rule));
				ruleSet.push_back(rule);
				if(useSpecifiedOnly)
					rulesFromSpecifiedConditionsCount++;
			}
			//cout << rule.toString(examples.getDataSet()) << endl;
		}
    }
    return ruleSet;
}
Ejemplo n.º 19
0
Rule UserRulesEditorFrame::GetRuleFromForm() {
	Rule newRule;
	//First validate.
	//Calling functions need to check for an enabled = false; rule as a failure.
	//Failure description is given in ruleObject.
	string ruleItem = RuleModBox->GetValue().ToUTF8();
	string sortItem = SortModBox->GetValue().ToUTF8();
	string insertItem = InsertModBox->GetValue().ToUTF8();
	if (Item(ruleItem).IsPlugin()) {
		if (SortModsCheckBox->IsChecked()) {
			if (SortModOption->GetValue()) {
				if (SortModOption->GetValue() && SortModBox->IsEmpty())
					throw boss_error(loc::translate("No mod is specified to sort relative to."), BOSS_ERROR_INVALID_SYNTAX);
				else if (!Item(sortItem).IsPlugin())  //Sort object is a group. Error.
					throw boss_error(loc::translate("Cannot sort a plugin relative to a group."), BOSS_ERROR_INVALID_SYNTAX);
			} else if (InsertModOption->GetValue() && !Item(insertItem).IsGroup()) {  //Inserting into a mod. Error.
				if (InsertModBox->IsEmpty())
					throw boss_error(loc::translate("No group is specified to insert into."), BOSS_ERROR_INVALID_SYNTAX);
				else
					throw boss_error(loc::translate("Cannot insert into a plugin."), BOSS_ERROR_INVALID_SYNTAX);
			}
		}
		if (AddMessagesCheckBox->IsChecked() && NewModMessagesBox->IsEmpty())  //Can't add no messages. Error.
			throw boss_error(loc::translate("Cannot add messages when none are given."), BOSS_ERROR_INVALID_SYNTAX);
	} else {  //Rule object is a group, or empty.
		if (RuleModBox->IsEmpty())
			throw boss_error(loc::translate("No rule mod is specified."), BOSS_ERROR_INVALID_SYNTAX);
		if (SortModsCheckBox->IsChecked()) {
			if (SortModOption->GetValue()) {
				if (SortModBox->IsEmpty())  //No sort object specified. Error.
					throw boss_error(loc::translate("No group is specified to sort relative to."), BOSS_ERROR_INVALID_SYNTAX);
				else if (Item(sortItem).IsPlugin())  //Sort object is a plugin. Error.
					throw boss_error(loc::translate("Cannot sort a group relative to a plugin."), BOSS_ERROR_INVALID_SYNTAX);
			} else if (InsertModOption->GetValue())  //Can't insert groups. Error.
				throw boss_error(loc::translate("Cannot insert groups."), BOSS_ERROR_INVALID_SYNTAX);
		}
		if (AddMessagesCheckBox->IsChecked())  //Can't add messages to a group. Error.
			throw boss_error(loc::translate("Cannot add messages to groups."), BOSS_ERROR_INVALID_SYNTAX);
	}
	if (!SortModsCheckBox->IsChecked() && !AddMessagesCheckBox->IsChecked())
		throw boss_error(loc::translate("The rule mod is not being sorted nor having its attached messages altered."), BOSS_ERROR_INVALID_SYNTAX);

	newRule.Enabled(true);
	newRule.Object(ruleItem);
	if (!SortModsCheckBox->IsChecked())
		newRule.Key(FOR);
	else {
		if (Item(newRule.Object()).IsGroup())
			newRule.Key(OVERRIDE);
		else {
			size_t pos = game.masterlist.FindItem(newRule.Object(), MOD);
			if (pos != game.masterlist.Items().size())  //Mod in masterlist.
				newRule.Key(OVERRIDE);
			else
				newRule.Key(ADD);
		}


		if (SortModOption->GetValue()) {
			RuleLine newLine;
			newLine.Object(sortItem);
			if (BeforeAfterChoiceBox->GetSelection() == 0)
				newLine.Key(BEFORE);
			else
				newLine.Key(AFTER);
			vector<RuleLine> lines = newRule.Lines();
			lines.push_back(newLine);
			newRule.Lines(lines);
		} else if (InsertModOption->GetValue()) {
			RuleLine newLine;
			newLine.Object(insertItem);
			if (TopBottomChoiceBox->GetSelection() == 0)
				newLine.Key(TOP);
			else
				newLine.Key(BOTTOM);
			vector<RuleLine> lines = newRule.Lines();
			lines.push_back(newLine);
			newRule.Lines(lines);
		}
	}

	//Now add message lines.
	if (AddMessagesCheckBox->IsChecked()) {
		RuleLine newLine;
		string messages = NewModMessagesBox->GetValue().ToUTF8();
		if (!messages.empty()) {
			//Split messages string by \n characters.
			size_t pos1 = 0, pos2 = string::npos;
			pos2 = messages.find("\n");
			if (pos2 == string::npos)  //No \n characters.
				pos2 = messages.length();
			while (pos2 != string::npos) {
				newLine.Object(trim_copy(messages.substr(pos1,pos2-pos1)));
				if (pos1 == 0 && ReplaceMessagesCheckBox->IsChecked())
					newLine.Key(REPLACE);
				else
					newLine.Key(APPEND);

				if (!newLine.IsObjectMessage())  //Message is formatted incorrectly. Error.
					throw boss_error((format("The message \"%1%\" is formatted incorrectly.") % newLine.Object()).str(), BOSS_ERROR_INVALID_SYNTAX);

				vector<RuleLine> lines = newRule.Lines();
				lines.push_back(newLine);
				newRule.Lines(lines);

				if (pos2 >= messages.length()-1)
					break;
				pos1 = pos2 + 1;
				pos2 = messages.find("\n", pos1);
				if (pos2 == string::npos && pos1 < messages.length()-1)
					pos2 = messages.length();
			}
		}
	}

	return newRule;
}
bool SequentialCoveringWithPreferences::isConditionForbiddenInRule(Rule& rule, double decClass, int attributeIndex, double value, bool greaterEqual, bool nominal)
{
	bool isForbidden = false;

	//for each forbidden rule
	for(list<KnowledgeRule>::iterator itForbRule = knowledge->getForbiddenRules()[decClass].begin(); !isForbidden && itForbRule != knowledge->getForbiddenRules()[decClass].end(); itForbRule++)
	{
		//check if current condition is present in forbidden rule
		list<KnowledgeCondition>::iterator itForbCond;
		for(itForbCond = itForbRule->getConditions().getConditions().begin(); itForbCond != itForbRule->getConditions().getConditions().end(); itForbCond++)
		{
			if(itForbCond->getAttributeIndex() == attributeIndex)
			{
				if(nominal)
				{
					if(itForbCond->getValue() == value)
						break;
				}
				else
				{
					if(isConitionsInterceptionNotEmpty(decClass, attributeIndex, value, greaterEqual, *itForbCond))
						break;
				}
			}
		}
		//if current condition is present in "itForbRule" forbidden rule, check if all other conditions from this forbidden rule are in a current rule
		if(itForbCond != itForbRule->getConditions().getConditions().end())
		{
			list<KnowledgeCondition>::iterator itForbCondPrime;
			for(itForbCondPrime = itForbRule->getConditions().getConditions().begin(); itForbCondPrime != itForbRule->getConditions().getConditions().end(); itForbCondPrime++)
			{
				if(itForbCondPrime == itForbCond)
					continue;

				//check if "itCondPrime" condition from forbidden rule is present in current rule
				bool isConditionPresent = false;

				if(rule.getConditions().size() > (unsigned int)itForbCondPrime->getAttributeIndex())
				{
					if(itForbCondPrime->getAttributeType() == Attribute::NOMINAL)
					{
						if(rule.getConditions()[attributeIndex].size() == 0 && itForbRule->getConditions().getConditionsForAttribute(attributeIndex).size() > 1)
						{
							isConditionPresent = true;
						}
						else
						{
							for(list<ElementaryCondition>::iterator itElCond = rule.getConditions()[itForbCondPrime->getAttributeIndex()].begin(); itElCond != rule.getConditions()[itForbCondPrime->getAttributeIndex()].end(); itElCond++)
							{
								if(itForbCondPrime->getValue() == itElCond->getAttributeValue() ||
										itForbRule->getConditions().getConditionsForAttribute(itForbCondPrime->getAttributeIndex()).size() > 1)
								{
									isConditionPresent = true;
									break;
								}
							}
						}
					}
					else
					{
						for(list<ElementaryCondition>::iterator itElCond = rule.getConditions()[itForbCondPrime->getAttributeIndex()].begin(); itElCond != rule.getConditions()[itForbCondPrime->getAttributeIndex()].end(); itElCond++)
						{
							if(isConitionsInterceptionNotEmpty(decClass, itElCond->getAttributeIndex(), itElCond->getAttributeValue(), typeid(*itElCond->getOperator()) == typeid(GreaterEqualOperator), *itForbCondPrime))
							{
								isConditionPresent = true;
								break;
							}
						}
					}
				}

				//if not, adding condition to the rule will not create forbidden conjunction according to "itRule"
				if(!isConditionPresent)
					break;
			}

			if(itForbCondPrime == itForbRule->getConditions().getConditions().end())
				isForbidden = true;
		}
	}

	return isForbidden;
}
Ejemplo n.º 21
0
int Rule::makeCNF(Rule *&TopRule)
/**
  Static Function::

  Function to make the tree into CNF
  (conditional normal form)
  @param TopRule :: Rule to simplify.

  We do not use *this :: The reason is that
  we need to change the toprule type e.g. from
  an intersection to a union.
  Since the type of a class can't be changed
  it is necessary to have a static function,
  so that the place that TopRule points is changable

  @retval 0 on failure
  @retval 1 on success
*/
{
  // Start at top to tree to find an instance
  // an intersection with stuff below.

  if (!TopRule)
    return 0;

  TopRule->makeParents();
  int count(0);             // Number of changes made
  int active(1);            // Do we still have to use
  Rule *tmpA, *tmpB, *tmpC; // need three to play

  while (active) {
    active = 0;
    count++;
    std::stack<Rule *> TreeLine; // Tree stack of rules

    // Start by putting the top item on the Tree Stack.
    // Note that it doesn't have a parent.
    TreeLine.push(TopRule);

    // Exit condition is that nothing changed last time
    // or the tree is Empty.
    if (!TopRule->checkParents())
      std::cerr << "Parents False" << std::endl;
    while (!active && !TreeLine.empty()) {
      // Ok get and remvoe the top item from the stack.
      tmpA = TreeLine.top();
      TreeLine.pop();

      // Now it might be a Union or Intersection
      // so we need to get is branches.

      tmpB = tmpA->leaf(0); // get leaves (two of)
      tmpC = tmpA->leaf(1);

      if (tmpB)
        TreeLine.push(tmpB);
      if (tmpC)
        TreeLine.push(tmpC);

      //
      //  Time to see if we can apply rule 4 (propositional calculus)
      //  to expand (a ^ b) v c to (a v c) ^ (b v c)
      //
      if (tmpA->type() == 1 && tmpB &&
          tmpC) // it is an intersection otherwise no work to do
      {
        // require either the left or right to be unions.
        if (tmpB->type() == -1 ||
            tmpC->type() == -1) // this is a union expand....
        {
          Rule *partReplace;
          Rule *alpha, *beta, *gamma, *Uobj; // Uobj to be deleted
          if (tmpB->type() ==
              -1) // ok the LHS is a union. (a ^ b) v g ==> (a v g) ^ (b v g )
          {
            // Make copies of the Unions leaves (allowing for null union)
            alpha = tmpB->leaf(0);
            beta = tmpB->leaf(1);
            gamma = tmpC;
            Uobj = tmpB;
          } else // RHS a v (b ^ g) ==> (a v b) ^ (a v g )
          {
            // Make copies of the Unions leaves (allowing for null union)
            // Note :: alpha designated as beta , gamma plays the role of alpha
            // in the RHS part of the above equation (allows common replace
            // block below.
            alpha = tmpC->leaf(0);
            beta = tmpC->leaf(1);
            gamma = tmpB;
            Uobj = tmpC;
          }
          // Have bit to replace

          // Note:: no part of this can be memory copy
          // hence we have to play games with a second
          // gamma->clone()
          partReplace = new Union(new Intersection(alpha, gamma),
                                  new Intersection(beta, gamma->clone()));
          //
          // General replacement
          //
          Rule *Pnt = tmpA->getParent(); // parent
          if (Pnt) // Not the top rule (so replace parents leaf)
          {
            const int leafN = Pnt->findLeaf(tmpA);
            Pnt->setLeaf(partReplace, leafN);
          } else
            TopRule = partReplace;

          // Clear up the mess and delete the rule that we have changes
          // Set the cutoffs in the correct place to avoid a complete
          // tree deletion
          tmpA->setLeaves(0, 0);
          delete tmpA;
          Uobj->setLeaves(0, 0);
          delete Uobj;
          // Now we have to go back to the begining again and start again.
          active = 1; // Exit loop
        }
      }
    }
  }
  return count - 1; // return number of changes
}
Ejemplo n.º 22
0
uint32_t analyse (FILE *fmatched, const char *file)
{
      int rule_id = -1, test_id = -1;

      if (!rule)
	  {   // Initial rule
          MDEBUG(("%s\n", file));
          if (!rule.load (file, RULE_MAX_REPEAT, true))
          {
              MDEBUG (("\tFailed to reference tune %s\n", file));
              return 0;
          }
          MDEBUG (("\tInitial rule base $%04x, length %d, matches %d\n", rule.base(), rule.length(), rule.ids()));
		  //rule.md5_add ();
		  return 1;
	  }

      // Now try for a match with tune two. 
      if (!test.load (file, -1, true))
      {
          MDEBUG (("%s\n\tFailed to load, skipping\n", file));
          return 0;
      }

      fprintf (stderr, "%s\n", file);

      int end = test.ids() - RULE_MATCH;
      if (end < 0)
      {
          MDEBUG (("\tInput file not long enough to match against\n", file));
          return 0;
      }

      for (int id = 0; id < end; id++)
      {
          rule_id = rule.find (test, id, RULE_MATCH);
          if (rule_id < 0)
              continue;
          test_id = id;
          break;
      }

      if (rule_id < 0)
      {
          MDEBUG (("\tNo match found\n"));
          return 0;
      }
      else
      {
          MDEBUG (("\tMatch rule id %d ($%04x) with test id %d ($%04x)\n", rule_id, rule.addr(rule_id), test_id, test.addr(test_id)));
      }

      if (!rule.combine (test, test_id, rule_id, RULE_MIN_MATCH))
          MDEBUG (("\tMatches less that minimum threshold, tune ignored\n"));
      else
          MDEBUG (("\tRule base $%04x, length %d, matches %d\n", rule.base(), rule.length(), rule.ids()));
      test.md5_add ();
      fprintf (fmatched, "%s %d %s @ %04x\n", test.md5_get(), rule.player_id(), file, test.addr(test_id));
      return 1;
}
Ejemplo n.º 23
0
void Nids::process_packet_gpu(Packet *packet)
{
    BOOST_LOG_TRIVIAL(trace) << "Begin - Nids::process_packet_gpu";

    matched_rules.clear();
    analyze_header(packet, matched_rules);

    // Check if some of headers rules matched.
    // If it's matched we need to analyze payload.
    if (matched_rules.size() > 0) {
        bool ac_analyze_needed = false;

        //cout << "Number of matched rule for received packet: " << matched_rules.size() << endl;

        // locked on gpu_switch_buffer_mutex
        {
            boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(gpu_switch_buffer_mutex);
            for (vector<int>::iterator it = matched_rules.begin(); it != matched_rules.end(); ++it) {
                Rule *r = rules[*it];

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

                if (regex_dfa_offset[*it] != -1) {
                    tasks->push_back(packet_buffer->size());
                    tasks->push_back(packet->get_payload_size());
                    tasks->push_back(regex_dfa_offset[*it] + ac.count_states());
                    tasks->push_back(*it);
                }

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

            if (ac_analyze_needed) {
                tasks->push_back(packet_buffer->size());
                tasks->push_back(packet->get_payload_size());
                tasks->push_back(0);
                tasks->push_back(0);
            }

            packet_buffer->insert(packet_buffer->end(),
                                 packet->get_raw_packet() + packet->get_payload_offset(),
                                 packet->get_raw_packet() + packet->get_payload_offset() + packet->get_payload_size());
            int rem = packet->get_payload_size() % 32;
            packet_buffer->resize(packet_buffer->size() + rem, 0);

//            for (int i = 0; i < packet->get_payload_size(); ++i) {
//                cout << (packet->get_raw_packet() + packet->get_payload_offset())[i] << ' ';
//            }

//            cout << endl;
        }

        if (window_type == BUF_SIZE && packet_buffer->size() >= buffer_threshold && gpu_task_finished.try_wait())
            gpu_task_ready.post();
    }

    BOOST_LOG_TRIVIAL(trace) << "End - Nids::process_packet_gpu";
}
Ejemplo n.º 24
0
// Combine our rule with the supplied rule
bool Rule::combine (const Rule &rule, int id, int myid, int threshold)
{
    // Check the rules to make sure they are within range
    if ((myid < 0) || (myid >= m_ids))
        return false;
    if ((id < 0) || (id >= rule.ids ()))
        return false;

	/*
    int base = rule.m_addr[0];
    {   // Calculate base addresses
        int addr     = m_addr[myid];
        int myoffset = addr - m_base;
        int offset   = rule.m_addr[id] - base;
        myid = 0; // Calculate real starting id
        while (offset < myoffset)
        {
            m_memory[m_base] = IGNORED;
            m_base   = m_addr[++myid];
            myoffset = addr - m_base;
        }
        base = rule.m_addr[id] - myoffset;
    }
	*/

    int base = rule.m_addr[id];
    for (int i = 0; i < myid; i++)
        m_memory[m_addr[i]] = IGNORED;
    m_base = m_addr[myid];

    int end = m_addr[m_ids-1];
    {   // Calculate end address
        int mylen = end - m_base;
        int len   = rule.m_addr[rule.ids()-1] - base;
        if (len   < mylen)
            end   = m_base + len;
    }
    

    // Combine rule
    int count = 0;
    for (; myid < m_ids; myid++)
    {
        int addr = m_addr[myid];
        if (addr > end)
            break;
        int flags = m_flags[addr];
        int i = addr - m_base;
        if (m_memory[addr] != rule.m_memory[base+i])
		{
            m_flags[addr] = IGNORED;
            continue;
        }
        m_addr[count++] = addr;
    }

    // Trim off any remaining end bits
    while (myid < m_ids)
        m_flags[m_addr[myid++]] = IGNORED;
    m_ids = count;

    // This filters the rule of spurious data
    _eval ();
    //md5_add ();
    m_matches++;
    return true;
}
Ejemplo n.º 25
0
void PropagatorFactory::add(const Rule& rule) {
	notifyMonitorsOfAdding(rule);

	definitions->addRule(rule.getID(), rule.onlyif, rule.definitionID, rule.conjunctive, rule.head, rule.body);
}
Ejemplo n.º 26
0
void readSpatialSBML() {
	SBMLDocument *document2 = readSBML("spatial_example2.xml");
  
	Model *model2 = document2->getModel();
	Compartment *comp;
	SpatialCompartmentPlugin* cplugin;
	for (unsigned int i = 0; i < model2->getNumCompartments(); i++) {
		comp = model2->getCompartment(i);
		cout << "Compartment" << i << ": "  << comp->getId() << endl;
		cplugin = static_cast<SpatialCompartmentPlugin*>(comp->getPlugin("spatial"));
		if (cplugin->getCompartmentMapping()->isSetId()) {
			cout << "Comp" << i << "  CMSpId: "  << cplugin->getCompartmentMapping()->getId() << endl;
			cout << "Comp" << i << "  CM_DType: "  << cplugin->getCompartmentMapping()->getDomainType() << endl;
			cout << "Comp" << i << "  CM_UnitSz: "  << cplugin->getCompartmentMapping()->getUnitSize() << endl;
		}
	}

	Species *sp;
	SpatialSpeciesPlugin* srplugin;
	for (unsigned int i = 0; i < model2->getNumSpecies(); i++) {
		sp = model2->getSpecies(i);
		cout << "Species" << i << ": "      << sp->getId()      << endl;
		srplugin = static_cast<SpatialSpeciesPlugin*>(sp->getPlugin("spatial"));
		if (srplugin->getIsSpatial()) {
			cout << "species" << i << "  isSpatial: "  << srplugin->getIsSpatial() << endl;
		}
	}

	Parameter *param;
	SpatialParameterPlugin* pplugin;
	for (unsigned int i = 0; i < model2->getNumParameters(); i++) {
		param = model2->getParameter(i);
		cout << "Parameter" << i << ": "  << param->getId() << endl;
		pplugin = static_cast<SpatialParameterPlugin*>(param->getPlugin("spatial"));
		if (pplugin->isSetSpatialSymbolReference()) {
			cout << "Parameter" << i << "  SpRefId: "  << pplugin->getSpatialSymbolReference()->getSpatialRef() << endl;
		}
		if (pplugin->isSetDiffusionCoefficient()) {
			cout << "Diff_" << i << "  SpeciesVarId: "  << pplugin->getDiffusionCoefficient()->getVariable() << endl;
			cout << "Diff_" << i << "  Type: "  << DiffusionKind_toString(pplugin->getDiffusionCoefficient()->getType()) << endl;
      for (unsigned int j = 0; j < pplugin->getDiffusionCoefficient()->getNumCoordinateReferences(); ++j)
        cout << "Diff_" << i << "  SpCoordIndex  " << j << " : " << CoordinateKind_toString(pplugin->getDiffusionCoefficient()->getCoordinateReference(j) ->getCoordinate()) << endl;
		}
		if (pplugin->isSetAdvectionCoefficient()) {
			cout << "Adv_" << i << "  SpeciesVarId: "  << pplugin->getAdvectionCoefficient()->getVariable() << endl;
			cout << "Adv_" << i << "  SpCoordIndex: "  << CoordinateKind_toString(pplugin->getAdvectionCoefficient()->getCoordinate()) << endl;
		}
		if (pplugin->isSetBoundaryCondition()) {
			cout << "BC_" << i << "  SpeciesVarId: "  << pplugin->getBoundaryCondition()->getVariable() << endl;
			cout << "BC_" << i << "  SpCoordBoundary: "  << pplugin->getBoundaryCondition()->getCoordinateBoundary() << endl;
			cout << "BC_" << i << "  SpBoundaryType: "  << pplugin->getBoundaryCondition()->getType() << endl;
		}
	}

	Reaction *rxn;
	SpatialReactionPlugin* rplugin;
	for (unsigned int i = 0; i < model2->getNumReactions(); i++) {
		rxn = model2->getReaction(i);
		cout << "Reaction" << i << ": "      << rxn->getId()      << endl;
		rplugin = static_cast<SpatialReactionPlugin*>(rxn->getPlugin("spatial"));
		if (rplugin->getIsLocal()) {
			cout << "rxn" << i << "  isLocal: "  << rplugin->getIsLocal() << endl;
		}
	}

	Rule *rule;
	for (unsigned int i = 0; i < model2->getNumRules(); i++) {
		rule = model2->getRule(i);
		cout << "Rule" << i << ": "      << rule->getVariable()      << endl;
	}

	//
	// Get a SpatialModelPlugin object plugged in the model object.
	//
	// The type of the returned value of SBase::getPlugin() function is 
	// SBasePlugin*, and thus the value needs to be cast for the 
	// corresponding derived class.
	//
	SpatialModelPlugin* mplugin2;
	mplugin2 = static_cast<SpatialModelPlugin*>(model2->getPlugin("spatial"));
	cout << "URI: "      << mplugin2->getURI()      << endl;
	cout << "prefix: "      << mplugin2->getPrefix()      << endl;

	// get a Geometry object via SpatialModelPlugin object.
	Geometry* geometry2 = mplugin2->getGeometry();
	cout << "Geometry coordSystem: "      << geometry2->getCoordinateSystem()      << endl;
    
	// get a CoordComponent object via the Geometry object.	
	CoordinateComponent* coordComp = geometry2->getCoordinateComponent(0);
	std::cout << "CoordComponent Id: " << coordComp->getId() << std::endl;
  std::cout << "CoordComponent type: " << CoordinateKind_toString( coordComp->getType()) << std::endl;
	std::cout << "CoordComponent sbmlUnit: " << coordComp->getUnit() << std::endl;
  if (coordComp->isSetBoundaryMin())
  {
  Boundary* minX = coordComp->getBoundaryMin();
	std::cout << "minX name: " << minX->getId() << std::endl;
	std::cout << "minX value: " << minX->getValue() << std::endl;
  }
  if (coordComp->isSetBoundaryMax())
  {
	Boundary* maxX = coordComp->getBoundaryMax();
	std::cout << "maxX name: " << maxX->getId() << std::endl;
	std::cout << "maxX value: " << maxX->getValue() << std::endl;
  }

	// get a DomainType object via the Geometry object.	
	DomainType* domainType2 = geometry2->getDomainType(0);
	std::cout << "DomainType Id: " << domainType2->getId() << std::endl;
	std::cout << "DomainType spatialDim: " << domainType2->getSpatialDimension() << std::endl;

	// get a Domain object via the Geometry object.	
	Domain* domain = geometry2->getDomain(0);
	std::cout << "Domain1 Id: " << domain->getId() << std::endl;
	std::cout << "Domain1 domainType: " << domain->getDomainType() << std::endl;
	// get an internal point via the domain object
	InteriorPoint* internalPt = domain->getInteriorPoint(0);
	std::cout << "InternalPt_1 coord1: " << internalPt->getCoord1() << std::endl;

	// get a Domain object via the Geometry object.	
	domain = geometry2->getDomain(1);
	std::cout << "Domain2 Id: " << domain->getId() << std::endl;
	std::cout << "Domain2 domainType: " << domain->getDomainType() << std::endl;
	// get an internal point via the domain object
	internalPt = domain->getInteriorPoint(0);
	std::cout << "InternalPt_2 coord1: " << internalPt->getCoord1() << std::endl;

	// get an AdjacentDomains object via the Geometry object.	
	AdjacentDomains* adjDomain = geometry2->getAdjacentDomains(0);
	std::cout << "AdjDomain Id: " << adjDomain->getId() << std::endl;
	std::cout << "AdjDomain domain1: " << adjDomain->getDomain1() << std::endl;
	std::cout << "AdjDomain domain2: " << adjDomain->getDomain2() << std::endl;

	// get an AnalyticGeometry object via the Geometry object.
	GeometryDefinition* gd;
	for (unsigned int i = 0; i < geometry2->getNumGeometryDefinitions(); i++) {
		gd = geometry2->getGeometryDefinition(i);
		if (gd->isAnalyticGeometry()) {
			AnalyticGeometry* analyticalGeom = static_cast<AnalyticGeometry*>(gd);
			std::cout << "AnalGeom Id: " << analyticalGeom->getId() << std::endl;

			// analVol from analGeom.
			AnalyticVolume* av = analyticalGeom->getAnalyticVolume(0);
			std::cout << "AnalVol Id: " << av->getId() << std::endl;
			std::cout << "AnalVol domainType: " << av->getDomainType() << std::endl;
			std::cout << "AnalVol funcType: " << av->getFunctionType() << std::endl;
			std::cout << "AnalVol ordinal: " << av->getOrdinal() << std::endl;
			const ASTNode* mathNode = av->getMath();
			char* mathStr = writeMathMLToString(mathNode);
			std::cout << "AnalVol math: " << mathStr << std::endl;
		}
		if (gd->isSampledFieldGeometry()) {
			SampledFieldGeometry* sfGeom = static_cast<SampledFieldGeometry*>(gd);
			std::cout << "SampledFieldGeom Id: " << sfGeom->getId() << std::endl;
			
			// sampledField from sfGeom
			SampledField* sf = sfGeom->getSampledField();
			std::cout << "SampledField Id: " << sf->getId() << std::endl;
			std::cout << "SampledField dataType: " << sf->getDataType() << std::endl;
			std::cout << "SampledField interpolation: " << sf->getInterpolationType() << std::endl;
			std::cout << "SampledField encoding: " << sf->getEncoding() << std::endl;
			std::cout << "SampledField numSamples1: " << sf->getNumSamples1() << std::endl;
			std::cout << "SampledField numSamples2: " << sf->getNumSamples2() << std::endl;
			std::cout << "SampledField numSamples3: " << sf->getNumSamples3() << std::endl;
			const ImageData* id = sf->getImageData();
			int* samples = new int[id->getSamplesLength()];
			id->getSamples(samples);
			std::cout << "ImageData samples[0]: " << samples[0] << std::endl;
			std::cout << "ImageData dtype: " << id->getDataType() << std::endl;
			std::cout << "ImageData samplesLen: " << id->getSamplesLength() << std::endl;
      
			// sampledVolVol from sfGeom.
			SampledVolume* sv = sfGeom->getSampledVolume(0);
			std::cout << "SampledVol Id: " << sv->getId() << std::endl;
			std::cout << "SampledVol domainType: " << sv->getDomainType() << std::endl;
			std::cout << "SampledVol sampledVal: " << sv->getSampledValue() << std::endl;
			std::cout << "SampledVol min: " << sv->getMinValue() << std::endl;
			std::cout << "SampledVol max: " << sv->getMaxValue() << std::endl;
		}
	}

	delete document2;
}
Ejemplo n.º 27
0
//
// return true if the event matched the rule
//
bool			Session::ApplyRule(const Rule & rule, const EVENTLOGRECORD * ev) {
	string test;

	GetEventUser(ev, test);
	if (rule.GetEventId() != 0 && rule.GetEventId() != (ev->EventID & MSG_ID_MASK))
		return false;
	if (ev->TimeGenerated < (m_now - rule.GetDelay()) 
		&& rule.GetIgnore() == false) // ignore rules don't depend on delay parameters
		return false;
	if (rule.GetSource().length() > 0) {
		string source = (LPSTR) ((LPBYTE) ev + sizeof(EVENTLOGRECORD));
		std::transform(source.begin(), source.end(), source.begin(), tolower);
		if (source != rule.GetSource())
			return false;
	}
	if (rule.GetType() != 0 && rule.GetType() != ev->EventType)
		return false;
	if (rule.GetUser().length() > 0) {
		string user;

		boost::regex e(rule.GetUser(), boost::regbase::perl);
		GetEventUser(ev, user);
		boost::match_results<std::string::const_iterator>	what;
		if(boost::regex_search(user, what, e) == 0)	{
			return false;
		} 
	}
	if (rule.GetValue().length() > 0) {
		string desc;
		
		boost::regex e(rule.GetValue(), boost::regbase::perl);
		GetEventDescription(ev, desc);
		boost::match_results<std::string::const_iterator>	what;
		if(boost::regex_search(desc, what, e) == 0)	{
			return false;
		} 
	}
	return true;
}
Ejemplo n.º 28
0
QString RuleWidget::condition(Rule rule)
{
    return Statements::columnList().at(static_cast<int>(rule.column())) + tr(" is ") + rule.value();
}
Ejemplo n.º 29
0
LIBSBML_CPP_NAMESPACE_USE

int
main (int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << endl << "Usage: printUnits filename" << endl << endl;
        return 1;
    }

    const char* filename   = argv[1];
    SBMLDocument* document = readSBML(filename);

    if (document->getNumErrors() > 0)
    {
        cerr << "Encountered the following SBML errors:" << endl;
        document->printErrors(cerr);
        return 1;
    }

    Model* model = document->getModel();

    if (model == 0)
    {
        cout << "No model present." << endl;
        return 1;
    }

    unsigned int i,j;
    for (i = 0; i < model->getNumSpecies(); i++)
    {
        Species* s = model->getSpecies(i);
        cout << "Species " << i << ": "
             << UnitDefinition::printUnits(s->getDerivedUnitDefinition()) << endl;
    }

    for (i = 0; i < model->getNumCompartments(); i++)
    {
        Compartment *c = model->getCompartment(i);
        cout << "Compartment " << i << ": "
             << UnitDefinition::printUnits(c->getDerivedUnitDefinition())
             << endl;
    }

    for (i = 0; i < model->getNumParameters(); i++)
    {
        Parameter *p = model->getParameter(i);
        cout << "Parameter " << i << ": "
             << UnitDefinition::printUnits(p->getDerivedUnitDefinition())
             << endl;
    }


    for (i = 0; i < model->getNumInitialAssignments(); i++)
    {
        InitialAssignment *ia = model->getInitialAssignment(i);
        cout << "InitialAssignment " << i << ": "
             << UnitDefinition::printUnits(ia->getDerivedUnitDefinition()) << endl;
        cout << "        undeclared units: ";
        cout << (ia->containsUndeclaredUnits() ? "yes\n" : "no\n");
    }

    for (i = 0; i < model->getNumEvents(); i++)
    {
        Event *e = model->getEvent(i);
        cout << "Event " << i << ": " << endl;

        if (e->isSetDelay())
        {
            cout << "Delay: "
                 << UnitDefinition::printUnits(e->getDelay()->getDerivedUnitDefinition()) << endl;
            cout << "        undeclared units: ";
            cout << (e->getDelay()->containsUndeclaredUnits() ? "yes\n" : "no\n");
        }

        for (j = 0; j < e->getNumEventAssignments(); j++)
        {
            EventAssignment *ea = e->getEventAssignment(j);
            cout << "EventAssignment " << j << ": "
                 << UnitDefinition::printUnits(ea->getDerivedUnitDefinition()) << endl;
            cout << "        undeclared units: ";
            cout << (ea->containsUndeclaredUnits() ? "yes\n" : "no\n");
        }
    }

    for (i = 0; i < model->getNumReactions(); i++)
    {
        Reaction *r = model->getReaction(i);

        cout << "Reaction " << i << ": " << endl;

        if (r->isSetKineticLaw())
        {
            cout << "Kinetic Law: "
                 << UnitDefinition::printUnits(r->getKineticLaw()->getDerivedUnitDefinition()) << endl;
            cout << "        undeclared units: ";
            cout << (r->getKineticLaw()->containsUndeclaredUnits() ? "yes\n" : "no\n");
        }

        for (j = 0; j < r->getNumReactants(); j++)
        {
            SpeciesReference *sr = r->getReactant(j);

            if (sr->isSetStoichiometryMath())
            {
                cout << "Reactant stoichiometryMath" << j << ": "
                     << UnitDefinition::printUnits(sr->getStoichiometryMath()->getDerivedUnitDefinition()) << endl;
                cout << "        undeclared units: ";
                cout << (sr->getStoichiometryMath()->containsUndeclaredUnits() ? "yes\n" : "no\n");
            }
        }

        for (j = 0; j < r->getNumProducts(); j++)
        {
            SpeciesReference *sr = r->getProduct(j);

            if (sr->isSetStoichiometryMath())
            {
                cout << "Product stoichiometryMath" << j << ": "
                     << UnitDefinition::printUnits(sr->getStoichiometryMath()->getDerivedUnitDefinition()) << endl;
                cout << "        undeclared units: ";
                cout << (sr->getStoichiometryMath()->containsUndeclaredUnits() ? "yes\n" : "no\n");
            }
        }
    }

    for (i = 0; i < model->getNumRules(); i++)
    {
        Rule *r = model->getRule(i);
        cout << "Rule " << i << ": "
             << UnitDefinition::printUnits(r->getDerivedUnitDefinition()) << endl;
        cout << "        undeclared units: ";
        cout << (r->containsUndeclaredUnits() ? "yes\n" : "no\n");
    }

    delete document;
    return 0;
}
Ejemplo n.º 30
0
// parser = ((cmd|codeblock)end)*
auto_ptr<Rule> exstatik::CreateParser_Complex() {
  auto_ptr<Rule> parser(STAR("parser"));
  Rule* line = parser->AddChild(SEQ("line"));
  //line->AddChild(META("WS"));
  Rule* cmdorcode = line->AddChild(OR("Or (cmdorcode)"));
  Rule* end = line->AddChild(OR("end"));
  end->AddChild(META(";"));
  end->AddChild(META("\n"));

  Rule* cmdline = cmdorcode->AddChild(SEQ("cmdline"));
  cmdline->AddChild(META("ID", "program"));
  Rule* cmdargs = cmdline->AddChild(STAR("* (cmdargs)"));
  Rule* cmdarg = cmdargs->AddChild(SEQ("cmdarg"));
  cmdarg->AddChild(META("WS"));
  cmdarg->AddChild(META("arg"));

  Rule* codeblock = cmdorcode->AddChild(SEQ("codeblock"));
  codeblock->AddChild(META("{"));
  Rule* stmts = codeblock->AddChild(STAR("* (stmts)"));
  codeblock->AddChild(META("}"));

  Rule* stmt = stmts->AddChild(OR("Or (stmt)"));
  Rule* newstmt = stmt->AddChild(SEQ("new stmt"));
  newstmt->AddChild(META("new"));
  newstmt->AddChild(META("WS"));
  newstmt->AddChild(META("identifier", "ID"));
  newstmt->AddChild(META(";"));
  Rule* delstmt = stmt->AddChild(SEQ("del stmt"));
  delstmt->AddChild(META("del"));
  delstmt->AddChild(META("WS"));
  delstmt->AddChild(META("identifier", "ID"));
  delstmt->AddChild(META(";"));
  return parser;
}