Ejemplo n.º 1
0
bool isSameExpression(bool cpp, const Token *tok1, const Token *tok2, const std::set<std::string> &constFunctions)
{
    if (tok1 == nullptr && tok2 == nullptr)
        return true;
    if (tok1 == nullptr || tok2 == nullptr)
        return false;
    if (cpp) {
        if (tok1->str() == "." && tok1->astOperand1() && tok1->astOperand1()->str() == "this")
            tok1 = tok1->astOperand2();
        if (tok2->str() == "." && tok2->astOperand1() && tok2->astOperand1()->str() == "this")
            tok2 = tok2->astOperand2();
    }
    if (tok1->varId() != tok2->varId() || tok1->str() != tok2->str()) {
        if ((Token::Match(tok1,"<|>")   && Token::Match(tok2,"<|>")) ||
            (Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) {
            return isSameExpression(cpp, tok1->astOperand1(), tok2->astOperand2(), constFunctions) &&
                   isSameExpression(cpp, tok1->astOperand2(), tok2->astOperand1(), constFunctions);
        }
        return false;
    }
    if (tok1->str() == "." && tok1->originalName() != tok2->originalName())
        return false;
    if (tok1->isExpandedMacro() || tok2->isExpandedMacro())
        return false;
    if (tok1->isName() && tok1->next()->str() == "(" && tok1->str() != "sizeof") {
        if (!tok1->function() && !Token::Match(tok1->previous(), ".|::") && constFunctions.find(tok1->str()) == constFunctions.end() && !tok1->isAttributeConst() && !tok1->isAttributePure())
            return false;
        else if (tok1->function() && !tok1->function()->isConst() && !tok1->function()->isAttributeConst() && !tok1->function()->isAttributePure())
            return false;
    }
    // templates/casts
    if ((Token::Match(tok1, "%name% <") && tok1->next()->link()) ||
        (Token::Match(tok2, "%name% <") && tok2->next()->link())) {

        // non-const template function that is not a dynamic_cast => return false
        if (Token::simpleMatch(tok1->next()->link(), "> (") &&
            !(tok1->function() && tok1->function()->isConst()) &&
            tok1->str() != "dynamic_cast")
            return false;

        // some template/cast stuff.. check that the template arguments are same
        const Token *t1 = tok1->next();
        const Token *t2 = tok2->next();
        const Token *end1 = t1->link();
        const Token *end2 = t2->link();
        while (t1 && t2 && t1 != end1 && t2 != end2) {
            if (t1->str() != t2->str())
                return false;
            t1 = t1->next();
            t2 = t2->next();
        }
        if (t1 != end1 || t2 != end2)
            return false;
    }
    if (tok1->tokType() == Token::eIncDecOp || tok1->isAssignmentOp())
        return false;
    // bailout when we see ({..})
    if (tok1->str() == "{")
        return false;
    if (tok1->str() == "(" && tok1->previous() && !tok1->previous()->isName()) { // cast => assert that the casts are equal
        const Token *t1 = tok1->next();
        const Token *t2 = tok2->next();
        while (t1 && t2 && t1->str() == t2->str() && (t1->isName() || t1->str() == "*")) {
            t1 = t1->next();
            t2 = t2->next();
        }
        if (!t1 || !t2 || t1->str() != ")" || t2->str() != ")")
            return false;
    }
    bool noncommuative_equals =
        isSameExpression(cpp, tok1->astOperand1(), tok2->astOperand1(), constFunctions);
    noncommuative_equals = noncommuative_equals &&
                           isSameExpression(cpp, tok1->astOperand2(), tok2->astOperand2(), constFunctions);

    if (noncommuative_equals)
        return true;

    const bool commutative = tok1->astOperand1() && tok1->astOperand2() && Token::Match(tok1, "%or%|%oror%|+|*|&|&&|^|==|!=");
    bool commuative_equals = commutative &&
                             isSameExpression(cpp, tok1->astOperand2(), tok2->astOperand1(), constFunctions);
    commuative_equals = commuative_equals &&
                        isSameExpression(cpp, tok1->astOperand1(), tok2->astOperand2(), constFunctions);

    // in c++, "a"+b might be different to b+"a"
    if (cpp && commuative_equals && tok1->str() == "+" &&
        (tok1->astOperand1()->tokType() == Token::eString || tok1->astOperand2()->tokType() == Token::eString)) {
        const Token * const other = tok1->astOperand1()->tokType() != Token::eString ? tok1->astOperand1() : tok1->astOperand2();
        return other && astIsIntegral(other,false);
    }

    return commuative_equals;
}
Ejemplo n.º 2
0
bool generate_sql_makefile()
{
    if (new_sql_updates.empty()) return true;

    // find all files in the update dir
    snprintf(cmd, MAX_CMD, "git show HEAD:%s", sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    char newname[MAX_PATH];
    std::set<std::string> file_list;
    sql_update_info info;

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (buffer[strlen(buffer) - 1] != '/' &&
                strncmp(buffer, "Makefile.am", MAX_BUF) != 0)
        {
            if (new_sql_updates.find(buffer) != new_sql_updates.end())
            {
                if (!get_sql_update_info(buffer, info)) return false;
                snprintf(newname, MAX_PATH, REV_PRINT "_%s_%0*d_%s%s%s.sql", rev, info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
                file_list.insert(newname);
            }
            else
                file_list.insert(buffer);
        }
    }

    pclose(cmd_pipe);

    // write the makefile
    char file_name[MAX_PATH];
    snprintf(file_name, MAX_PATH, "%s%s/Makefile.am", path_prefix, sql_update_dir);
    FILE* fout = fopen(file_name, "w");
    if (!fout) { pclose(cmd_pipe); return false; }

    fprintf(fout,
            "# This code is part of MaNGOS. Contributor & Copyright details are in AUTHORS/THANKS.\n"
            "#\n"
            "# This program is free software; you can redistribute it and/or modify\n"
            "# it under the terms of the GNU General Public License as published by\n"
            "# the Free Software Foundation; either version 2 of the License, or\n"
            "# (at your option) any later version.\n"
            "#\n"
            "# This program is distributed in the hope that it will be useful,\n"
            "# but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
            "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
            "# GNU General Public License for more details.\n"
            "#\n"
            "# You should have received a copy of the GNU General Public License\n"
            "# along with this program; if not, write to the Free Software\n"
            "# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
            "\n"
            "## Process this file with automake to produce Makefile.in\n"
            "\n"
            "## Sub-directories to parse\n"
            "SUBDIRS = before_upgrade_to_0.13\n"
            "\n"
            "## Change installation location\n"
            "#  datadir = mangos/%s\n"
            "pkgdatadir = $(datadir)/mangos/%s\n"
            "\n"
            "## Files to be installed\n"
            "#  Install basic SQL files to datadir\n"
            "pkgdata_DATA = \\\n",
            sql_update_dir, sql_update_dir
    );

    for(std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fprintf(fout,
            "\n## Additional files to include when running 'make dist'\n"
            "#  SQL update files, to upgrade database schema from older revisions\n"
            "EXTRA_DIST = \\\n"
           );

    for (std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fclose(fout);

    snprintf(cmd, MAX_CMD, "git add %s%s/Makefile.am", path_prefix, sql_update_dir);
    system_switch_index(cmd);

    return true;
}
Ejemplo n.º 3
0
 bool isBpFunction(const char* nm) const {
   std::set<string>::const_iterator i = enabledFunctions.find(string(nm));
   return i != enabledFunctions.end();
 }
 void SetData(uint32 type, uint32 data)
 {
     switch (type)
     {
     case DATA_MAGTHERIDON_EVENT:
         m_auiEncounter[0] = data;
         if (data == NOT_STARTED)
             RespawnTimer = 10000;
         if (data != IN_PROGRESS)
            HandleGameObject(DoorGUID, true);
         break;
     case DATA_CHANNELER_EVENT:
         switch (data)
         {
         case NOT_STARTED: // Reset all channelers once one is reset.
             if (m_auiEncounter[1] != NOT_STARTED)
             {
                 m_auiEncounter[1] = NOT_STARTED;
                 for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                 {
                     if (Creature* Channeler = instance->GetCreature(*i))
                     {
                         if (Channeler->IsAlive())
                             Channeler->AI()->EnterEvadeMode();
                         else
                             Channeler->Respawn();
                     }
                 }
                 CageTimer = 0;
                 HandleGameObject(DoorGUID, true);
             }
             break;
         case IN_PROGRESS: // Event start.
             if (m_auiEncounter[1] != IN_PROGRESS)
             {
                 m_auiEncounter[1] = IN_PROGRESS;
                 // Let all five channelers aggro.
                 for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                 {
                     Creature* Channeler = instance->GetCreature(*i);
                     if (Channeler && Channeler->IsAlive())
                         Channeler->AI()->AttackStart(Channeler->SelectNearestTarget(999));
                 }
                 // Release Magtheridon after two minutes.
                 Creature* Magtheridon = instance->GetCreature(MagtheridonGUID);
                 if (Magtheridon && Magtheridon->IsAlive())
                 {
                     Magtheridon->MonsterTextEmote(EMOTE_BONDS_WEAKEN, 0);
                     CageTimer = 120000;
                 }
                 HandleGameObject(DoorGUID, false);
             }
             break;
         case DONE: // Add buff and check if all channelers are dead.
             for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
             {
                 Creature* Channeler = instance->GetCreature(*i);
                 if (Channeler && Channeler->IsAlive())
                 {
                     //Channeler->CastSpell(Channeler, SPELL_SOUL_TRANSFER, true);
                     data = IN_PROGRESS;
                     break;
                 }
             }
             break;
         }
         m_auiEncounter[1] = data;
         break;
     case DATA_COLLAPSE:
         // true - collapse / false - reset
         for (std::set<uint64>::const_iterator i = ColumnGUID.begin(); i != ColumnGUID.end(); ++i)
             DoUseDoorOrButton(*i);
         break;
     default:
         break;
     }
 }
Ejemplo n.º 5
0
bool find_sql_updates()
{
    printf("+ finding new sql updates on HEAD\n");
    // add all updates from HEAD
    snprintf(cmd, MAX_CMD, "git show HEAD:%s", sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    sql_update_info info;

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (!get_sql_update_info(buffer, info)) continue;

        if (info.db_idx == NUM_DATABASES)
        {
            if (info.rev > 0) printf("WARNING: incorrect database name for sql update %s\n", buffer);
            continue;
        }

        new_sql_updates.insert(buffer);
    }

    pclose(cmd_pipe);

    // Add last milestone's file information
    last_sql_rev[0] = 11785;
    last_sql_nr[0] = 2;
    sscanf("11785_02_characters_instance", "%s", last_sql_update[0]);
    last_sql_rev[2] = 10008;
    last_sql_nr[2] = 1;
    sscanf("10008_01_realmd_realmd_db_version", "%s", last_sql_update[2]);

    // remove updates from the last commit also found on origin
    snprintf(cmd, MAX_CMD, "git show %s:%s", origin_hash, sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (!get_sql_update_info(buffer, info)) continue;

        // find the old update with the highest rev for each database
        // (will be the required version for the new update)
        std::set<std::string>::iterator itr = new_sql_updates.find(buffer);
        if (itr != new_sql_updates.end())
        {
            if (info.rev > 0 && (info.rev > last_sql_rev[info.db_idx] ||
                                 (info.rev == last_sql_rev[info.db_idx] && info.nr > last_sql_nr[info.db_idx])))
            {
                last_sql_rev[info.db_idx] = info.rev;
                last_sql_nr[info.db_idx] = info.nr;
                if (db_sql_rev_parent[info.db_idx])
                    snprintf(last_sql_update[info.db_idx], MAX_PATH, "%s_%0*d_%s%s%s", info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
                else
                    sscanf(buffer, "%[^.]", last_sql_update[info.db_idx]);
            }
            new_sql_updates.erase(itr);
        }
    }

    pclose(cmd_pipe);

    if (!new_sql_updates.empty())
    {
        for (std::set<std::string>::iterator itr = new_sql_updates.begin(); itr != new_sql_updates.end(); ++itr)
            printf("%s\n", itr->c_str());
    }
    else
        printf("WARNING: no new sql updates found.\n");

    return true;
}
Ejemplo n.º 6
0
bool isPresent(const T *value, const std::set<const T *> &values) {
  auto result = std::find(values.begin(), values.end(), value);
  return result != values.end();
}
Ejemplo n.º 7
0
void inline instrumentert::instrument_minimum_interference_inserter(
  const std::set<event_grapht::critical_cyclet>& set_of_cycles)
{
  /* Idea:
     We solve this by a linear programming approach,
     using for instance glpk lib.

     Input: the edges to instrument E, the cycles C_j
     Pb: min sum_{e_i in E} d(e_i).x_i
         s.t. for all j, sum_{e_i in C_j} >= 1,
       where e_i is a pair to potentially instrument,
       x_i is a Boolean stating whether we instrument
       e_i, and d() is the cost of an instrumentation.
     Output: the x_i, saying which pairs to instrument

     For this instrumentation, we propose:
     d(poW*)=1
     d(poRW)=d(rfe)=2
     d(poRR)=3

     This function can be refined with the actual times
     we get in experimenting the different pairs in a
     single IRIW.
  */

#ifdef HAVE_GLPK
  /* first, identify all the unsafe pairs */
  std::set<event_grapht::critical_cyclet::delayt> edges;
  for(std::set<event_grapht::critical_cyclet>::iterator
    C_j=set_of_cycles.begin();
    C_j!=set_of_cycles.end();
    ++C_j)
    for(std::set<event_grapht::critical_cyclet::delayt>::const_iterator e_i=
      C_j->unsafe_pairs.begin();
      e_i!=C_j->unsafe_pairs.end();
      ++e_i)
      edges.insert(*e_i);

  glp_prob* lp;
  glp_iocp parm;
  glp_init_iocp(&parm);
  parm.msg_lev=GLP_MSG_OFF;
  parm.presolve=GLP_ON;

  lp=glp_create_prob();
  glp_set_prob_name(lp, "instrumentation optimisation");
  glp_set_obj_dir(lp, GLP_MIN);

  message.debug() << "edges: "<<edges.size()<<" cycles:"<<set_of_cycles.size()
    << messaget::eom;

  /* sets the variables and coefficients */
  glp_add_cols(lp, edges.size());
  std::size_t i=0;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
      e_i=edges.begin();
      e_i!=edges.end();
      ++e_i)
  {
    ++i;
    std::string name="e_"+std::to_string(i);
    glp_set_col_name(lp, i, name.c_str());
    glp_set_col_bnds(lp, i, GLP_LO, 0.0, 0.0);
    glp_set_obj_coef(lp, i, cost(*e_i));
    glp_set_col_kind(lp, i, GLP_BV);
  }

  /* sets the constraints (soundness): one per cycle */
  glp_add_rows(lp, set_of_cycles.size());
  i=0;
  for(std::set<event_grapht::critical_cyclet>::iterator
    C_j=set_of_cycles.begin();
    C_j!=set_of_cycles.end();
    ++C_j)
  {
    ++i;
    std::string name="C_"+std::to_string(i);
    glp_set_row_name(lp, i, name.c_str());
    glp_set_row_bnds(lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
  }

  const std::size_t mat_size=set_of_cycles.size()*edges.size();
  message.debug() << "size of the system: " << mat_size
    << messaget::eom;
  int* imat=(int*)malloc(sizeof(int)*(mat_size+1));
  int* jmat=(int*)malloc(sizeof(int)*(mat_size+1));
  double* vmat=(double*)malloc(sizeof(double)*(mat_size+1));

  /* fills the constraints coeff */
  /* tables read from 1 in glpk -- first row/column ignored */
  std::size_t col=1;
  std::size_t row=1;
  i=1;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
    e_i=edges.begin();
    e_i!=edges.end();
    ++e_i)
  {
    row=1;
    for(std::set<event_grapht::critical_cyclet>::iterator
      C_j=set_of_cycles.begin();
      C_j!=set_of_cycles.end();
      ++C_j)
    {
      imat[i]=row;
      jmat[i]=col;
      if(C_j->unsafe_pairs.find(*e_i)!=C_j->unsafe_pairs.end())
        vmat[i]=1.0;
      else
        vmat[i]=0.0;
      ++i;
      ++row;
    }
    ++col;
  }

#ifdef DEBUG
  for(i=1; i<=mat_size; ++i)
    message.statistics() <<i<<"["<<imat[i]<<","<<jmat[i]<<"]="<<vmat[i]
      << messaget::eom;
#endif

  /* solves MIP by branch-and-cut */
  glp_load_matrix(lp, mat_size, imat, jmat, vmat);
  glp_intopt(lp, &parm);

  /* loads results (x_i) */
  message.statistics() << "minimal cost: " << glp_mip_obj_val(lp)
    << messaget::eom;
  i=0;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
    e_i=edges.begin();
    e_i!=edges.end();
    ++e_i)
  {
    ++i;
    if(glp_mip_col_val(lp, i)>=1)
    {
      const abstract_eventt& first_ev=egraph[e_i->first];
      var_to_instr.insert(first_ev.variable);
      id2loc.insert(
        std::pair<irep_idt,source_locationt>(first_ev.variable,first_ev.source_location));
      if(!e_i->is_po)
      {
        const abstract_eventt& second_ev=egraph[e_i->second];
        var_to_instr.insert(second_ev.variable);
        id2loc.insert(
          std::pair<irep_idt,source_locationt>(second_ev.variable,second_ev.source_location));
      }
    }
  }

  glp_delete_prob(lp);
  free(imat);
  free(jmat);
  free(vmat);
#else
  throw "Sorry, minimum interference option requires glpk; "
        "please recompile goto-instrument with glpk.";
#endif
}
Ejemplo n.º 8
0
bool BlockFlow::identifyOutSet()
{
  bool MadeChange = false;
  std::vector<GlobalCheck*> outChecks;
  if (!isEntry && !killAll) {
    identifyInSet();
  #if DEBUG_GLOBAL
    errs() << "Generating Out-Set: " << blk->getName() << "\n";
  #endif
    // Identify checks from inSet that should be killed
    for (std::vector<GlobalCheck*>::iterator i = inSet.checks.begin(), e = inSet.checks.end();
            i != e; i++) {
      // For each global check, see if it survives past block, or if we can tell how variable changes
      GlobalCheck *chk = *i;
      std::set<Value*>::iterator it = storeSet.find(chk->var);
      if (it == storeSet.end()) {
        outChecks.push_back(chk);
      } else {
        ConstraintGraph::CompareEnum change = cg->identifyMemoryChange(chk->var);
        if (chk->isUpper) {
          // Upper-bound check
          switch (change) {
            case ConstraintGraph::EQUALS:
            case ConstraintGraph::LESS_THAN:
              outChecks.push_back(chk);
              break;
            default:
              break;
          }
        } else {
          // Lower-bound check
          switch (change) {
            case ConstraintGraph::EQUALS:
            case ConstraintGraph::GREATER_THAN:
              outChecks.push_back(chk);
              break;
            default:
              break;
          }
        }
      }
    }
  }
#if DEBUG_GLOBAL
  else {
    errs() << "Generating Out-Set: " << blk->getName() << "\n";
  }
#endif
  // Just identify checks that are live at the end of set
  for (std::vector<GlobalCheck*>::iterator i = globalChecks.begin(), e = globalChecks.end();
              i != e; i++) {
    GlobalCheck *chk = *i;
    bool add = true;
    for (unsigned int o = 0; o < outChecks.size(); o++) {
      GlobalCheck *oCheck = outChecks.at(o);
      ConstantInt *const1 = dyn_cast<ConstantInt>(chk->var);
      ConstantInt *const2 = dyn_cast<ConstantInt>(oCheck->var);
      if (chk->isUpper && oCheck->isUpper) {
        // Both upper bounds checks
        if (const1 != NULL && const2 != NULL) {
          // If both constants, replace with the more strict version
          if (const1->getSExtValue() > const2->getSExtValue()) {
            outChecks.at(o) = chk;
          }
          add = false;
          break;
        } else if (const1 == NULL && const2 == NULL) {
          if (chk->var == oCheck->var) {
            ConstantInt *bound1 = dyn_cast<ConstantInt>(chk->bound);
            ConstantInt *bound2 = dyn_cast<ConstantInt>(oCheck->bound);
            if (bound1 != NULL && bound2 != NULL) {
              if (bound1->getZExtValue() < bound2->getZExtValue()) {
                outChecks.at(o) = chk;
              }
              add = false;
              break;
            } else if (bound1 == NULL && bound2 == NULL) {
              if (bound1 == bound2) {
                add = false;
                break;
              }
            }
          }
        }
      } else if (!chk->isUpper && !oCheck->isUpper) {
        // Both lower bounds checks
        if (const1 != NULL && const2 != NULL) {
          // If both constants, replace with the more strict version
          if (const1->getSExtValue() < const2->getSExtValue()) {
            outChecks.at(o) =  chk;
          }
          add = false;
          break;
        } else if (const1 == NULL && const2 == NULL) {
          if (chk->var == oCheck->var) {
            add = false;
            break;
          }
        }
      }
    }
    if (add) {
      outChecks.push_back(chk);
    }
  }

  if (isEntry && outChecks.empty()) {
    outSet.allChecks = false;
    return true;
  }

  if (outChecks.empty()) {
    if (inSet.allChecks) {
      bool oldState = outSet.allChecks;
      outSet.checks.clear();
      outSet.allChecks = true;
      return oldState != true;
    } else {
      outSet.allChecks = false;
      if (outSet.checks.empty()) {
        return false;
      } else {
        outSet.checks.clear();
        return true;
      }
    }
  }

  for (std::vector<GlobalCheck*>::iterator i = outChecks.begin(), e = outChecks.end(); i != e; i++) {
  #if DEBUG_GLOBAL
    errs() << "Adding Check to Out Set:\n";
    (*i)->print();
  #endif
    MadeChange |= outSet.addAvailableCheck(*i);
  }
  return MadeChange;
}
void
FindFilesOnVol(const std::string &verref,
               const std::set<std::string> &volset,
               SeenVers &seen,
               RebuildVers &found,
               RebuildNode::CurrentStack &currentStack,
               int &count, int interval)
{
  if (seen.find(verref) != seen.end()) {
    seen[verref]->AddUser(currentStack);
    return;
  }

  AssetVersion version(verref);
  if (!version) {
    notify(NFY_WARN, "Unable to load asset version %s",
           version.Ref().c_str());
  }

  RebuildNode *node = new RebuildNode(verref, currentStack);
  CurrentStackGuard stackGuard(currentStack, node);

  seen.insert(make_pair(verref, node));

  if (interval && (++count % interval == 0)) {
    fprintf(stderr, "\r%d", count);
  }


  if (version->IsLeaf() && (version->state == AssetDefs::Succeeded)) {

    std::vector<std::string> outfiles;
    version->GetOutputFilenames(outfiles);

    for (std::vector<std::string>::const_iterator outfile =
           outfiles.begin(); outfile != outfiles.end(); ++outfile) {
      khFusionURI uri(theVolumeManager.DeduceURIFromPath(*outfile));
      if (uri.Volume().empty()) {
        // non-file outfile (GFS?). Do nothing.
      } else if (volset.find(uri.Volume()) != volset.end()) {
        // This outfile is on a volume we care about. Remember the
        // versionref.

        node->rebuild = true;
        found.insert(node);

        // once we find even one outfile, we're done. We'll have to run
        // the whole command anyway. No sense checking other outfiles.
        break;
      } else {
        // On a volume we don't care about. Do Nothing
      }
    }
  }

  for (std::vector<std::string>::const_iterator input =
         version->inputs.begin();
       input != version->inputs.end(); ++input) {
    FindFilesOnVol(*input, volset, seen,
                   found, currentStack,
                   count, interval);
  }
  if (!version->IsLeaf()) {
    for (std::vector<std::string>::const_iterator child =
           version->children.begin();
         child != version->children.end(); ++child) {
      FindFilesOnVol(*child, volset, seen,
                     found, currentStack,
                     count, interval);
    }
  }
}
Ejemplo n.º 10
0
 void check_out(void * const This)
 {
     BOOST_TEST(objs.find(This) != objs.end());
     objs.erase(This);
 }
Ejemplo n.º 11
0
 static void free(char * const block)
 {
     BOOST_TEST(allocated_blocks.find(block) != allocated_blocks.end());
     allocated_blocks.erase(block);
     UserAllocator::free(block);
 }
Ejemplo n.º 12
0
 void check_in(void * const This)
 {
     BOOST_TEST(objs.find(This) == objs.end());
     objs.insert(This);
 }
Ejemplo n.º 13
0
        void SetData(uint32 type, uint32 data)
        {
            switch (type)
            {
            case TYPE_MOGRAINE_AND_WHITE_EVENT:
                if (data == IN_PROGRESS)
                    DoUseDoorOrButton(DoorHighInquisitorGUID);
                if (data == FAIL)
                    DoUseDoorOrButton(DoorHighInquisitorGUID);

                Encounter[0] = data;
                break;
            case GAMEOBJECT_PUMPKIN_SHRINE:
                HandleGameObject(PumpkinShrineGUID, false);
                break;
            case DATA_HORSEMAN_EVENT:
                Encounter[1] = data;
                if (data == DONE)
                {
                    for (std::set<uint64>::const_iterator itr = HorsemanAdds.begin(); itr != HorsemanAdds.end(); ++itr)
                    {
                        Creature* add = instance->GetCreature(*itr);
                        if (add && add->isAlive())
                            add->Kill(add);
                    }
                    HorsemanAdds.clear();
                    HandleGameObject(PumpkinShrineGUID, false);
                }
                break;
            }
        }
Ejemplo n.º 14
0
bool isConstExpression(const Token *tok, const std::set<std::string> &constFunctions)
{
    if (!tok)
        return true;
    if (tok->isName() && tok->next()->str() == "(") {
        if (!tok->function() && !Token::Match(tok->previous(), ".|::") && constFunctions.find(tok->str()) == constFunctions.end())
            return false;
        else if (tok->function() && !tok->function()->isConst())
            return false;
    }
    if (tok->tokType() == Token::eIncDecOp)
        return false;
    // bailout when we see ({..})
    if (tok->str() == "{")
        return false;
    return isConstExpression(tok->astOperand1(),constFunctions) && isConstExpression(tok->astOperand2(),constFunctions);
}
Ejemplo n.º 15
0
::std::string to_string(::std::set<T> const& s)
{
	return to_string(s.begin(), s.end());
}
Ejemplo n.º 16
0
/// Based on GetAllUndefinedSymbols() from LLVM3.2
///
/// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
/// exist in an LLVM module. This is a bit tricky because there may be two
/// symbols with the same name but different LLVM types that will be resolved to
/// each other but aren't currently (thus we need to treat it as resolved).
///
/// Inputs:
///  M - The module in which to find undefined symbols.
///
/// Outputs:
///  UndefinedSymbols - A set of C++ strings containing the name of all
///                     undefined symbols.
///
static void
GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
  static const std::string llvmIntrinsicPrefix="llvm.";
  std::set<std::string> DefinedSymbols;
  UndefinedSymbols.clear();
  KLEE_DEBUG_WITH_TYPE("klee_linker",
                       dbgs() << "*** Computing undefined symbols ***\n");

  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
    if (I->hasName()) {
      if (I->isDeclaration())
        UndefinedSymbols.insert(I->getName());
      else if (!I->hasLocalLinkage()) {
#if LLVM_VERSION_CODE < LLVM_VERSION(3, 5)
            assert(!I->hasDLLImportLinkage() && "Found dllimported non-external symbol!");
#else
            assert(!I->hasDLLImportStorageClass() && "Found dllimported non-external symbol!");
#endif
        DefinedSymbols.insert(I->getName());
      }
    }

  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
       I != E; ++I)
    if (I->hasName()) {
      if (I->isDeclaration())
        UndefinedSymbols.insert(I->getName());
      else if (!I->hasLocalLinkage()) {
#if LLVM_VERSION_CODE < LLVM_VERSION(3, 5)
            assert(!I->hasDLLImportLinkage() && "Found dllimported non-external symbol!");
#else
            assert(!I->hasDLLImportStorageClass() && "Found dllimported non-external symbol!");
#endif
        DefinedSymbols.insert(I->getName());
      }
    }

  for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
       I != E; ++I)
    if (I->hasName())
      DefinedSymbols.insert(I->getName());


  // Prune out any defined symbols from the undefined symbols set
  // and other symbols we don't want to treat as an undefined symbol
  std::vector<std::string> SymbolsToRemove;
  for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
       I != UndefinedSymbols.end(); ++I )
  {
    if (DefinedSymbols.count(*I))
    {
      SymbolsToRemove.push_back(*I);
      continue;
    }

    // Strip out llvm intrinsics
    if ( (I->size() >= llvmIntrinsicPrefix.size() ) &&
       (I->compare(0, llvmIntrinsicPrefix.size(), llvmIntrinsicPrefix) == 0) )
    {
      KLEE_DEBUG_WITH_TYPE("klee_linker", dbgs() << "LLVM intrinsic " << *I <<
                      " has will be removed from undefined symbols"<< "\n");
      SymbolsToRemove.push_back(*I);
      continue;
    }

    // Symbol really is undefined
    KLEE_DEBUG_WITH_TYPE("klee_linker",
                         dbgs() << "Symbol " << *I << " is undefined.\n");
  }

  // Remove KLEE intrinsics from set of undefined symbols
  for (SpecialFunctionHandler::const_iterator sf = SpecialFunctionHandler::begin(),
       se = SpecialFunctionHandler::end(); sf != se; ++sf)
  {
    if (UndefinedSymbols.find(sf->name) == UndefinedSymbols.end())
      continue;

    SymbolsToRemove.push_back(sf->name);
    KLEE_DEBUG_WITH_TYPE("klee_linker",
                         dbgs() << "KLEE intrinsic " << sf->name <<
                         " has will be removed from undefined symbols"<< "\n");
  }

  // Now remove the symbols from undefined set.
  for (size_t i = 0, j = SymbolsToRemove.size(); i < j; ++i )
    UndefinedSymbols.erase(SymbolsToRemove[i]);

  KLEE_DEBUG_WITH_TYPE("klee_linker",
                       dbgs() << "*** Finished computing undefined symbols ***\n");
}
Ejemplo n.º 17
0
bool is_ignored(int i) {
  static std::set<int> ignore = {};
  return ignore.find(i) != ignore.end();
}
Ejemplo n.º 18
0
bool ObjectSelection::add(std::set<long int> ids)
{
	selections.insert(ids.begin(),ids.end());
	emit changed();
	return true;
}
Ejemplo n.º 19
0
void CSettingManager::RegisterCallback(ISettingCallback *callback, const std::set<std::string> &settingList)
{
	XR::CSingleLock lock(m_settingsCritical);
	if (callback == nullptr)
		return;

	for (std::set<std::string>::const_iterator settingIt = settingList.begin(); settingIt != settingList.end(); ++settingIt) {
		std::string id = *settingIt;
		StringUtils::ToLower(id);

		SettingMap::iterator setting = m_settings.find(id);
		if (setting == m_settings.end()) {
			if (m_initialized)
				continue;

			Setting tmpSetting = { NULL };
			std::pair<SettingMap::iterator, bool> tmpIt = m_settings.insert(make_pair(id, tmpSetting));
			setting = tmpIt.first;
		}

		setting->second.callbacks.insert(callback);
	}
}
Ejemplo n.º 20
0
bool ObjectSelection::remove(std::set<long int> ids)
{
	selections.erase(ids.begin(),ids.end());
	emit changed();
	return true;
}
Ejemplo n.º 21
0
void UpdateData::AddOutOfRangeGUID(std::set<uint64>& guids)
{
    m_outOfRangeGUIDs.insert(guids.begin(), guids.end());
}
Ejemplo n.º 22
0
template <class C, class V> inline
bool CubitLoops<C, V>::recursive_make_loop(V* start_vertex, CoEdge* coedge,
    std::set<CoEdge* >& used_coedges,
    std::multimap<V*, CoEdge*>& start_coedge_map,
    std::vector<CoEdge*>& loop)
{
  V* curr_vertex;
  if (coedge->sense == CUBIT_FORWARD)
    curr_vertex = coedge->end;
  else
    curr_vertex = coedge->start;
  loop.push_back(coedge);
  used_coedges.insert(coedge);

  while (curr_vertex != start_vertex) 
  {
    typename std::multimap<V*, CoEdge*>::iterator iter;
    typename std::multimap<V*, CoEdge*>::iterator last;

    iter = start_coedge_map.lower_bound(curr_vertex);
    last = start_coedge_map.upper_bound(curr_vertex);

    std::vector<CoEdge*> possible_coedges;
    for (/*preinitialized*/; iter != last; iter++)
    {
      if (used_coedges.find(iter->second) == used_coedges.end())
        possible_coedges.push_back(iter->second);
    }

    if (possible_coedges.size() == 0)
      return false;
    else if (possible_coedges.size() == 1)
    {
      coedge = possible_coedges[0];
      loop.push_back(coedge);
      used_coedges.insert(coedge);
      if (coedge->sense == CUBIT_FORWARD)
        curr_vertex = coedge->end;
      else
        curr_vertex = coedge->start;
    }
    else
    {
      for (size_t i=0; i<possible_coedges.size(); i++)
      {
        std::vector<CoEdge*> sub_loop;
        if (recursive_make_loop(curr_vertex, possible_coedges[i], used_coedges, start_coedge_map, sub_loop) )
        {
          loop.insert(loop.end(), sub_loop.begin(), sub_loop.end());
        }
        else
        {
          for (size_t j=0; j<sub_loop.size(); j++)
            used_coedges.erase(sub_loop[j]);
          coedge = possible_coedges[i];
        }
      }
      loop.push_back(coedge);
      used_coedges.insert(coedge);
      if (coedge->sense == CUBIT_FORWARD)
        curr_vertex = coedge->end;
      else
        curr_vertex = coedge->start;
    }
  }

  return true;
}
            void Update(uint32 diff)
            {
                if (CageTimer)
                {
                    if (CageTimer <= diff)
                    {
                        Creature* Magtheridon = instance->GetCreature(MagtheridonGUID);
                        if (Magtheridon && Magtheridon->IsAlive())
                        {
                            Magtheridon->ClearUnitState(UNIT_STATE_STUNNED);
                            Magtheridon->AI()->AttackStart(Magtheridon->SelectNearestTarget(999));
                        }
                        CageTimer = 0;
                    } else CageTimer -= diff;
                }

                if (RespawnTimer)
                {
                    if (RespawnTimer <= diff)
                    {
                        for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                        {
                            if (Creature* Channeler = instance->GetCreature(*i))
                            {
                                if (Channeler->IsAlive())
                                    Channeler->AI()->EnterEvadeMode();
                                else
                                    Channeler->Respawn();
                            }
                        }
                        RespawnTimer = 0;
                    } else RespawnTimer -= diff;
                }
            }
