Exemplo n.º 1
0
void DateSpan::merge(const std::vector<DateSpan>& in, std::vector<DateSpan>* out)
{
    using DatePoints = std::map<const DateTime*, int, DateTimeCompare>;

    static const int FROM_DATE = 0x1;
    static const int TO_DATE   = 0x2;

    DatePoints date;
    for (auto in_iter = in.begin(); in_iter != in.end(); ++in_iter)
    {
        date[&((*in_iter).from_date())] |= FROM_DATE;
        date[&((*in_iter).to_date())]   |= TO_DATE;
    }

    auto date_next_iter = date.begin();
    auto date_iter = date.begin();
    for(++date_next_iter; date_next_iter != date.end(); ++date_iter, ++date_next_iter)
    {
        DateTime curr_from_date = *((*date_iter).first);
        DateTime curr_to_date = *((*date_next_iter).first);

        // 该日期不是终止日期,则去掉当前天,即日期前移1天
        if (((*date_next_iter).second & TO_DATE) == 0)
        {
            curr_to_date.addDay(1);
        }

        // 确保DatePeriod:from_date < to_date
        if (!(curr_from_date < curr_to_date))
        {
            continue;
        }

        char curr_period = 0;
        for (auto in_iter = in.begin(); in_iter != in.end(); ++in_iter)
        {
            if ((*in_iter).from_date() <= curr_from_date && curr_to_date <= (*in_iter).to_date())
            {
                curr_period |= (*in_iter).period();
            }
        }

        if (curr_period == 0)
        {
            continue;
        }

        DateSpan current(curr_from_date, curr_to_date, curr_period);
        bool need_pushed = true;
        if ((*out).size() > 0)
        {
            DateSpan& last = (*out)[(*out).size()-1];
            if (canBeMerged(last, current))
            {
                last.set_to_date(current.to_date());
                last.set_period(last.period() | current.period());
                need_pushed = false;
            }
        }
        if (need_pushed)
        {
            (*out).push_back(current);
        }
    }

    for (auto iter = (*out).begin(); iter != (*out).end(); ++iter)
    {
        (*iter).normalize();
    }
}
Exemplo n.º 2
0
 void do_stuff(const std::vector<int>& v, int i) {
   std::copy(v.begin(),v.end(), std::ostream_iterator<int>(std::cout," "));
   std::cout << " i = " << i << std::endl;
 }
variant unit_callable::get_value(const std::string& key) const
{
    if(key == "x") {
        if (loc_==map_location::null_location) {
            return variant();
        } else {
            return variant(loc_.x+1);
        }
    } else if(key == "y") {
        if (loc_==map_location::null_location) {
            return variant();
        } else {
            return variant(loc_.y+1);
        }
    } else if(key == "loc") {
        if (loc_==map_location::null_location) {
            return variant();
        } else {
            return variant(new location_callable(loc_));
        }
    } else if(key == "id") {
        return variant(u_.id());
    } else if(key == "type") {
        return variant(u_.type_id());
    } else if(key == "name") {
        return variant(u_.name());
    } else if(key == "usage") {
        return variant(u_.usage());
    } else if(key == "leader") {
        return variant(u_.can_recruit());
    } else if(key == "undead") {
        return variant(u_.get_state("not_living") ? 1 : 0);
    } else if(key == "attacks") {
        const std::vector<attack_type>& att = u_.attacks();
        std::vector<variant> res;

        for( std::vector<attack_type>::const_iterator i = att.begin(); i != att.end(); ++i)
            res.push_back(variant(new attack_type_callable(*i)));
        return variant(&res);
    } else if(key == "abilities") {
        std::vector<std::string> abilities = u_.get_ability_list();
        std::vector<variant> res;

        if (abilities.empty())
            return variant( &res );

        for (std::vector<std::string>::iterator it = abilities.begin(); it != abilities.end(); ++it)
        {
            res.push_back( variant(*it) );
        }
        return variant( &res );
    } else if(key == "hitpoints") {
        return variant(u_.hitpoints());
    } else if(key == "max_hitpoints") {
        return variant(u_.max_hitpoints());
    } else if(key == "experience") {
        return variant(u_.experience());
    } else if(key == "max_experience") {
        return variant(u_.max_experience());
    } else if(key == "level") {
        return variant(u_.level());
    } else if(key == "total_movement") {
        return variant(u_.total_movement());
    } else if(key == "movement_left") {
        return variant(u_.movement_left());
    } else if(key == "attacks_left") {
        return variant(u_.attacks_left());
    } else if(key == "traits") {
        const std::vector<std::string> traits = u_.get_traits_list();
        std::vector<variant> res;

        if(traits.empty())
            return variant( &res );

        for (std::vector<std::string>::const_iterator it = traits.begin(); it != traits.end(); ++it)
        {
            res.push_back( variant(*it) );
        }
        return variant( &res );
    } else if(key == "states") {
        const std::map<std::string, std::string>& states_map = u_.get_states();

        return convert_map( states_map );
    } else if(key == "side") {
        return variant(u_.side()-1);
    } else if(key == "cost") {
        return variant(u_.cost());
    } else if(key == "vars") {
        if(u_.formula_vars()) {
            return variant(u_.formula_vars().get());
        } else {
            return variant();
        }
    } else {
        return variant();
    }
}
Exemplo n.º 4
0
bool StencilAnalysis::isShareableReference(const std::vector<SgExpression*> subscripts, 
					   const bool corner_yz //=FALSE
					   ) 
{
  //March 2 2011, made changes in the function, we have more robust sharing conditions
  //checks if an array reference can be replaced with shared memory reference
  //by looking at the index expressions 
  //assumes the variable is already checked for candidacy

  //check if subsrcipts are _gidx, _gidy or _gidz
  std::vector<SgExpression*>::const_iterator it;
  
  size_t count = 0;
  int indexNo = 0;

  for(it= subscripts.begin(); it != subscripts.end(); it++)
    {      
      indexNo++;
      SgExpression* index = isSgExpression(*it);

      Rose_STL_Container<SgNode*> varList = NodeQuery::querySubTree(index, V_SgVarRefExp);
      
      if(varList.size() != 1) //there should be only 1 variable and that should be gidx,y,z
	return false;
      //check if that varRef is x, y, z

      SgVarRefExp* varExp = isSgVarRefExp(*(varList.begin()));
      ROSE_ASSERT(varExp);

      string index_str = varExp->unparseToString();      
      
      if(indexNo == 1 && index_str != GIDX )
	return false;
      if(indexNo == 2 && index_str != GIDY )
	return false;
      if(indexNo == 3 && index_str != GIDZ )
	return false;

      Rose_STL_Container<SgNode*> constList = NodeQuery::querySubTree(index, V_SgIntVal);

      if(constList.size() > 1 )
	return false;

      if(constList.size() == 1)
	{

	  SgIntVal* constVal = isSgIntVal(*(constList.begin()));
	  ROSE_ASSERT(constVal);

	  if(constVal->get_value() > MAX_ORDER)
	    return false;

	  //we keep maximum 3 planes in shared memory
	  if(constVal->get_value() > 1 && indexNo == 3)
	    return false;

	  Rose_STL_Container<SgNode*> binOpList = NodeQuery::querySubTree(index, V_SgBinaryOp);
      
	  if(binOpList.size() != 1)
	    return false;

	  SgBinaryOp* binOp = isSgBinaryOp(*(binOpList.begin()));

	  //we want either one add or subtract operation in the index expression
	  //no complex indexing is supported for now. 
	  //A[i+2][i-4] is valid but A[i*2] is not valid
	  
	  if( !isSgAddOp(binOp) &&  !isSgSubtractOp(binOp))
	    return false;

	  if(indexNo == 3 && !corner_yz) 
	    { //corner of yz is only shareable when corner_yz is true
	      return false;
	    }

	}
      count++;
    }

  return (count == subscripts.size()) ? true : false ;

}
Exemplo n.º 5
0
bool MDNS::addService(String protocol, String service, uint16_t port, String instance, std::vector<String> subServices) {
  bool success = true;
  String status = "Ok";

  if (!labels[HOSTNAME]) {
    status = "Hostname not set";
    success = false;
  }

  if (success && protocol.length() < MAX_LABEL_SIZE - 1 && service.length() < MAX_LABEL_SIZE - 1 &&
  instance.length() < MAX_LABEL_SIZE && isAlphaDigitHyphen(protocol) && isAlphaDigitHyphen(service) && isNetUnicode(instance)) {

    PTRRecord * ptrRecord = new PTRRecord();
    SRVRecord * srvRecord = new SRVRecord();
    txtRecord = new TXTRecord();
    InstanceNSECRecord * instanceNSECRecord = new InstanceNSECRecord();

    records.push_back(ptrRecord);
    records.push_back(srvRecord);
    records.push_back(txtRecord);
    records.push_back(instanceNSECRecord);

    String serviceString = "_" + service + "._" + protocol;

    Label * protocolLabel = new Label("_" + protocol, LOCAL);

    if (labels[serviceString] == NULL) {
      labels[serviceString] = new ServiceLabel(aRecord, "_" + service, protocolLabel);
    }

    ((ServiceLabel *) labels[serviceString])->addInstance(ptrRecord, srvRecord, txtRecord);

    String instanceString = instance + "._" + service + "._" + protocol;

    labels[instanceString] = new InstanceLabel(srvRecord, txtRecord, instanceNSECRecord, aRecord, instance, labels[serviceString], true);

    for (std::vector<String>::const_iterator i = subServices.begin(); i != subServices.end(); ++i) {
      String subServiceString = "_" + *i + "._sub." + serviceString;

      if (labels[subServiceString] == NULL) {
        labels[subServiceString] = new ServiceLabel(aRecord, "_" + *i, new Label("_sub", labels[serviceString]));
      }

      PTRRecord * subPTRRecord = new PTRRecord();

      subPTRRecord->setLabel(labels[subServiceString]);
      subPTRRecord->setInstanceLabel(labels[instanceString]);

      records.push_back(subPTRRecord);

      ((ServiceLabel *) labels[subServiceString])->addInstance(subPTRRecord, srvRecord, txtRecord);
    }

    ptrRecord->setLabel(labels[serviceString]);
    ptrRecord->setInstanceLabel(labels[instanceString]);
    srvRecord->setLabel(labels[instanceString]);
    srvRecord->setPort(port);
    srvRecord->setHostLabel(labels[HOSTNAME]);
    txtRecord->setLabel(labels[instanceString]);
    instanceNSECRecord->setLabel(labels[instanceString]);
  } else {
    status = success? "Invalid name" : status;
    success = false;
  }

  return success;
}
Exemplo n.º 6
0
/** Test relation writing */
void testRelationWrite() {
    std::string left_name = "_x";
    std::string right_name = "_y";

    std::string field_left_name = "a";
    std::string field_right_name = "b";

    std::string field_left_val = "1";
    std::string field_right_val = "2";

    std::unordered_map<std::string, std::string> left_types, right_types;
    defpair e1Def, e2Def;
    valpair e1Val, e2Val;

    // setup test entity
    e1Def.push_back(std::make_pair(new IntegerColumn(), field_left_name));
    e2Def.push_back(std::make_pair(new IntegerColumn(), field_right_name));
    makeTestEntity(left_name, e1Def);
    makeTestEntity(right_name, e2Def);
    writeEntities();

    e1Val.push_back(std::make_pair(field_left_name, field_left_val));
    e2Val.push_back(std::make_pair(field_right_name, field_right_val));
    left_types.insert(std::make_pair("a", COLTYPE_NAME_INT));
    right_types.insert(std::make_pair("b", COLTYPE_NAME_INT));
    makeTestRelation(left_name, right_name, e1Val, e2Val, left_types,
        right_types);
    writeRelations();

    // Fetch the relation written
    IndexHandler ih;
    Json::Value json;
    std::string key;
    std::vector<std::string> keys;
    for (std::vector<Relation>::iterator it = openRelations.begin();
            it != openRelations.end(); ++it) {
        ih.fetchRaw(it->generateKey(), json);
        keys.push_back(it->generateKey());
        assert(std::strcmp(json[JSON_ATTR_REL_ENTL].asCString(),
            it->name_left.c_str()) == 0);
        assert(std::strcmp(json[JSON_ATTR_REL_ENTR].asCString(),
            it->name_right.c_str()) == 0);
        assert(json[JSON_ATTR_REL_FIELDSL].isMember(field_left_name));
        assert(json[JSON_ATTR_REL_FIELDSR].isMember(field_right_name));
        assert(json[JSON_ATTR_REL_FIELDSL][JSON_ATTR_FIELDS_COUNT].asInt()
            == 1);
        assert(json[JSON_ATTR_REL_FIELDSR][JSON_ATTR_FIELDS_COUNT].asInt()
            == 1);
        assert(std::strcmp(json[JSON_ATTR_REL_FIELDSL][
            std::string(JSON_ATTR_REL_TYPE_PREFIX) + field_left_name].
            asCString(), COLTYPE_NAME_INT) == 0);
        assert(std::strcmp(json[JSON_ATTR_REL_FIELDSR][
            std::string(JSON_ATTR_REL_TYPE_PREFIX) + field_right_name].
            asCString(), COLTYPE_NAME_INT) == 0);
    }

    for (defpair::iterator it = e1Def.begin() ; it != e1Def.end(); ++it)
        delete it->first;
    for (defpair::iterator it = e2Def.begin() ; it != e2Def.end(); ++it)
        delete it->first;

    // Cleanup
    removeEntities();
    removeRelations();
    releaseObjects();

    // Test Removal
    for (std::vector<std::string>::iterator it = keys.begin() ; it != keys.end(); ++it) {
        json = Json::Value();
        assert(!ih.fetchRaw(*it, json));
    }
}
Exemplo n.º 7
0
void htmlWidgetTop7Categories::getTopCategoryStats(
    std::vector<std::pair<wxString, double> > &categoryStats
    , const mmDateRange* date_range) const
{
    //Get base currency rates for all accounts
    std::map<int, double> acc_conv_rates;
    for (const auto& account: Model_Account::instance().all())
    {
        Model_Currency::Data* currency = Model_Account::currency(account);
        acc_conv_rates[account.ACCOUNTID] = currency->BASECONVRATE;
    }
    //Temporary map
    std::map<std::pair<int /*category*/, int /*sub category*/>, double> stat;

    const auto splits = Model_Splittransaction::instance().get_all();
    const auto &transactions = Model_Checking::instance().find(
            Model_Checking::TRANSDATE(date_range->start_date(), GREATER_OR_EQUAL)
            , Model_Checking::TRANSDATE(date_range->end_date(), LESS_OR_EQUAL)
            , Model_Checking::STATUS(Model_Checking::VOID_, NOT_EQUAL)
            , Model_Checking::TRANSCODE(Model_Checking::TRANSFER, NOT_EQUAL));

    for (const auto &trx : transactions)
    {
        bool withdrawal = Model_Checking::type(trx) == Model_Checking::WITHDRAWAL;
        const auto it = splits.find(trx.TRANSID);

        if (it == splits.end())
        {
            std::pair<int, int> category = std::make_pair(trx.CATEGID, trx.SUBCATEGID);
            if (withdrawal)
                stat[category] -= trx.TRANSAMOUNT * (acc_conv_rates[trx.ACCOUNTID]);
            else
                stat[category] += trx.TRANSAMOUNT * (acc_conv_rates[trx.ACCOUNTID]);
        }
        else
        {
            for (const auto& entry : it->second)
            {
                std::pair<int, int> category = std::make_pair(entry.CATEGID, entry.SUBCATEGID);
                double val = entry.SPLITTRANSAMOUNT
                    * (acc_conv_rates[trx.ACCOUNTID])
                    * (withdrawal ? -1 : 1);
                stat[category] += val;
            }
        }
    }

    categoryStats.clear();
    for (const auto& i : stat)
    {
        if (i.second < 0)
        {
            std::pair <wxString, double> stat_pair;
            stat_pair.first = Model_Category::full_name(i.first.first, i.first.second);
            stat_pair.second = i.second;
            categoryStats.push_back(stat_pair);
        }
    }

    std::stable_sort(categoryStats.begin(), categoryStats.end()
        , [] (const std::pair<wxString, double> x, const std::pair<wxString, double> y)
        { return x.second < y.second; }
    );

    int counter = 0;
    std::vector<std::pair<wxString, double> >::iterator iter;
    for (iter = categoryStats.begin(); iter != categoryStats.end(); )
    {
        counter++;
        if (counter > 7)
            iter = categoryStats.erase(iter);
        else
            ++iter;
    }
}
Exemplo n.º 8
0
 ~Allocator() {
   for(typename std::vector<T*>::iterator i = chunks_.begin(); i != chunks_.end(); ++i) {
     T* chunk = *i;
     delete[] chunk;
   }
 }
 void ActivateStoneKeepers()
 {
     for (std::vector<uint64>::const_iterator i = vStoneKeeper.begin(); i != vStoneKeeper.end(); ++i)
     {
         Creature *pTarget = instance->GetCreature(*i);
         if (!pTarget || !pTarget->isAlive() || pTarget->getFaction() == 14)
             continue;
         pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
         pTarget->setFaction(14);
         pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
         return;        // only want the first one we find
     }
     // if we get this far than all four are dead so open the door
     SetData (DATA_ALTAR_DOORS, DONE);
     SetDoor (uiArchaedasTempleDoor, true); //open next the door too
 }