Ejemplo n.º 24
0
bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
  bool print_sample_count = false;
  std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
  for (size_t i = 0; i < args.size(); ++i) {
    if (args[i] == "-b") {
      use_branch_address_ = true;
    } else if (args[i] == "--children") {
      accumulate_callchain_ = true;
    } else if (args[i] == "-g") {
      print_callgraph_ = true;
      accumulate_callchain_ = true;
    } else if (args[i] == "-i") {
      if (!NextArgumentOrError(args, &i)) {
        return false;
      }
      record_filename_ = args[i];

    } else if (args[i] == "-n") {
      print_sample_count = true;

    } else if (args[i] == "--no-demangle") {
      DsoFactory::SetDemangle(false);

    } else if (args[i] == "--sort") {
      if (!NextArgumentOrError(args, &i)) {
        return false;
      }
      sort_keys = android::base::Split(args[i], ",");
    } else if (args[i] == "--symfs") {
      if (!NextArgumentOrError(args, &i)) {
        return false;
      }
      if (!DsoFactory::SetSymFsDir(args[i])) {
        return false;
      }
    } else {
      ReportUnknownOption(args, i);
      return false;
    }
  }

  if (!accumulate_callchain_) {
    displayable_items_.push_back(
        std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_, "Overhead")));
  } else {
    displayable_items_.push_back(
        std::unique_ptr<Displayable>(new AccumulatedOverheadItem(*sample_tree_)));
    displayable_items_.push_back(std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_)));
  }
  if (print_sample_count) {
    displayable_items_.push_back(std::unique_ptr<Displayable>(new SampleCountItem));
  }
  for (auto& key : sort_keys) {
    if (!use_branch_address_ && branch_sort_keys.find(key) != branch_sort_keys.end()) {
      LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
      return false;
    }
    if (key == "pid") {
      PidItem* item = new PidItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "tid") {
      TidItem* item = new TidItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "comm") {
      CommItem* item = new CommItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "dso") {
      DsoItem* item = new DsoItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "symbol") {
      SymbolItem* item = new SymbolItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "dso_from") {
      DsoFromItem* item = new DsoFromItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "dso_to") {
      DsoToItem* item = new DsoToItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "symbol_from") {
      SymbolFromItem* item = new SymbolFromItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else if (key == "symbol_to") {
      SymbolToItem* item = new SymbolToItem;
      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
      comparable_items_.push_back(item);
    } else {
      LOG(ERROR) << "Unknown sort key: " << key;
      return false;
    }
  }
  return true;
}
Ejemplo n.º 25
0
bool convert_sql_updates()
{
    if (new_sql_updates.empty()) return true;

    printf("+ converting sql updates\n");

    // rename the sql update files and add the required update statement
    for (std::set<std::string>::iterator itr = new_sql_updates.begin(); itr != new_sql_updates.end(); ++itr)
    {
        sql_update_info info;
        if (!get_sql_update_info(itr->c_str(), info)) return false;
        if (info.db_idx == NUM_DATABASES) return false;

        // generating the new name should work for updates with or without a rev
        char src_file[MAX_PATH], new_name[MAX_PATH], new_req_name[MAX_PATH], dst_file[MAX_PATH];
        snprintf(src_file, MAX_PATH, "%s%s/%s", path_prefix, sql_update_dir, itr->c_str());
        snprintf(new_name, MAX_PATH, REV_PRINT "_%s_%0*d_%s%s%s", rev, info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
        snprintf(dst_file, MAX_PATH, "%s%s/%s.sql", path_prefix, sql_update_dir, new_name);

        if (db_sql_rev_parent[info.db_idx])
            snprintf(new_req_name, MAX_PATH, "%s_%0*d_%s%s%s", info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
        else
            strncpy(new_req_name, new_name, MAX_PATH);

        FILE* fin = fopen(src_file, "r");
        if (!fin) return false;

        std::ostringstream out_buff;

        // add the update requirements for non-parent-controlled revision sql update
        if (!db_sql_rev_parent[info.db_idx])
        {
            // add the update requirements
            out_buff << "ALTER TABLE " << db_version_table[info.db_idx]
                     << " CHANGE COLUMN required_" << last_sql_update[info.db_idx]
                     << " required_" << new_name << " bit;\n\n";

            // skip the first one or two lines from the input
            // if it already contains update requirements
            if (fgets(buffer, MAX_BUF, fin))
            {
                char dummy[MAX_BUF];
                if (sscanf(buffer, "ALTER TABLE %s CHANGE COLUMN required_%s required_%s bit", dummy, dummy, dummy) == 3)
                {
                    if (fgets(buffer, MAX_BUF, fin) && buffer[0] != '\n')
                        out_buff << buffer;
                }
                else
                    out_buff << buffer;
            }
        }

        // copy the rest of the file
        while (fgets(buffer, MAX_BUF, fin))
            out_buff << buffer;

        fclose(fin);

        FILE* fout = fopen(dst_file, "w");
        if (!fout) { fclose(fin); return false; }

        fprintf(fout, "%s", out_buff.str().c_str());

        fclose(fout);

        // rename the file in git
        snprintf(cmd, MAX_CMD, "git add %s", dst_file);
        system_switch_index(cmd);

        // delete src file if it different by name from dst file
        if (strncmp(src_file, dst_file, MAX_PATH))
        {
            snprintf(cmd, MAX_CMD, "git rm --quiet %s", src_file);
            system_switch_index(cmd);
        }

        // update the last sql update for the current database
        strncpy(last_sql_update[info.db_idx], new_req_name, MAX_PATH);
    }

    return true;
}
Ejemplo n.º 26
0
void actionCollect(const std::string &filename, enum CollectingMode mode, StatisticsCollection &statisticsCollection, HistogramCollection &histogramCollection, bool mwaChannels, size_t flaggedTimesteps, const std::set<size_t> &flaggedAntennae)
{
	MeasurementSet *ms = new MeasurementSet(filename);
	const unsigned polarizationCount = ms->GetPolarizationCount();
	const unsigned bandCount = ms->BandCount();
	const bool ignoreChannelZero = ms->ChannelZeroIsRubish();
	const std::string stationName = ms->GetStationName();
	BandInfo *bands = new BandInfo[bandCount];
	double **frequencies = new double*[bandCount];
	unsigned totalChannels = 0;
	for(unsigned b=0;b<bandCount;++b)
	{
		bands[b] = ms->GetBandInfo(b);
		frequencies[b] = new double[bands[b].channels.size()];
		totalChannels += bands[b].channels.size();
		for(unsigned c=0;c<bands[b].channels.size();++c)
		{
			frequencies[b][c] = bands[b].channels[c].frequencyHz;
		}
	}
	delete ms;
	
	std::cout
		<< "Polarizations: " << polarizationCount << '\n'
		<< "Bands: " << bandCount << '\n'
		<< "Channels/band: " << (totalChannels / bandCount) << '\n';
	if(ignoreChannelZero)
		std::cout << "Channel zero will be ignored, as this looks like a LOFAR data set with bad channel 0.\n";
	else
		std::cout << "Channel zero will be included in the statistics, as it seems that channel 0 is okay.\n";
	
	// Initialize statisticscollection
	statisticsCollection.SetPolarizationCount(polarizationCount);
	if(mode == CollectDefault)
	{
		for(unsigned b=0;b<bandCount;++b)
		{
			if(ignoreChannelZero)
				statisticsCollection.InitializeBand(b, (frequencies[b]+1), bands[b].channels.size()-1);
			else
				statisticsCollection.InitializeBand(b, frequencies[b], bands[b].channels.size());
		}
	}
	// Initialize Histograms collection
	histogramCollection.SetPolarizationCount(polarizationCount);

	// get columns
	casa::Table table(filename, casa::Table::Update);
	const char *dataColumnName = "DATA";
	casa::ROArrayColumn<casa::Complex> dataColumn(table, dataColumnName);
	casa::ROArrayColumn<bool> flagColumn(table, "FLAG");
	casa::ROScalarColumn<double> timeColumn(table, "TIME");
	casa::ROScalarColumn<int> antenna1Column(table, "ANTENNA1"); 
	casa::ROScalarColumn<int> antenna2Column(table, "ANTENNA2");
	casa::ROScalarColumn<int> windowColumn(table, "DATA_DESC_ID");
	
	std::cout << "Collecting statistics..." << std::endl;
	
	size_t channelCount = bands[0].channels.size();
	bool correlatorFlags[channelCount], correlatorFlagsForBadAntenna[channelCount];
	for(size_t ch=0; ch!=channelCount; ++ch)
	{
		correlatorFlags[ch] = false;
		correlatorFlagsForBadAntenna[ch] = true;
	}
	
	if(mwaChannels)
	{
		if(channelCount%24 != 0)
			std::cout << "MWA channels requested, but nr of channels not a multiply of 24. Ignoring.\n";
		else {
			size_t chanPerSb = channelCount/24;
			for(size_t x=0;x!=24;++x)
			{
				correlatorFlags[x*chanPerSb] = true;
				correlatorFlags[x*chanPerSb + chanPerSb/2] = true;
				correlatorFlags[x*chanPerSb + chanPerSb-1] = true;
			}
		}
	}
	
	const unsigned nrow = table.nrow();
	size_t timestepIndex = (size_t) -1;
	double prevtime = -1.0;
	for(unsigned row = 0; row!=nrow; ++row)
	{
		const double time = timeColumn(row);
		const unsigned antenna1Index = antenna1Column(row);
		const unsigned antenna2Index = antenna2Column(row);
		const unsigned bandIndex = windowColumn(row);
		
		if(time != prevtime)
		{
			++timestepIndex;
			prevtime = time;
		}
		
		const BandInfo &band = bands[bandIndex];
		
		const casa::Array<casa::Complex> dataArray = dataColumn(row);
		const casa::Array<bool> flagArray = flagColumn(row);
		
		std::complex<float> *samples[polarizationCount];
		bool *isRFI[polarizationCount];
		for(unsigned p = 0; p < polarizationCount; ++p)
		{
			isRFI[p] = new bool[band.channels.size()];
			samples[p] = new std::complex<float>[band.channels.size()];
		}
		const bool antennaIsFlagged =
			flaggedAntennae.find(antenna1Index) != flaggedAntennae.end() ||
			flaggedAntennae.find(antenna2Index) != flaggedAntennae.end();
		
		casa::Array<casa::Complex>::const_iterator dataIter = dataArray.begin();
		casa::Array<bool>::const_iterator flagIter = flagArray.begin();
		const unsigned startChannel = ignoreChannelZero ? 1 : 0;
		if(ignoreChannelZero)
		{
			for(unsigned p = 0; p < polarizationCount; ++p)
			{
				++dataIter;
				++flagIter;
			}
		}
		for(unsigned channel = startChannel ; channel<band.channels.size(); ++channel)
		{
			for(unsigned p = 0; p < polarizationCount; ++p)
			{
				samples[p][channel - startChannel] = *dataIter;
				isRFI[p][channel - startChannel] = *flagIter;
				
				++dataIter;
				++flagIter;
			}
		}
		
		for(unsigned p = 0; p < polarizationCount; ++p)
		{
			switch(mode)
			{
				case CollectDefault:
					if(antennaIsFlagged || timestepIndex < flaggedTimesteps)
						statisticsCollection.Add(antenna1Index, antenna2Index, time, bandIndex, p, &samples[p]->real(), &samples[p]->imag(), isRFI[p], correlatorFlagsForBadAntenna, band.channels.size() - startChannel, 2, 1, 1);
					else
						statisticsCollection.Add(antenna1Index, antenna2Index, time, bandIndex, p, &samples[p]->real(), &samples[p]->imag(), isRFI[p], correlatorFlags, band.channels.size() - startChannel, 2, 1, 1);
					break;
				case CollectHistograms:
					histogramCollection.Add(antenna1Index, antenna2Index, p, samples[p], isRFI[p], band.channels.size() - startChannel);
					break;
			}
		}

		for(unsigned p = 0; p < polarizationCount; ++p)
		{
			delete[] isRFI[p];
			delete[] samples[p];
		}
		
		reportProgress(row, nrow);
	}
	
	for(unsigned b=0;b<bandCount;++b)
		delete[] frequencies[b];
	delete[] frequencies;
	delete[] bands;
	std::cout << "100\n";
}
Ejemplo n.º 27
0
void ElasticFoundationForceImpl::processContact
   (const State& state, 
    ContactSurfaceIndex meshIndex, ContactSurfaceIndex otherBodyIndex, 
    const Parameters& param, const std::set<int>& insideFaces,
    Real areaScale, Vector_<SpatialVec>& bodyForces, Real& pe) const 
{
    const ContactGeometry& otherObject = subsystem.getBodyGeometry(set, otherBodyIndex);
    const MobilizedBody& body1 = subsystem.getBody(set, meshIndex);
    const MobilizedBody& body2 = subsystem.getBody(set, otherBodyIndex);
    const Transform t1g = body1.getBodyTransform(state)*subsystem.getBodyTransform(set, meshIndex); // mesh to ground
    const Transform t2g = body2.getBodyTransform(state)*subsystem.getBodyTransform(set, otherBodyIndex); // other object to ground
    const Transform t12 = ~t2g*t1g; // mesh to other object

    // Loop over all the springs, and evaluate the force from each one.

    for (std::set<int>::const_iterator iter = insideFaces.begin(); 
                                       iter != insideFaces.end(); ++iter) {
        int face = *iter;
        UnitVec3 normal;
        bool inside;
        Vec3 nearestPoint = otherObject.findNearestPoint(t12*param.springPosition[face], inside, normal);
        if (!inside)
            continue;
        
        // Find how much the spring is displaced.
        
        nearestPoint = t2g*nearestPoint;
        const Vec3 springPosInGround = t1g*param.springPosition[face];
        const Vec3 displacement = nearestPoint-springPosInGround;
        const Real distance = displacement.norm();
        if (distance == 0.0)
            continue;
        const Vec3 forceDir = displacement/distance;
        
        // Calculate the relative velocity of the two bodies at the contact point.
        
        const Vec3 station1 = body1.findStationAtGroundPoint(state, nearestPoint);
        const Vec3 station2 = body2.findStationAtGroundPoint(state, nearestPoint);
        const Vec3 v1 = body1.findStationVelocityInGround(state, station1);
        const Vec3 v2 = body2.findStationVelocityInGround(state, station2);
        const Vec3 v = v2-v1;
        const Real vnormal = dot(v, forceDir);
        const Vec3 vtangent = v-vnormal*forceDir;
        
        // Calculate the damping force.
        
        const Real area = areaScale * param.springArea[face];
        const Real f = param.stiffness*area*distance*(1+param.dissipation*vnormal);
        Vec3 force = (f > 0 ? f*forceDir : Vec3(0));
        
        // Calculate the friction force.
        
        const Real vslip = vtangent.norm();
        if (f > 0 && vslip != 0) {
            const Real vrel = vslip/transitionVelocity;
            const Real ffriction = 
                f*(std::min(vrel, Real(1))
                 *(param.dynamicFriction+2*(param.staticFriction-param.dynamicFriction)
                 /(1+vrel*vrel))+param.viscousFriction*vslip);
            force += ffriction*vtangent/vslip;
        }

        body1.applyForceToBodyPoint(state, station1, force, bodyForces);
        body2.applyForceToBodyPoint(state, station2, -force, bodyForces);
        pe += param.stiffness*area*displacement.normSqr()/2;
    }
}
Ejemplo n.º 28
0
inline bool Controller::IsRouteSettled( const RouteID _id ) const {
	return m_unsettledRoutes.find( _id ) == m_unsettledRoutes.end();
}
Ejemplo n.º 29
0
 std::vector<std::string> toposort() {
     std::vector<std::string> result;
     std::vector<std::set<Class>::iterator> classItsWithNoPrereqs;
     for (auto targetIt = classes.begin(); targetIt != classes.end();
          ++targetIt) {
         bool hasPrereq = false;
         for (auto potentialPrereqIt = classes.begin();
              potentialPrereqIt != classes.end(); ++potentialPrereqIt) {
             int potentialPrereqIndex = std::distance(classes.begin(),
                                                      potentialPrereqIt);
             int targetIndex = std::distance(classes.begin(), targetIt);
             if (adjMat[potentialPrereqIndex][targetIndex]) {
                 hasPrereq = true;
                 break;
             }
         }
         if (!hasPrereq) {
             classItsWithNoPrereqs.push_back(targetIt);
         }
     }
     while (!classItsWithNoPrereqs.empty()) {
         // Find a class with no pre-reqs (resolve ties by # then dept)
         std::sort(classItsWithNoPrereqs.begin(),
                   classItsWithNoPrereqs.end(),
                   [](std::set<Class>::iterator c1,
                      std::set<Class>::iterator c2) { return *c1 < *c2; });
         auto firstClassIt = classItsWithNoPrereqs.begin();
         auto prereqIt = *firstClassIt;
         int prereqIndex = std::distance(classes.begin(), prereqIt);
         result.push_back(*prereqIt); // Calls std::string() implicitly
         classItsWithNoPrereqs.erase(firstClassIt);
         for (auto potentialTargetIt = classes.begin();
              potentialTargetIt != classes.end(); ++potentialTargetIt) {
             int potentialTargetIndex = std::distance(classes.begin(),
                                                      potentialTargetIt);
             if (adjMat[prereqIndex][potentialTargetIndex]) {
                 adjMat[prereqIndex][potentialTargetIndex] = false;
                 --numEdges;
                 // Check for other incoming edges to the target
                 bool hasOtherIncomingEdges = false;
                 for (auto potentialPrereqIt = classes.begin();
                      potentialPrereqIt != classes.end();
                      ++potentialPrereqIt) {
                     int potentialPrereqIndex =
                         std::distance(classes.begin(),
                                       potentialPrereqIt);
                     if (adjMat[potentialPrereqIndex]
                               [potentialTargetIndex]) {
                         hasOtherIncomingEdges = true;
                         break;
                     }
                 }
                 if (!hasOtherIncomingEdges) {
                     classItsWithNoPrereqs.push_back(potentialTargetIt);
                 }
             }
         }
     }
     if (0 != numEdges) {
         return {};
     }
     return result;
 }
BOOL LLWindowManager::isWindowValid(LLWindow *window)
{
	return sWindowList.find(window) != sWindowList.end();
}