Exemplo n.º 10
0
/// runPasses - Run the specified passes on Program, outputting a bitcode file
/// and writing the filename into OutputFile if successful.  If the
/// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false.  If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined.  This prints to
/// outs() a single line message indicating whether compilation was successful
/// or failed.
///
bool BugDriver::runPasses(Module *Program,
                          const std::vector<std::string> &Passes,
                          std::string &OutputFilename, bool DeleteOutput,
                          bool Quiet, unsigned NumExtraArgs,
                          const char * const *ExtraArgs) const {
  // setup the output file name
  outs().flush();
  SmallString<128> UniqueFilename;
  error_code EC = sys::fs::createUniqueFile(
      OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
  if (EC) {
    errs() << getToolName() << ": Error making unique filename: "
           << EC.message() << "\n";
    return 1;
  }
  OutputFilename = UniqueFilename.str();

  // set up the input file name
  SmallString<128> InputFilename;
  int InputFD;
  EC = sys::fs::createUniqueFile(OutputPrefix + "-input-%%%%%%%.bc", InputFD,
                                 InputFilename);
  if (EC) {
    errs() << getToolName() << ": Error making unique filename: "
           << EC.message() << "\n";
    return 1;
  }

  tool_output_file InFile(InputFilename.c_str(), InputFD);

  WriteBitcodeToFile(Program, InFile.os());
  InFile.os().close();
  if (InFile.os().has_error()) {
    errs() << "Error writing bitcode file: " << InputFilename << "\n";
    InFile.os().clear_error();
    return 1;
  }

  std::string tool = OptCmd.empty()? sys::FindProgramByName("opt") : OptCmd;
  if (tool.empty()) {
    errs() << "Cannot find `opt' in PATH!\n";
    return 1;
  }

  // Ok, everything that could go wrong before running opt is done.
  InFile.keep();

  // setup the child process' arguments
  SmallVector<const char*, 8> Args;
  if (UseValgrind) {
    Args.push_back("valgrind");
    Args.push_back("--error-exitcode=1");
    Args.push_back("-q");
    Args.push_back(tool.c_str());
  } else
    Args.push_back(tool.c_str());

  Args.push_back("-o");
  Args.push_back(OutputFilename.c_str());
  for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
    Args.push_back(OptArgs[i].c_str());
  std::vector<std::string> pass_args;
  for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
    pass_args.push_back( std::string("-load"));
    pass_args.push_back( PluginLoader::getPlugin(i));
  }
  for (std::vector<std::string>::const_iterator I = Passes.begin(),
       E = Passes.end(); I != E; ++I )
    pass_args.push_back( std::string("-") + (*I) );
  for (std::vector<std::string>::const_iterator I = pass_args.begin(),
       E = pass_args.end(); I != E; ++I )
    Args.push_back(I->c_str());
  Args.push_back(InputFilename.c_str());
  for (unsigned i = 0; i < NumExtraArgs; ++i)
    Args.push_back(*ExtraArgs);
  Args.push_back(nullptr);

  DEBUG(errs() << "\nAbout to run:\t";
        for (unsigned i = 0, e = Args.size()-1; i != e; ++i)
          errs() << " " << Args[i];
        errs() << "\n";
        );
void MissionControl::transmitPatches(const std::vector<katana::RoadBase::ConstPtr>& patches, u_int8_t status, u_int8_t number_of_stitches, u_int8_t patches_to_search,
                                     double matching_threshold) {

  if(status == (u_int8_t)PerceptionState::JUNCTION_AHEAD || status == (u_int8_t) PerceptionState::JUNCTION_AHEAD_AGAIN) {
    #ifdef KATANA_MC_PATCH_TRANSMIT_DEBUG
      std::cout << "MC: junction  AHEAD transmitting to lanetracker. Tranmitting patches:" << std::endl;
      for(RoadBase::ConstPtr segment : patches) {
	std::cout << "Type: " << (u_int32_t)segment->getPatchType() << segment->getAnchorPose() << std::endl;
      }
    #endif

    m_transmit_patches_func(patches, status, number_of_stitches, patches_to_search, matching_threshold);
  } else {
    // If junction is detected then insert straight patches for perception
    std::vector<katana::RoadBase::ConstPtr> working_copy;

    for(std::vector<katana::RoadBase::ConstPtr>::const_iterator it = patches.begin(); it != patches.end(); ++it) {

      // Do not insert junctions or parking patches
      if((*it)->getPatchType() >= PatchType::JUNCTION) {
	#ifdef KATANA_MC_PATCH_TRANSMIT_DEBUG
		std::cout << "MC: skipping junction or parking patch to transmit" << std::endl;
	#endif
      } else {
	// Copy patch to working copy
	working_copy.push_back(*it);
      }
    }
    m_transmit_patches_func(working_copy, status, number_of_stitches, patches_to_search , matching_threshold);
    //m_transmit_patches_func(patches, status, 0, 0, -1.0);
  }
}
Exemplo n.º 12
0
        /// @internal
        /// @brief Determine which tests need to be run and run them
        virtual void RunTests()
        {
            if (RunAutomaticTests==RunInteractiveTests && RunInteractiveTests==false)   // enforce running automatic tests if no type of test is specified
                { RunAutomaticTests=true;  }

            if (RunAll)
            {
                for(map<String,UnitTestGroup*>::iterator Iter=TestGroups.begin(); Iter!=TestGroups.end(); ++Iter)
                    { TestGroupsToRun.push_back(Iter->first); }
            }

            if(ExecuteInThisMemorySpace) // Should we be executing the test right now?
            {
                for(std::vector<Mezzanine::String>::iterator CurrentTestName=TestGroupsToRun.begin(); CurrentTestName!=TestGroupsToRun.end(); ++CurrentTestName ) // Actually run the tests
                {
                    try{
                        TestGroups[*CurrentTestName]->RunTests(RunAutomaticTests, RunInteractiveTests);
                    } catch (std::exception e) {
                        TestError << std::endl << e.what() << std::endl;
                        // maybe we should log or somehting.
                    }

                    (*this) += *(TestGroups[*CurrentTestName]);
                }
            }else{ // No, We should be executing the test in a place that cannot possibly crash this program
                for(std::vector<Mezzanine::String>::iterator CurrentTestName=TestGroupsToRun.begin(); CurrentTestName!=TestGroupsToRun.end(); ++CurrentTestName )
                {
                    ClearTempFile();
                    if(system(String(CommandName + " " + *CurrentTestName + " " + MemSpaceArg + " " + Mezzanine::String(RunAutomaticTests?"automatic ":"") + Mezzanine::String(RunInteractiveTests?"interactive ":"")).c_str()))   // Run a single unit test as another process
                    {
                        this->AddTestResult(String("Process::" + *CurrentTestName), Testing::Failed);
                    }else {
                        this->AddTestResult(String("Process::" + *CurrentTestName), Success);
                    }

                    try
                    {
                        (*this) += GetResultsFromTempFile();
                    } catch (std::exception& e) {
                        TestError << e.what() << endl;
                    }

                }
                DeleteTempFile();
            } // \if(ExecuteInThisMemorySpace)
        } // \function
/**
 * Function TestForExistingItem
 * test if aItem exists somewhere in lists of items
 * This is a function used by PutDataInPreviousState to be sure an item was not deleted
 * since an undo or redo.
 * This could be possible:
 *   - if a call to SaveCopyInUndoList was forgotten in Pcbnew
 *   - in zones outlines, when a change in one zone merges this zone with an other
 * This function avoids a Pcbnew crash
 * Before using this function to test existence of items,
 * it must be called with aItem = NULL to prepare the list
 * @param aPcb = board to test
 * @param aItem = item to find
 *              = NULL to build the list of existing items
 */
static bool TestForExistingItem( BOARD* aPcb, BOARD_ITEM* aItem )
{
    static std::vector<BOARD_ITEM*> itemsList;

    if( aItem == NULL ) // Build list
    {
        // Count items to store in itemsList:
        int icnt = 0;
        BOARD_ITEM* item;

        // Count tracks:
        for( item = aPcb->m_Track; item != NULL; item = item->Next() )
            icnt++;

        // Count modules:
        for( item = aPcb->m_Modules; item != NULL; item = item->Next() )
            icnt++;

        // Count drawings
        for( item = aPcb->m_Drawings; item != NULL; item = item->Next() )
            icnt++;

        // Count zones outlines
        icnt +=  aPcb->GetAreaCount();

        // Count zones segm (now obsolete):
        for( item = aPcb->m_Zone; item != NULL; item = item->Next() )
             icnt++;

        // Build candidate list:
        itemsList.clear();
        itemsList.reserve(icnt);

        // Store items in list:
        // Append tracks:
        for( item = aPcb->m_Track; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append modules:
        for( item = aPcb->m_Modules; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append drawings
        for( item = aPcb->m_Drawings; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append zones outlines
        for( int ii = 0; ii < aPcb->GetAreaCount(); ii++ )
            itemsList.push_back( aPcb->GetArea( ii ) );

        // Append zones segm:
        for( item = aPcb->m_Zone; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Sort list
        std::sort( itemsList.begin(), itemsList.end() );
        return false;
    }

    // search in list:
    return std::binary_search( itemsList.begin(), itemsList.end(), aItem );
}
Exemplo n.º 14
0
std::unique_ptr<Process>
createSmallDeformationProcess(
    MeshLib::Mesh& mesh,
    std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler,
    std::vector<ProcessVariable> const& variables,
    std::vector<std::unique_ptr<ParameterBase>> const& parameters,
    unsigned const integration_order,
    BaseLib::ConfigTree const& config)
{
    //! \ogs_file_param{process__type}
    config.checkConfigParameter("type", "SMALL_DEFORMATION_WITH_LIE");
    DBUG("Create SmallDeformationProcess with LIE.");

    // Process variables
    auto const pv_conf = config.getConfigSubtree("process_variables");
    auto range = pv_conf.getConfigParameterList<std::string>("process_variable");
    std::vector<std::reference_wrapper<ProcessVariable>> process_variables;
    for (std::string const& pv_name : range)
    {
        if (pv_name != "displacement"
            && pv_name.find("displacement_jump")==std::string::npos)
            OGS_FATAL("Found a process variable name '%s'. It should be 'displacement' or 'displacement_jumpN'");
        auto variable = std::find_if(
            variables.cbegin(), variables.cend(),
            [&pv_name](ProcessVariable const& v) { return v.getName() == pv_name; });

        if (variable == variables.end())
        {
            OGS_FATAL(
                "Could not find process variable '%s' in the provided variables "
                "list for config tag <%s>.",
                pv_name.c_str(), "process_variable");
        }
        DBUG("Found process variable \'%s\' for config tag <%s>.",
             variable->getName().c_str(), "process_variable");

        process_variables.emplace_back(const_cast<ProcessVariable&>(*variable));
    }
    if (process_variables.size() > 2)
        OGS_FATAL("Currently only one displacement jump is supported");

    DBUG("Associate displacement with process variable \'%s\'.",
         process_variables.back().get().getName().c_str());

    if (process_variables.back().get().getNumberOfComponents() !=
        DisplacementDim)
    {
        OGS_FATAL(
            "Number of components of the process variable '%s' is different "
            "from the displacement dimension: got %d, expected %d",
            process_variables.back().get().getName().c_str(),
            process_variables.back().get().getNumberOfComponents(),
            DisplacementDim);
    }

    // Constitutive relation.
    // read type;
    auto const constitutive_relation_config =
        //! \ogs_file_param{process__SMALL_DEFORMATION_WITH_LIE__constitutive_relation}
        config.getConfigSubtree("constitutive_relation");

    auto const type =
        constitutive_relation_config.peekConfigParameter<std::string>("type");

    std::unique_ptr<MaterialLib::Solids::MechanicsBase<DisplacementDim>> material = nullptr;
    if (type == "LinearElasticIsotropic")
    {
        material = MaterialLib::Solids::createLinearElasticIsotropic<DisplacementDim>(
            parameters, constitutive_relation_config);
    }
    else
    {
        OGS_FATAL(
            "Cannot construct constitutive relation of given type \'%s\'.",
            type.c_str());
    }

    // Fracture constitutive relation.
    // read type;
    auto const fracture_constitutive_relation_config =
        //! \ogs_file_param{process__SMALL_DEFORMATION_WITH_LIE__constitutive_relation}
        config.getConfigSubtree("fracture_constitutive_relation");

    auto const frac_type =
        fracture_constitutive_relation_config.peekConfigParameter<std::string>("type");

    std::unique_ptr<MaterialLib::Fracture::FractureModelBase<DisplacementDim>> fracture_model = nullptr;
    if (frac_type == "LinearElasticIsotropic")
    {
        fracture_model = MaterialLib::Fracture::createLinearElasticIsotropic<DisplacementDim>(
            parameters, fracture_constitutive_relation_config);
    }
    else if (frac_type == "MohrCoulomb")
    {
        fracture_model = MaterialLib::Fracture::createMohrCoulomb<DisplacementDim>(
            parameters, fracture_constitutive_relation_config);
    }
    else
    {
        OGS_FATAL(
            "Cannot construct fracture constitutive relation of given type \'%s\'.",
            frac_type.c_str());
    }

    // Fracture properties
    //! \ogs_file_param{process__SMALL_DEFORMATION_WITH_LIE__fracture_properties}
    auto fracture_properties_config = config.getConfigSubtree("fracture_properties");
    auto &para_b0 = ProcessLib::findParameter<double>(fracture_properties_config, "initial_aperture", parameters, 1);
    std::unique_ptr<FractureProperty> frac_prop(new FractureProperty());
    frac_prop->mat_id = fracture_properties_config.getConfigParameter<int>("material_id");
    frac_prop->aperture0 = &para_b0;


    SmallDeformationProcessData<DisplacementDim> process_data(
        std::move(material), std::move(fracture_model), std::move(frac_prop));

    SecondaryVariableCollection secondary_variables;

    NumLib::NamedFunctionCaller named_function_caller(
        {"SmallDeformation_displacement"});

    ProcessLib::parseSecondaryVariables(config, secondary_variables,
                                        named_function_caller);

    return std::unique_ptr<SmallDeformationProcess<DisplacementDim>>{
        new SmallDeformationProcess<DisplacementDim>{
            mesh, std::move(jacobian_assembler), parameters, integration_order,
            std::move(process_variables), std::move(process_data),
            std::move(secondary_variables), std::move(named_function_caller)}};
}
Exemplo n.º 15
0
void removeEntities() {
    RedisHandler rds(REDISDBTEST, REDISPORT);
    for (std::vector<Entity>::iterator it = openEntities.begin();
            it != openEntities.end(); ++it)
        it->remove(rds);
}
            // used when Archaedas dies.  All active minions must be despawned.
            void DeActivateMinions()
            {
                // first despawn any aggroed wall minions
                for (std::vector<uint64>::const_iterator i = vArchaedasWallMinions.begin(); i != vArchaedasWallMinions.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14)
                        continue;
                    pTarget->setDeathState(JUST_DIED);
                    pTarget->RemoveCorpse();
                }

                // Vault Walkers
                for (std::vector<uint64>::const_iterator i = vVaultWalker.begin(); i != vVaultWalker.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14)
                        continue;
                    pTarget->setDeathState(JUST_DIED);
                    pTarget->RemoveCorpse();
                }

                // Earthen Guardians
                for (std::vector<uint64>::const_iterator i = vEarthenGuardian.begin(); i != vEarthenGuardian.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14)
                        continue;
                    pTarget->setDeathState(JUST_DIED);
                    pTarget->RemoveCorpse();
                }
            }
Exemplo n.º 17
0
void removeRelations() {
    RedisHandler rds(REDISDBTEST, REDISPORT);
    for (std::vector<Relation>::iterator it = openRelations.begin();
            it != openRelations.end(); ++it)
        it->remove(rds);
}
            void RespawnMinions()
            {
                // first respawn any aggroed wall minions
                for (std::vector<uint64>::const_iterator i = vArchaedasWallMinions.begin(); i != vArchaedasWallMinions.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (pTarget && pTarget->isDead())
                    {
                        pTarget->Respawn();
                        pTarget->GetMotionMaster()->MoveTargetedHome();
                        SetFrozenState(pTarget);
                    }
                }

                // Vault Walkers
                for (std::vector<uint64>::const_iterator i = vVaultWalker.begin(); i != vVaultWalker.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (pTarget && pTarget->isDead())
                    {
                        pTarget->Respawn();
                        pTarget->GetMotionMaster()->MoveTargetedHome();
                        SetFrozenState(pTarget);
                    }
                }

                // Earthen Guardians
                for (std::vector<uint64>::const_iterator i = vEarthenGuardian.begin(); i != vEarthenGuardian.end(); ++i)
                {
                    Creature *pTarget = instance->GetCreature(*i);
                    if (pTarget && pTarget->isDead())
                    {
                        pTarget->Respawn();
                        pTarget->GetMotionMaster()->MoveTargetedHome();
                        SetFrozenState(pTarget);
                    }
                }
            }
Exemplo n.º 19
0
Arquivo: main.cpp Projeto: CCJY/coliru
 explicit test_id(std::vector<int> const& v_id) : first(v_id.begin()), last(v_id.end()){}
Exemplo n.º 20
0
void Demux::populate_pvr_streams()
{
  CLockObject Lock(m_mutex);

  uint16_t mainPid = 0xffff;
  int mainType = XBMC_CODEC_TYPE_UNKNOWN;
  std::vector<XbmcPvrStream> new_streams;
  const std::vector<ElementaryStream*> es_streams = m_AVContext->GetStreams();
  for (std::vector<ElementaryStream*>::const_iterator it = es_streams.begin(); it != es_streams.end(); it++)
  {
    const char* codec_name = (*it)->GetStreamCodecName();
    xbmc_codec_t codec = CODEC->GetCodecByName(codec_name);
    if (codec.codec_type != XBMC_CODEC_TYPE_UNKNOWN)
    {
      // Find the main stream:
      // The best candidate would be the first video. Else the first audio
      switch (mainType)
      {
      case XBMC_CODEC_TYPE_VIDEO:
        break;
      case XBMC_CODEC_TYPE_AUDIO:
        if (codec.codec_type != XBMC_CODEC_TYPE_VIDEO)
          break;
      default:
        mainPid = (*it)->pid;
        mainType = codec.codec_type;
      }

      XbmcPvrStream new_stream;
      m_streams.GetStreamData((*it)->pid, &new_stream);

      new_stream.iCodecId       = codec.codec_id;
      new_stream.iCodecType     = codec.codec_type;
      recode_language((*it)->stream_info.language, new_stream.strLanguage);
      new_stream.iIdentifier    = stream_identifier((*it)->stream_info.composition_id, (*it)->stream_info.ancillary_id);
      new_stream.iFPSScale      = (*it)->stream_info.fps_scale;
      new_stream.iFPSRate       = (*it)->stream_info.fps_rate;
      new_stream.iHeight        = (*it)->stream_info.height;
      new_stream.iWidth         = (*it)->stream_info.width;
      new_stream.fAspect        = (*it)->stream_info.aspect;
      new_stream.iChannels      = (*it)->stream_info.channels;
      new_stream.iSampleRate    = (*it)->stream_info.sample_rate;
      new_stream.iBlockAlign    = (*it)->stream_info.block_align;
      new_stream.iBitRate       = (*it)->stream_info.bit_rate;
      new_stream.iBitsPerSample = (*it)->stream_info.bits_Per_sample;

      new_streams.push_back(new_stream);
      m_AVContext->StartStreaming((*it)->pid);

      // Add stream to no setup set
      if (!(*it)->has_stream_info)
        m_nosetup.insert((*it)->pid);

      if (g_bExtraDebug)
        XBMC->Log(LOG_DEBUG, LOGTAG"%s: register PES %.4x %s", __FUNCTION__, (*it)->pid, codec_name);
    }
  }
  m_streams.UpdateStreams(new_streams);
  // Renew main stream
  m_mainStreamPID = mainPid;
}
Exemplo n.º 21
0
int StencilAnalysis::getSharingCategory(const std::vector<SgExpression*> subscripts) 
{
  //return 2 if it is up or down
  //return 1 if it is off-center
  //return 0 if it is center
  //return -1 if it is neither

  //check if subsrcipts are _gidx, _gidy or _gidz
  std::vector<SgExpression*>::const_iterator it;
  
  size_t count = 0;
  int indexNo = 0;
  size_t category = 0;

  for(it= subscripts.begin(); it != subscripts.end(); it++)
    {      
      indexNo++;
      SgExpression* index = isSgExpression(*it);

      Rose_STL_Container<SgNode*> varList = NodeQuery::querySubTree(index, V_SgVarRefExp);
      
      if(varList.size() != 1) //there should be only 1 variable and that should be gidx,y,z
	return -1;
      //check if that varRef is x, y, z

      SgVarRefExp* varExp = isSgVarRefExp(*(varList.begin()));
      ROSE_ASSERT(varExp);

      string index_str = varExp->unparseToString();      
      
      if(indexNo == 1 && index_str != GIDX )
	return -1;
      else if(indexNo == 2 && index_str != GIDY )
	return -1;
      else if(indexNo == 3 && index_str != GIDZ )
	return -1;

      Rose_STL_Container<SgNode*> constList = NodeQuery::querySubTree(index, V_SgIntVal);

      if(constList.size() > 1 )
	return -1;

      if(constList.size() == 1)
	{
	  category = 1;

	  SgIntVal* constVal = isSgIntVal(*(constList.begin()));
	  ROSE_ASSERT(constVal);

	  if(constVal->get_value() > MAX_ORDER)
	    return -1;

	  //we keep maximum 3 planes in shared memory
	  if(constVal->get_value() > 1 && indexNo == 3)
	    return -1;

	  Rose_STL_Container<SgNode*> binOpList = NodeQuery::querySubTree(index, V_SgBinaryOp);
      
	  if(binOpList.size() != 1)
	    return -1;

	  SgBinaryOp* binOp = isSgBinaryOp(*(binOpList.begin()));

	  //we want either one add or subtract operation in the index expression
	  //no complex indexing is supported for now. 
	  //A[i+2][i-4] is valid but A[i*2] is not valid
	  
	  if( !isSgAddOp(binOp) &&  !isSgSubtractOp(binOp))
	    return -1;

	  if(indexNo == 3) 
	    { 
	      category = 2;
	    }
	}
      count++;
    }

  return (count == subscripts.size()) ? category : -1 ;

}
Exemplo n.º 22
0
void Scene::printObjects()
{
	for (auto iter = mObjects.begin(); iter != mObjects.end(); ++iter)
		std::cout << (*iter) << std::endl;
}
Exemplo n.º 23
0
PLUGIN_EXPORT void Reload(void* data, void* rm, double* maxValue)
{
	Measure* measure = (Measure*)data;

	// Data is stored in two structs: Measure and ParentMeasure. ParentMeasure is created for measures
	// with PlayerName=someplayer. Measure is created for all measures and points to ParentMeasure as
	// referenced in PlayerName=[section].

	// Read settings from the ini-file
	void* skin = RmGetSkin(rm);
	LPCWSTR str = RmReadString(rm, L"PlayerName", L"", FALSE);
	if (str[0] == L'[')
	{
		if (measure->parent)
		{
			// Don't let a measure measure change its parent
		}
		else
		{
			// PlayerName starts with [ so use referenced section
			++str;
			int len = static_cast<int>(wcslen(str));
			if (len > 0 && str[len - 1] == L']')
			{
				--len;

				std::vector<ParentMeasure*>::iterator iter = g_ParentMeasures.begin();
				for ( ; iter != g_ParentMeasures.end(); ++iter)
				{
					if (skin == (*iter)->skin &&
						wcsncmp(str, (*iter)->ownerName, len) == 0)
					{
						// Use same ParentMeasure as referenced section
						measure->parent = (*iter);
						++measure->parent->measureCount;

						break;
					}
				}

				if (!measure->parent)
				{
					// The referenced section doesn't exist
					std::wstring error = L"NowPlaying.dll: Invalid PlayerName=";
					error.append(str - 1, len + 2);
					error += L" in [";
					error += RmGetMeasureName(rm);
					error += L"]";
					RmLog(LOG_WARNING, error.c_str());
					return;
				}
			}
		}
	}
	else
	{
		// ParentMeasure is created when PlayerName is an actual player (and not a reference)
		ParentMeasure* parent = measure->parent;
		Player* oldPlayer = nullptr;
		if (parent)
		{
			if (parent->data != data)
			{
				// Don't let a measure-only measure become a parent measure
				return;
			}

			oldPlayer = parent->player;
		}
		else
		{
			parent = new ParentMeasure;
			g_ParentMeasures.push_back(parent);
			parent->data = data;
			parent->skin = skin;
			parent->ownerName = RmGetMeasureName(rm);
			measure->parent = parent;
		}

		if (_wcsicmp(L"AIMP", str) == 0)
		{
			parent->player = PlayerAIMP::Create();
		}
		else if (_wcsicmp(L"CAD", str) == 0)
		{
			parent->player = PlayerCAD::Create();
		}
		else if (_wcsicmp(L"foobar2000", str) == 0)
		{
			HWND fooWindow = FindWindow(L"foo_rainmeter_class", nullptr);
			if (fooWindow)
			{
				const WCHAR* error = L"Your foobar2000 plugin is out of date.\n\nDo you want to update the plugin now?";
				if (MessageBox(nullptr, error, L"Rainmeter", MB_YESNO | MB_ICONINFORMATION | MB_TOPMOST) == IDYES)
				{
					ShellExecute(nullptr, L"open", L"http://github.com/poiru/foo-cad#readme", nullptr, nullptr, SW_SHOWNORMAL);
				}
			}

			parent->player = PlayerCAD::Create();
		}
		else if (_wcsicmp(L"iTunes", str) == 0)
		{
			parent->player = PlayerITunes::Create();
		}
		else if (_wcsicmp(L"MediaMonkey", str) == 0)
		{
			parent->player = PlayerWinamp::Create(WA_MEDIAMONKEY);
		}
		else if (_wcsicmp(L"Spotify", str) == 0)
		{
			parent->player = PlayerSpotify::Create();
		}
		else if (_wcsicmp(L"WinAmp", str) == 0)
		{
			parent->player = PlayerWinamp::Create(WA_WINAMP);
		}
		else if (_wcsicmp(L"WMP", str) == 0)
		{
			parent->player = PlayerWMP::Create();
		}
		else
		{
			// Default to WLM
			parent->player = PlayerWLM::Create();

			if (_wcsicmp(L"WLM", str) != 0)
			{
				std::wstring error = L"NowPlaying.dll: Invalid PlayerName=";
				error += str;
				error += L" in [";
				error += parent->ownerName;
				error += L"]";
				RmLog(LOG_ERROR, error.c_str());
			}
		}

		parent->player->AddInstance();
		parent->playerPath = RmReadString(rm, L"PlayerPath", L"");
		parent->trackChangeAction = RmReadString(rm, L"TrackChangeAction", L"", FALSE);
		parent->disableLeadingZero = RmReadInt(rm, L"DisableLeadingZero", 0);

		if (oldPlayer)
		{
			parent->player->SetMeasures(oldPlayer->GetMeasures());

			// Remove instance here so that player doesn't have to reinitialize if PlayerName was
			// not changed.
			oldPlayer->RemoveInstance();
		}
	}

	str = RmReadString(rm, L"PlayerType", L"");
	if (_wcsicmp(L"ARTIST", str) == 0)
	{
		measure->type = MEASURE_ARTIST;
	}
	else if (_wcsicmp(L"TITLE", str) == 0)
	{
		measure->type = MEASURE_TITLE;
	}
	else if (_wcsicmp(L"ALBUM", str) == 0)
	{
		measure->type = MEASURE_ALBUM;
	}
	else if (_wcsicmp(L"COVER", str) == 0)
	{
		measure->type = MEASURE_COVER;
	}
	else if (_wcsicmp(L"DURATION", str) == 0)
	{
		measure->type = MEASURE_DURATION;
	}
	else if (_wcsicmp(L"POSITION", str) == 0)
	{
		measure->type = MEASURE_POSITION;
	}
	else if (_wcsicmp(L"PROGRESS", str) == 0)
	{
		measure->type = MEASURE_PROGRESS;
		*maxValue = 100.0;
	}
	else if (_wcsicmp(L"RATING", str) == 0)
	{
		measure->type = MEASURE_RATING;
		*maxValue = 5.0;
	}
	else if (_wcsicmp(L"STATE", str) == 0)
	{
		measure->type = MEASURE_STATE;
	}
	else if (_wcsicmp(L"STATUS", str) == 0)
	{
		measure->type = MEASURE_STATUS;
	}
	else if (_wcsicmp(L"VOLUME", str) == 0)
	{
		measure->type = MEASURE_VOLUME;
		*maxValue = 100.0;
	}
	else if (_wcsicmp(L"SHUFFLE", str) == 0)
	{
		measure->type = MEASURE_SHUFFLE;
	}
	else if (_wcsicmp(L"REPEAT", str) == 0)
	{
		measure->type = MEASURE_REPEAT;
	}
	else if (_wcsicmp(L"LYRICS", str) == 0)
	{
		RmLog(LOG_WARNING, L"NowPlaying.dll: Using undocumented PlayerType=LYRICS!");
		measure->type = MEASURE_LYRICS;
	}
	else if (_wcsicmp(L"FILE", str) == 0)
	{
		measure->type = MEASURE_FILE;
	}
	else if (_wcsicmp(L"NUMBER", str) == 0)
	{
		measure->type = MEASURE_NUMBER;
	}
	else if (_wcsicmp(L"YEAR", str) == 0)
	{
		measure->type = MEASURE_YEAR;
	}
	else
	{
		std::wstring error = L"NowPlaying.dll: Invalid PlayerType=";
		error += str;
		error += L" in [";
		error += RmGetMeasureName(rm);
		error += L"]";
		RmLog(LOG_WARNING, error.c_str());
	}

	measure->parent->player->AddMeasure(measure->type);
}
Exemplo n.º 24
0
    void ActivateWallMinions()
    {
        Creature* archaedas = instance->GetCreature(archaedasGUID);
        if (!archaedas)
            return;

        for (std::vector<uint64>::const_iterator i = archaedasWallMinions.begin(); i != archaedasWallMinions.end(); ++i)
        {
            Creature* pTarget = instance->GetCreature(*i);
            if (!pTarget || !pTarget->isAlive() || pTarget->getFaction() == 14)
                continue;
            archaedas->CastSpell(pTarget, SPELL_AWAKEN_VAULT_WALKER, true);
            pTarget->CastSpell(pTarget, SPELL_ARCHAEDAS_AWAKEN,true);
            return;        // only want the first one we find
        }
    }
Exemplo n.º 25
0
		void remove_sink( sink* s )
		{
			auto it = std::find( global_sinks.begin(), global_sinks.end(), s );
			if ( it != global_sinks.end() ) global_sinks.erase( it );
			get_global_log_level();
		}
Exemplo n.º 26
0
void printOpenRelations() {
    for (std::vector<Relation>::iterator it = openRelations.begin();
            it != openRelations.end(); ++it)
        cout << it->stringify() << endl;
}
Exemplo n.º 27
0
game_info::game_info(const config& game, const config& game_config, const std::vector<std::string>& installed_addons)
	: mini_map()
	, id(game["id"])
	, map_data(game["map_data"])
	, name(game["name"])
	, scenario()
	, remote_scenario(false)
	, map_info()
	, map_size_info()
	, era()
	, era_short()
	, gold(game["mp_village_gold"])
	, support(game["mp_village_support"])
	, xp(game["experience_modifier"].str() + "%")
	, vision()
	, status()
	, time_limit()
	, vacant_slots(lexical_cast_default<int>(game["slots"], 0)) // Can't use to_int() here.
	, current_turn(0)
	, reloaded(game["savegame"].to_bool())
	, started(false)
	, fog(game["mp_fog"].to_bool())
	, shroud(game["mp_shroud"].to_bool())
	, observers(game["observer"].to_bool(true))
	, shuffle_sides(game["shuffle_sides"].to_bool(true))
	, use_map_settings(game["mp_use_map_settings"].to_bool())
	, registered_users_only(game["registered_users_only"].to_bool())
	, verified(true)
	, password_required(game["password"].to_bool())
	, have_era(true)
	, have_all_mods(true)
	, has_friends(false)
	, has_ignored(false)
	, display_status(NEW)
	, required_addons()
	, addons_outcome(SATISFIED)
{
	const auto parse_requirements = [&](const config& c, const std::string& id_key) {
		if(c.has_attribute(id_key)) {
			if(std::find(installed_addons.begin(), installed_addons.end(), c[id_key].str()) == installed_addons.end()) {
				required_addon r;
				r.addon_id = c[id_key].str();
				r.outcome = NEED_DOWNLOAD;

				r.message = vgettext("Missing addon: $id", {{"id", c[id_key].str()}});
				required_addons.push_back(r);
				if(addons_outcome == SATISFIED) {
					addons_outcome = NEED_DOWNLOAD;
				}
			}
		}
	};

	for(const config& addon : game.child_range("addon")) {
		parse_requirements(addon, "id");
	}

	/*
	 * Modifications have a different format than addons. The id and addon_id are keys sent by the
	 * server, so we have to parse them separately here and add them to the required_addons vector.
	 */
	for(const config& mod : game.child_range("modification")) {
		parse_requirements(mod, "addon_id");
	}

	std::string turn = game["turn"];
	if(!game["mp_era"].empty()) {
		const config& era_cfg = game_config.find_child("era", "id", game["mp_era"]);
		if(era_cfg) {
			era = era_cfg["name"].str();
			era_short = era_cfg["short_name"].str();
			if(era_short.empty()) {
				era_short = make_short_name(era);
			}

			ADDON_REQ result = check_addon_version_compatibility(era_cfg, game);
			addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
		} else {
			have_era = !game["require_era"].to_bool(true);
			era = vgettext("Unknown era: $era_id", {{"era_id", game["mp_era_addon_id"].str()}});
			era_short = make_short_name(era);
			verified = false;

			addons_outcome = NEED_DOWNLOAD;
		}
	} else {
		era = _("Unknown era");
		era_short = "??";
		verified = false;
	}

	std::stringstream info_stream;
	info_stream << era;

	if(!game.child_or_empty("modification").empty()) {
		for(const config& cfg : game.child_range("modification")) {
			if(const config& mod = game_config.find_child("modification", "id", cfg["id"])) {
				mod_info += (mod_info.empty() ? "" : ", ") + mod["name"].str();

				if(cfg["require_modification"].to_bool(false)) {
					ADDON_REQ result = check_addon_version_compatibility(mod, game);
					addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
				}
			} else {
				mod_info += (mod_info.empty() ? "" : ", ") + cfg["addon_id"].str();

				if(cfg["require_modification"].to_bool(false)) {
					have_all_mods = false;
					mod_info += " " + _("(missing)");

					addons_outcome = NEED_DOWNLOAD;
				}
			}
		}
	}

	if(map_data.empty()) {
		map_data = filesystem::read_map(game["mp_scenario"]);
	}

	if(map_data.empty()) {
		info_stream << " — ??×??";
	} else {
		try {
			gamemap map(std::make_shared<terrain_type_data>(game_config), map_data);
			// mini_map = image::getMinimap(minimap_size_, minimap_size_, map,
			// 0);
			std::ostringstream msi;
			msi << map.w() << font::unicode_multiplication_sign << map.h();
			map_size_info = msi.str();
			info_stream << " — " + map_size_info;
		} catch(incorrect_map_format_error& e) {
			ERR_CF << "illegal map: " << e.message << std::endl;
			verified = false;
		} catch(wml_exception& e) {
			ERR_CF << "map could not be loaded: " << e.dev_message << '\n';
			verified = false;
		}
	}
	info_stream << " ";

	//
	// Check scenarios and campaigns
	//
	if(!game["mp_scenario"].empty() && game["mp_campaign"].empty()) {
		// Check if it's a multiplayer scenario
		const config* level_cfg = &game_config.find_child("multiplayer", "id", game["mp_scenario"]);

		// Check if it's a user map
		if(!*level_cfg) {
			level_cfg = &game_config.find_child("generic_multiplayer", "id", game["mp_scenario"]);
		}

		if(*level_cfg) {
			scenario = formatter() << "<b>" << _("(S)") << "</b>" << " " << (*level_cfg)["name"].str();
			info_stream << scenario;

			// Reloaded games do not match the original scenario hash, so it makes no sense
			// to test them, since they always would appear as remote scenarios
			if(!reloaded) {
				if(const config& hashes = game_config.child("multiplayer_hashes")) {
					std::string hash = game["hash"];
					bool hash_found = false;
					for(const auto & i : hashes.attribute_range()) {
						if(i.first == game["mp_scenario"] && i.second == hash) {
							hash_found = true;
							break;
						}
					}

					if(!hash_found) {
						remote_scenario = true;
						info_stream << " — ";
						info_stream << _("Remote scenario");
						verified = false;
					}
				}
			}

			if((*level_cfg)["require_scenario"].to_bool(false)) {
				ADDON_REQ result = check_addon_version_compatibility((*level_cfg), game);
				addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
			}
		} else {
			scenario = vgettext("Unknown scenario: $scenario_id", {{"scenario_id", game["mp_scenario_name"].str()}});
			info_stream << scenario;
			verified = false;
		}
	} else if(!game["mp_campaign"].empty()) {
		if(const config& level_cfg = game_config.find_child("campaign", "id", game["mp_campaign"])) {
			std::stringstream campaign_text;
			campaign_text
				<< "<b>" << _("(C)") << "</b>" << " "
				<< level_cfg["name"] << " — "
				<< game["mp_scenario_name"];

			// Difficulty
			config difficulties = gui2::dialogs::generate_difficulty_config(level_cfg);
			for(const config& difficulty : difficulties.child_range("difficulty")) {
				if(difficulty["define"] == game["difficulty_define"]) {
					campaign_text << " — " << difficulty["description"];

					break;
				}
			}

			scenario = campaign_text.str();
			info_stream << campaign_text.rdbuf();

			// TODO: should we have this?
			//if(game["require_scenario"].to_bool(false)) {
				ADDON_REQ result = check_addon_version_compatibility(level_cfg, game);
				addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
			//}
		} else {
			scenario = vgettext("Unknown campaign: $campaign_id", {{"campaign_id", game["mp_campaign"].str()}});
			info_stream << scenario;
			verified = false;
		}
	} else {
		scenario = _("Unknown scenario");
		info_stream << scenario;
		verified = false;
	}

	// Remove any newlines that might have been in game titles
	boost::replace_all(scenario, "\n", " " + font::unicode_em_dash + " ");

	if(reloaded) {
		info_stream << " — ";
		info_stream << _("Reloaded game");
		verified = false;
	}

	if(!turn.empty()) {
		started = true;
		int index = turn.find_first_of('/');
		if(index > -1) {
			const std::string current_turn_string = turn.substr(0, index);
			current_turn = lexical_cast<unsigned int>(current_turn_string);
		}
		status = _("Turn") + " " + turn;
	} else {
		started = false;
		if(vacant_slots > 0) {
			status = _n("Vacant Slot:", "Vacant Slots:", vacant_slots) + " " + game["slots"];
		}
	}

	if(fog) {
		vision = _("Fog");
		if(shroud) {
			vision += "/";
			vision += _("Shroud");
		}
	} else if(shroud) {
		vision = _("Shroud");
	} else {
		vision = _("none");
	}

	if(game["mp_countdown"].to_bool()) {
		time_limit = formatter()
			<< game["mp_countdown_init_time"].str() << "+"
			<< game["mp_countdown_turn_bonus"].str() << "/"
			<< game["mp_countdown_action_bonus"].str();
	}

	map_info = info_stream.str();
}
Exemplo n.º 28
0
void printOpenEntities() {
    for (std::vector<Entity>::iterator it = openEntities.begin();
            it != openEntities.end(); ++it)
        cout << it->stringify() << endl;
}
Exemplo n.º 29
0
size_t
stumpd::insert::insert_data(std::vector <std::vector <std::string> > data)
{

  fprintf(stdout, "insert_data size %ld\n", data.size());
  FILE *fp;
  size_t document_count;
  document_count = 0;

  bool start;
  start = 1;

  char *ymd;
  ymd = (char*)calloc(sizeof(char), 10);

  char *ymd_old;
  ymd_old = (char*)calloc(sizeof(char), 10);

  struct tm *date_buf;
  date_buf = (struct tm*)calloc(sizeof(struct tm), 1);

  if(strcmp(DB_TYPE, "mysql") == 0)
  {

  std::string insert_query("START TRANSACTION;");
  std::vector <std::vector < std::string > > results;

    if(data.size() > 0)
      std::sort(data.begin(), data.end(), sort_dates);

    size_t i;
    time_t str_to_date;

    for(i=0;i<data.size();i++)
    {

      str_to_date = strtol(data[i][0].c_str(), NULL, 0);

      localtime_r(&str_to_date, date_buf);
      strftime(ymd, 10, "%Y%m%d", date_buf);

      if(strcmp(ymd, ymd_old) != 0)
      {
        if(strlen(ymd_old) != 0)
        {
          //fprintf(stdout, "ymd_old length is %ld\n", strlen(ymd_old));
          insert_query.erase(insert_query.length() - 1);
          insert_query.append(";");
        } else {
          if(i<data.size()-1&&start == 0)
            insert_query.append(",");
        }
        fprintf(stdout, "Starting new insert query, capping off the last one\n");
        start = 1;
      }
      

      if(start == 1)
      {

        strncpy(ymd_old, ymd, 10);
        //insert_query.clear();
        insert_query
          .append("INSERT INTO `documents_")
          .append(
            std::string(ymd)
              .substr(0, 4))
          .append("`.`")
          .append(ymd)
          .append("` (date, host, input, content) VALUES ");
          start = !start;
      }

        insert_query
          .append("(FROM_UNIXTIME(")
          .append(data[i][0])
          .append("),'")
          .append(data[i][1])
          .append("','")
          .append(data[i][2])
          .append("','")
          .append(data[i][3])
          .append("')");
          
          if(i<data.size()-1&&start == 0)
            insert_query.append(",");

    }

    insert_query
      .append(";COMMIT;");

    fp = fopen("/tmp/insert.log", "w+");
    fprintf(fp, "%s", insert_query.c_str());
    fclose(fp);


    results = mysql_conn->query(insert_query.c_str());
    free(ymd);
    free(ymd_old);
    if(results.size()  == 0)
      return 1;
    else
      return 0;
  } else
  if(strcmp(DB_TYPE, "clucene") == 0)
  {
    free(ymd);
    free(ymd_old);
    fprintf(stderr, "CLucene DB_TYPE is not yet supported\n");
    return 0;
  }


  free(ymd);
  free(ymd_old);

  return document_count;
}
Exemplo n.º 30
0
	void AddItems( std::vector< boost::shared_ptr<GameItem> >& pItems ) { if( pItems.empty() ) return; m_pProperty.insert( m_pProperty.end(), pItems.begin(), pItems.end() ); }