Example #1
0
template<class Super> bool
Parent<Super>::RecvGetOriginKey(const uint32_t& aRequestId,
                         const nsCString& aOrigin,
                         const bool& aPrivateBrowsing)
{
  MOZ_ASSERT(NS_IsMainThread());

  // First, get profile dir.

  MOZ_ASSERT(NS_IsMainThread());
  nsCOMPtr<nsIFile> profileDir;
  nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                       getter_AddRefs(profileDir));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  // Then over to stream-transport thread to do the actual file io.
  // Stash a pledge to hold the answer and get an id for this request.

  nsRefPtr<Pledge<nsCString>> p = new Pledge<nsCString>();
  uint32_t id = mOutstandingPledges.Append(*p);

  nsCOMPtr<nsIEventTarget> sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
  MOZ_ASSERT(sts);
  nsRefPtr<OriginKeyStore> store(mOriginKeyStore);
  bool sameProcess = mSameProcess;

  rv = sts->Dispatch(NewRunnableFrom([id, profileDir, store, sameProcess,
                                      aOrigin, aPrivateBrowsing]() -> nsresult {
    MOZ_ASSERT(!NS_IsMainThread());
    store->mOriginKeys.SetProfileDir(profileDir);
    nsCString result;
    if (aPrivateBrowsing) {
      store->mPrivateBrowsingOriginKeys.GetOriginKey(aOrigin, result);
    } else {
      store->mOriginKeys.GetOriginKey(aOrigin, result);
    }

    // Pass result back to main thread.
    nsresult rv;
    rv = NS_DispatchToMainThread(NewRunnableFrom([id, store, sameProcess,
                                                  result]() -> nsresult {
      Parent* parent = GccGetSingleton<Super>(); // GetSingleton();
      if (!parent) {
        return NS_OK;
      }
      nsRefPtr<Pledge<nsCString>> p = parent->mOutstandingPledges.Remove(id);
      if (!p) {
        return NS_ERROR_UNEXPECTED;
      }
      p->Resolve(result);
      return NS_OK;
    }), NS_DISPATCH_NORMAL);

    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    return NS_OK;
  }), NS_DISPATCH_NORMAL);

  if (NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  p->Then([aRequestId, sameProcess](const nsCString& aKey) mutable {
    if (!sameProcess) {
      if (!sIPCServingParent) {
        return NS_OK;
      }
      unused << sIPCServingParent->SendGetOriginKeyResponse(aRequestId, aKey);
    } else {
      nsRefPtr<MediaManager> mgr = MediaManager::GetInstance();
      if (!mgr) {
        return NS_OK;
      }
      nsRefPtr<Pledge<nsCString>> pledge =
          mgr->mGetOriginKeyPledges.Remove(aRequestId);
      if (pledge) {
        pledge->Resolve(aKey);
      }
    }
    return NS_OK;
  });
  return true;
}
Example #2
0
int
main()
{
    IloEnv env;
    try {
        NumMatrix cost(env, nbMonths);
        cost[0]=IloNumArray(env, nbProducts, 110.0, 120.0, 130.0, 110.0, 115.0);
        cost[1]=IloNumArray(env, nbProducts, 130.0, 130.0, 110.0,  90.0, 115.0);
        cost[2]=IloNumArray(env, nbProducts, 110.0, 140.0, 130.0, 100.0,  95.0);
        cost[3]=IloNumArray(env, nbProducts, 120.0, 110.0, 120.0, 120.0, 125.0);
        cost[4]=IloNumArray(env, nbProducts, 100.0, 120.0, 150.0, 110.0, 105.0);
        cost[5]=IloNumArray(env, nbProducts,  90.0, 100.0, 140.0,  80.0, 135.0);

        // Variable definitions
        IloNumVarArray produce(env, nbMonths, 0, IloInfinity);
        NumVarMatrix   use(env, nbMonths);
        NumVarMatrix   buy(env, nbMonths);
        NumVarMatrix   store(env, nbMonths);
        IloInt i, p;
        for (i = 0; i < nbMonths; i++) {
            use[i]   = IloNumVarArray(env, nbProducts, 0, IloInfinity);
            buy[i]   = IloNumVarArray(env, nbProducts, 0, IloInfinity);
            store[i] = IloNumVarArray(env, nbProducts, 0, 1000);
        }
        IloExpr profit(env);

        IloModel model(env);

        // For each type of raw oil we must have 500 tons at the end
        for (p = 0; p < nbProducts; p++) {
            store[nbMonths-1][p].setBounds(500, 500);
        }

        // Constraints on each month
        for (i = 0; i < nbMonths; i++) {
            // Not more than 200 tons of vegetable oil can be refined
            model.add(use[i][v1] + use[i][v2] <= 200);

            // Not more than 250 tons of non-vegetable oil can be refined
            model.add(use[i][o1] + use[i][o2] + use[i][o3] <= 250);

            // Constraints on food composition
            model.add(3 * produce[i] <=
                      8.8 * use[i][v1] + 6.1 * use[i][v2] +
                      2   * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3]);
            model.add(8.8 * use[i][v1] + 6.1 * use[i][v2] +
                      2   * use[i][o1] + 4.2 * use[i][o2] + 5 * use[i][o3]
                      <= 6 * produce[i]);
            model.add(produce[i] == IloSum(use[i]));

            // Raw oil can be stored for later use
            if (i == 0) {
                for (IloInt p = 0; p < nbProducts; p++)
                    model.add(500 + buy[i][p] == use[i][p] + store[i][p]);
            }
            else {
                for (IloInt p = 0; p < nbProducts; p++)
                    model.add(store[i-1][p] + buy[i][p] == use[i][p] + store[i][p]);
            }

            // Logical constraints
            // The food cannot use more than 3 oils
            // (or at least two oils must not be used)
            model.add((use[i][v1] == 0) + (use[i][v2] == 0) + (use[i][o1] == 0) +
                      (use[i][o2] == 0) + (use[i][o3] == 0) >= 2);

            // When an oil is used, the quantity must be at least 20 tons
            for (p = 0; p < nbProducts; p++)
                model.add((use[i][p] == 0) || (use[i][p] >= 20));

            // If products v1 or v2 are used, then product o3 is also used
            model.add(IloIfThen(env, (use[i][v1] >= 20) || (use[i][v2] >= 20),
                                use[i][o3] >= 20));

            // Objective function
            profit += 150 * produce[i] - IloScalProd(cost[i], buy[i]) -
                      5 * IloSum(store[i]);
        }

        // Objective function
        model.add(IloMaximize(env, profit));

        IloCplex cplex(model);

        if (cplex.solve()) {
            cout << "Solution status: " << cplex.getStatus() << endl;
            cout << " Maximum profit = " << cplex.getObjValue() << endl;
            for (IloInt i = 0; i < nbMonths; i++) {
                IloInt p;
                cout << " Month " << i << " " << endl;
                cout << "  . buy   ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(buy[i][p]) << "\t ";
                }
                cout << endl;
                cout << "  . use   ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(use[i][p]) << "\t ";
                }
                cout << endl;
                cout << "  . store ";
                for (p = 0; p < nbProducts; p++) {
                    cout << cplex.getValue(store[i][p]) << "\t ";
                }
                cout << endl;
            }
        }
        else {
            cout << " No solution found" << endl;
        }
    }
    catch (IloException& ex) {
        cerr << "Error: " << ex << endl;
    }
    catch (...) {
        cerr << "Error" << endl;
    }
    env.end();
    return 0;
}
Example #3
0
int main(int argc, char* argv[]) {
  
  int returnCode = 0;
  std::string context;
  bool alwaysAddContext = true;
  //Default to only use 1 thread. We define this early since plugin system or message logger
  // may be using TBB.
  bool setNThreadsOnCommandLine = false;
  std::unique_ptr<tbb::task_scheduler_init> tsiPtr{new tbb::task_scheduler_init{1}};
  boost::shared_ptr<edm::Presence> theMessageServicePresence;
  std::unique_ptr<std::ofstream> jobReportStreamPtr;
  boost::shared_ptr<edm::serviceregistry::ServiceWrapper<edm::JobReport> > jobRep;
  EventProcessorWithSentry proc;

  try {
    try {

      // NOTE: MacOs X has a lower rlimit for opened file descriptor than Linux (256
      // in Snow Leopard vs 512 in SLC5). This is a problem for some of the workflows
      // that open many small root datafiles.  Notice that this is safe to do also
      // for Linux, but we agreed not to change the behavior there for the moment.
      // Also the limits imposed by ulimit are not affected and still apply, if
      // there.
#ifdef __APPLE__
      context = "Setting file descriptor limit";
      struct rlimit limits;
      getrlimit(RLIMIT_NOFILE, &limits);
      limits.rlim_cur = (OPEN_MAX < limits.rlim_max) ? OPEN_MAX : limits.rlim_max;
      setrlimit(RLIMIT_NOFILE, &limits);
#endif

      context = "Initializing plug-in manager";
      edmplugin::PluginManager::configure(edmplugin::standard::config());

      // Decide whether to use the multi-thread or single-thread message logger
      //    (Just walk the command-line arguments, since the boost parser will
      //    be run below and can lead to error messages which should be sent via
      //    the message logger)
      context = "Initializing either multi-threaded or single-threaded message logger";
      bool multiThreadML = false;
      for(int i = 0; i < argc; ++i) {
        if((std::strncmp (argv[i], "-t", 20) == 0) ||
           (std::strncmp (argv[i], "--multithreadML", 20) == 0)) {
          multiThreadML = true;
          break;
        }
      }

      // Load the message service plug-in

      if(multiThreadML) {
        theMessageServicePresence = boost::shared_ptr<edm::Presence>(edm::PresenceFactory::get()->
          makePresence("MessageServicePresence").release());
      }
      else {
        theMessageServicePresence = boost::shared_ptr<edm::Presence>(edm::PresenceFactory::get()->
          makePresence("SingleThreadMSPresence").release());
      }

      context = "Processing command line arguments";
      std::string descString(argv[0]);
      descString += " [options] [--";
      descString += kParameterSetOpt;
      descString += "] config_file \nAllowed options";
      boost::program_options::options_description desc(descString);

      desc.add_options()
        (kHelpCommandOpt, "produce help message")
        (kParameterSetCommandOpt, boost::program_options::value<std::string>(), "configuration file")
        (kJobreportCommandOpt, boost::program_options::value<std::string>(),
                "file name to use for a job report file: default extension is .xml")
        (kEnableJobreportCommandOpt,
                "enable job report files (if any) specified in configuration file")
        (kJobModeCommandOpt, boost::program_options::value<std::string>(),
                "Job Mode for MessageLogger defaults - default mode is grid")
      (kNumberOfThreadsCommandOpt,boost::program_options::value<unsigned int>(),
                "Number of threads to use in job (0 is use all CPUs)")
        (kMultiThreadMessageLoggerOpt,
                "MessageLogger handles multiple threads - default is single-thread")
        (kStrictOpt, "strict parsing");

      // anything at the end will be ignored, and sent to python
      boost::program_options::positional_options_description p;
      p.add(kParameterSetOpt, 1).add(kPythonOpt, -1);

      // This --fwk option is not used anymore, but I'm leaving it around as
      // it might be useful again in the future for code development
      // purposes.  We originally used it when implementing the boost
      // state machine code.
      boost::program_options::options_description hidden("hidden options");
      hidden.add_options()("fwk", "For use only by Framework Developers")
        (kPythonOpt, boost::program_options::value< std::vector<std::string> >(),
         "options at the end to be passed to python");

      boost::program_options::options_description all_options("All Options");
      all_options.add(desc).add(hidden);

      boost::program_options::variables_map vm;
      try {
        store(boost::program_options::command_line_parser(argc, argv).options(all_options).positional(p).run(), vm);
        notify(vm);
      }
      catch (boost::program_options::error const& iException) {
        edm::LogAbsolute("CommandLineProcessing") << "cmsRun: Error while trying to process command line arguments:\n"
          << iException.what()
	  << "\nFor usage and an options list, please do 'cmsRun --help'.";
        return edm::errors::CommandLineProcessing;
      }

      if (vm.count(kHelpOpt)) {
        std::cout << desc << std::endl;
        if (!vm.count(kParameterSetOpt)) edm::HaltMessageLogging();
        return 0;
      }
      
      if(vm.count(kNumberOfThreadsOpt)) {
        setNThreadsOnCommandLine=true;
        unsigned int nThreads = vm[kNumberOfThreadsOpt].as<unsigned int>();
        setNThreads(nThreads,tsiPtr);
      }

      if (!vm.count(kParameterSetOpt)) {
        edm::LogAbsolute("ConfigFileNotFound") << "cmsRun: No configuration file given.\n"
          << "For usage and an options list, please do 'cmsRun --help'.";
        edm::HaltMessageLogging();
        return edm::errors::ConfigFileNotFound;
      }
      std::string fileName(vm[kParameterSetOpt].as<std::string>());

      if (vm.count(kStrictOpt)) {
        //edm::setStrictParsing(true);
        edm::LogSystem("CommandLineProcessing") << "Strict configuration processing is now done from python";
      }

      context = "Creating the JobReport Service";
      // Decide whether to enable creation of job report xml file
      //  We do this first so any errors will be reported
      std::string jobReportFile;
      if (vm.count(kJobreportOpt)) {
        jobReportFile = vm[kJobreportOpt].as<std::string>();
      } else if(vm.count(kEnableJobreportOpt)) {
        jobReportFile = "FrameworkJobReport.xml";
      }
      jobReportStreamPtr = std::auto_ptr<std::ofstream>(jobReportFile.empty() ? 0 : new std::ofstream(jobReportFile.c_str()));

      //NOTE: JobReport must have a lifetime shorter than jobReportStreamPtr so that when the JobReport destructor
      // is called jobReportStreamPtr is still valid
      std::auto_ptr<edm::JobReport> jobRepPtr(new edm::JobReport(jobReportStreamPtr.get()));
      jobRep.reset(new edm::serviceregistry::ServiceWrapper<edm::JobReport>(jobRepPtr));
      edm::ServiceToken jobReportToken =
        edm::ServiceRegistry::createContaining(jobRep);

      context = "Processing the python configuration file named ";
      context += fileName;
      boost::shared_ptr<edm::ProcessDesc> processDesc;
      try {
        boost::shared_ptr<edm::ParameterSet> parameterSet = edm::readConfig(fileName, argc, argv);
        processDesc.reset(new edm::ProcessDesc(parameterSet));
      }
      catch(cms::Exception& iException) {
        edm::Exception e(edm::errors::ConfigFileReadError, "", iException);
        throw e;
      }
      
      //See if we were told how many threads to use. If so then inform TBB only if
      // we haven't already been told how many threads to use in the command line
      context = "Setting up number of threads";
      {
        if(not setNThreadsOnCommandLine) {
          boost::shared_ptr<edm::ParameterSet> pset = processDesc->getProcessPSet();
          if(pset->existsAs<edm::ParameterSet>("options",false)) {
            auto const& ops = pset->getUntrackedParameterSet("options");
            if(ops.existsAs<unsigned int>("numberOfThreads",false)) {
              unsigned int nThreads = ops.getUntrackedParameter<unsigned int>("numberOfThreads");
              setNThreads(nThreads,tsiPtr);
            }
          }
        }
      }

      context = "Initializing default service configurations";
      std::vector<std::string> defaultServices;
      defaultServices.reserve(7);
      defaultServices.push_back("MessageLogger");
      defaultServices.push_back("InitRootHandlers");
#ifdef linux
      defaultServices.push_back("EnableFloatingPointExceptions");
#endif
      defaultServices.push_back("UnixSignalService");
      defaultServices.push_back("AdaptorConfig");
      defaultServices.push_back("SiteLocalConfigService");
      defaultServices.push_back("StatisticsSenderService");

      // Default parameters will be used for the default services
      // if they are not overridden from the configuration files.
      processDesc->addServices(defaultServices);

      context = "Setting MessageLogger defaults";
      // Decide what mode of hardcoded MessageLogger defaults to use
      if (vm.count(kJobModeOpt)) {
        std::string jobMode = vm[kJobModeOpt].as<std::string>();
        edm::MessageDrop::instance()->jobMode = jobMode;
      }

      context = "Constructing the EventProcessor";
      std::auto_ptr<edm::EventProcessor>
          procP(new
                edm::EventProcessor(processDesc, jobReportToken,
                                    edm::serviceregistry::kTokenOverrides));
      EventProcessorWithSentry procTmp(procP);
      proc = procTmp;

      alwaysAddContext = false;
      context = "Calling beginJob";
      proc->beginJob();

      alwaysAddContext = true;
      context = "Calling EventProcessor::forkProcess";
      if (!proc->forkProcess(jobReportFile)) {
        return 0;
      }

      alwaysAddContext = false;
      context = "Calling EventProcessor::runToCompletion (which does almost everything after beginJob and before endJob)";
      proc.on();
      bool onlineStateTransitions = false;
      proc->runToCompletion(onlineStateTransitions);
      proc.off();

      context = "Calling endJob";
      proc->endJob();
    }
    catch (cms::Exception& e) {
      throw;
    }
    // The functions in the following catch blocks throw an edm::Exception
    catch(std::bad_alloc& bda) {
      edm::convertException::badAllocToEDM();
    }
    catch (std::exception& e) {
      edm::convertException::stdToEDM(e);
    }
    catch(std::string& s) {
      edm::convertException::stringToEDM(s);
    }
    catch(char const* c) {
      edm::convertException::charPtrToEDM(c);
    }
    catch (...) {
      edm::convertException::unknownToEDM();
    }
  }
  // All exceptions which are not handled before propagating
  // into main will get caught here.
  catch (cms::Exception& ex) {
    returnCode = ex.returnCode();
    if (!context.empty()) {
      if (alwaysAddContext) {
        ex.addContext(context);
      }
      else if (ex.context().empty()) {
        ex.addContext(context);
      }
    }
    if (!ex.alreadyPrinted()) {
      if (jobRep.get() != 0) {
        edm::printCmsException(ex, &(jobRep->get()), returnCode);
      }
      else {
        edm::printCmsException(ex);
      }
    }
  }
  // Disable Root Error Handler.
  SetErrorHandler(DefaultErrorHandler);
  return returnCode;
}
    void store( const trx_block& b, const signed_transactions& deterministic_trxs, const block_evaluation_state_ptr& state  )
{   try {
            std::vector<uint160> trxs_ids;
            uint16_t t = 0;
            std::map<int32_t,uint64_t> delegate_votes;
            for( uint32_t i = 1; i <= 100; ++i )
            {
                delegate_votes[i] = 0;
            }
            for( ; t < b.trxs.size(); ++t )
            {
                store( b.trxs[t], trx_num( b.block_num, t) );
                trxs_ids.push_back( b.trxs[t].id() );


                /*** on the genesis block we need to store initial delegates and vote counts */
                if( b.block_num == 0 )
                {
                    if( t == 0 )
                    {
                        for( uint32_t o = 0; o < b.trxs[t].outputs.size(); ++o )
                        {
                            if( b.trxs[t].outputs[o].claim_func == claim_name )
                            {
                                auto claim = b.trxs[t].outputs[o].as<claim_name_output>();
                                update_name_record( claim.name, claim );
                                //    if( claim.delegate_id != 0 )
                                update_delegate( name_record( claim ) );
                            }
                        }
                    }
                    else // t != 0
                    {
                        name_record rec = _delegate_records.fetch( b.trxs[t].vote );
                        // first transaction registers names... the rest are initial balance
                        for( uint32_t o = 0; o < b.trxs[t].outputs.size(); ++o )
                        {
                            delegate_votes[b.trxs[t].vote] += b.trxs[t].outputs[o].amount.get_rounded_amount();
                            rec.votes_for += to_bips( b.trxs[t].outputs[o].amount.get_rounded_amount(), b.total_shares );
                        }
                        update_delegate( rec );
                    }
                } // block == 0
            }
            elog( "total votes:\n ${e}", ("e",fc::json::to_pretty_string( delegate_votes) ) );
            uint64_t sum = 0;
            for( auto i : delegate_votes )
            {
                sum += i.second;
            }
            elog( "grand total: ${g}", ("g",sum) );

            for( const signed_transaction& trx : deterministic_trxs )
            {
                store( trx, trx_num( b.block_num, t) );
                ++t;
                // trxs_ids.push_back( trx.id() );
            }
            head_block    = b;
            head_block_id = b.id();

            blocks.store( b.block_num, b );
            block_trxs.store( b.block_num, trxs_ids );

            blk_id2num.store( b.id(), b.block_num );

            for( auto item : state->_name_outputs )
            {
                update_name_record( item.first, item.second );
            }
            for( auto item : state->_input_votes )
            {
                auto rec = _delegate_records.fetch( abs(item.first) );
                if( item.first < 0 )
                    rec.votes_against -= to_bips(item.second,b.total_shares);
                else
                    rec.votes_for     -= to_bips(item.second,b.total_shares);
                update_delegate( rec );
            }
            for( auto item : state->_output_votes )
            {
                auto rec = _delegate_records.fetch( abs(item.first) );
                if( item.first < 0 )
                    rec.votes_against += to_bips( item.second, b.total_shares );
                else
                    rec.votes_for     += to_bips( item.second, b.total_shares );
                update_delegate( rec );
            }

        }
        FC_RETHROW_EXCEPTIONS( warn, "" )
    }
int main(){
	personagem per;
	monstro mon;
	char *map;
	char tEnd=1,tQuit=1,tRoom, test,test2;
	
	item it;
	strcpy(it.nome,"Capa Vampirica\0");
	it.categoria='a';
	it.value=80;

	monstro blair;
	blair.magicD = 160;
	blair.fisicalD = 160;
	blair.distD = 160;
	blair.atkType = 'm';
	blair.atk = 250;
	strcpy(blair.nome,"Bruxa Blair\0");
	strcpy(blair.drop,"Camiseta do TUSCA\0");
	blair.HP = 120;
	blair.XP = 0;

	srand(time(NULL));

	do{
		test=start(&per,&map);
		if(test==2)continue;
		if(test==1)break;
		scanf("%*c");
		do{
			system("cls");
			printf("SALA %i\n",per.pos);

			printf("deseja mexer em seu inventario?(s/n):");
			scanf("%c",&test);
			if(test=='s'){
				invMenu(&per);///cuidado olhar argumentos
			}			

			do{
				printf("Digite a direcao que dejeja seguir:norte-w; sul-s; leste-d; oeste-a; quit game-q:");
				scanf("%c",&test);
			}while(test!='w' && test!='a' && test!='s' && test!='d' && test!='q');

			if(test=='q'){
				printf("deseja salvar o seu progresso?(s/n)");
				scanf("%*c");
				scanf("%*c");
				scanf("%c",&test);
				if(test=='s'){
					test2=save(per);
				}
				tQuit=0;
				break;
			}
			else{
				move(test,&(per.pos));
			}

			printf("SALA %i\n",per.pos);

			switch(map[per.pos]){
				case 0://sala qualquer sem importancia
					tRoom=rand()%100;

					if(tRoom>=35){
						mon=monsterGet(rand()%monsterNum);
						tQuit=combat(&per,&mon);
						break;
					}

					if(tRoom>=15){
						printf("nao ha nada na sala\n");
						break;
					}

					if(tRoom>=5){
						printf("voce encontrou uma fonte de cura, e aproveitou para relaxar e tomar um banho, afinal ate os herois ficam cansados(as).");
						printf(" Alem de especialmente fedidos(as) afinal de contas um covil de monstros nao cheiram tao bem assim (na maioria dos casos)\n");
						heal(&per);
						break;
					}

					item it;
					test2=itemGet(rand()%itemNum,&it);
					printf("voce encontrou um '%s' deseja guardar no seu inventario?(s/n)\n",it.nome);
					scanf("%*c");
					scanf("%c",&test);
					if(test=='s'){
						store(it);
					}

					break;
				case 1://sala 0
					printf("SALA ZERO\n\n");
					printf("Voce esta em uma sala ampla com paredes e chao de pedra, ao seu redor existem varios destrocos pedacos de madeira e pedra, provavelmente vindos do telhado, ");
					printf("ja partido com frestas que permitem observar um o azul do ceu, e da decoracao, que antes imponente e bela agora nao passa de escombros\n\n");
					printf("mas voce eh capaz de identificar no meio disso um pedestal de pedra e sobre ele apenas os pes do que um dia ja foi uma estatua e uma inscricao que diz:\n");
					printf("'voce esta agora em um local seguro jovem aventureiro ou aventureira, aproveite este lugar para se preparar para as aventuras que estao a seguir.'");
					printf("\n o resto estva ilegivel apagado pelo tempo. Voce aproveita a seguranca temporaria para se preparar para o que ha a seguir");
					heal(&per);
					break;
				case 2://sala com primeiro boss Alucard
					printf("voce sente seu corpo ser transportado para um local difente das ruinas em que voce estava anteriormnte, voce agora esta em uma sala nao muito grande,mas");
					printf(" muito bem decorada com itens de beleza rara, apesar de ja ser noite a sala esta bem iluminada e ao olhar na direcao da janela voce ve um homem.\n");
					printf("Ele esta vestindo um longo sobretudo preto com detalhes em vermelho por cima da camisa e calca tambem de coras escuras e logo se vira para voce e diz:\n");
					printf("'seja bem vindo ao meu humilde castelo %s,eu estava lhe esperando. Meu nome eh Alucard sou um dos gurdioes das ruinas dos herois, por favor sente-se",per.nome);
					printf(", vou lhe contar a triste historia deste lugar:\n");
					system("pause");
					system("cls");
					printf("Ha muitos anos este lugar era um reduto de aventureiros que que reuniam nos arredores para desafiar as salas e conquistar as recompensas ");
					printf("que aqui existem, ate que um dia a bruxa Blair, que era uma guardia, assasinou o antigo mestre, tomou seu lugar e comecou a enviar os desafiantes para ");
					printf("a morte certa ate que certa vez os aventureiros se revoltaram contra ela. Uma grande batalha foi travada e o resultado foi um massacre. Eles nao puderam ");
					printf("conta as forcas de Blair e tudo o que restou sao os destrocos da sala zero. Apos isso os poucos que fugiram no inicio da batalha lacraram a entada para que " );
					printf("nenhum desavisado caisse em suas garas. Desde entao Blair tem trazido pessoas aqui atravez de armadilhas para que lutem aqui ate a morte certa, destruindo ");
					printf("os ideais do primeiro mestre. Eu nunca pude fazer nada contra o seu poder, mas agora com voce aqui eh diferente, voce tem potencial para mudar isto.");
					system("pause");
					system("cls");
					printf("Torne-se mais forte para poder derrota-la, eu orei lhe ajudar quando a hora chegar.\nComo prova de minha lealdade lhe dou isto:'\n");
					printf("Voce recebeu a 'capa vampirica' e guardou em seu inventario.");
					store(it);
					printf("'um ultimo aviso cuidado com o proximo guardiao ele pode parecer inofensivo mas eh uma fera selvagem e mortal.'");
					system("pause");
					system("cls");
					printf("voce entao retorna para as ruinas");
					per.rooms[0]=0;
					map[per.pos]=0;
					break;
				case 3://sala com segundo boss galinha
					if(per.rooms[0]!=0){
						printf("nao ha nada na sala\n");
						break;
					}
					printf("Ao entrar na sala voce se ve em meio a um palheiro e bem ao centro voce ve uma galinha.\no que voce deseja fazer:");
					printf("1 - matar a galinha e assar sua carne (ela parece suculenta);");
					printf("2 - andar de fininho e passar tentando nao chamar a atencao;");
					printf("outro - gritar por socoro;");
					scanf("%c",&test);
					switch(test){
						case '1':
							printf("A galinha eh mais poderosa que voce e te mata.");
							tQuit=0;
							break;
						case '2':
							printf("voce passa sem cahmar a atencao e se salva");
							per.rooms[1]=0;
							map[per.pos]=0;
							break;
						default:
							printf("Voce chamou a atencao da galinha, sair vivo nao eh mais uma opcao.");
							tQuit=0;
							break;						
					}
					break;				
				case 4:
					if(per.rooms[1]!=0){
						printf("nao ha nada na sala\n");
						break;
					}
					printf("Voce se encontra agora num lugar que aparenta ser uma arena de combate medieval. Blair se encontra a sua frente com seu cajado em posicao de combate");
					printf("Blair diz: 'me surpreende muito que voce tenha chegado ate aqui, achei que fosse apenas mais um idiota, mas voce tem algum valor.'");
					system("pause");
					test=combat(&per,&blair);
					switch(test){
						case 0:
							tQuit = 0;
							break;
						case 1:
							printf("Com a morte de Blair, Alucard assume o comendo das Ruina dos Herois e voce eh nomeado um dos Guardioes da Ruina. \n");
							printf("Novamente, aventureiros se reunem para desafiar as salas e conquistar suas recompensas.\n");
							printf(" Voce jamais volta para casa, afinal, para que voltar para casa?!");
							printf("\n\nFIM.");
							break;
						case 2:
							printf("Voce foi transportado para a SALA ZERO");
							per.pos = 0;
							break;
					}
			}

			if(tQuit==0)break;

			printf("deseja salvar o seu progresso?(s/n)");
			scanf("%c",&test);
			if(test=='s'){
				save(per);
			}

		}while(tQuit);

		printf("deseja voltar ao menu inicial?(s/n)");
		scanf("%*c");
		scanf("%c",&tEnd);
		system("cls");

	}while(tEnd!='n');
	system("pause");
	return 0;
}
Tsubtitle* TsubtitleParserSami::parse(Tstream &fd, int flags, REFERENCE_TIME start, REFERENCE_TIME stop)
{
    wchar_t text[this->LINE_LEN + 1], *p = NULL, *q;
    int state;

    /* read the first line */
    if (!s)
        if ((s = fd.fgets(line, this->LINE_LEN)) == NULL) {
            return NULL;
        }

    TsubtitleText current(this->format);
    current.start = current.stop = 0;
    state = 0;

    do {
        switch (state) {

        case 0: /* find "START=" or "Slacktime:" */
            slacktime_s = stristr(s, L"Slacktime:");
            if (slacktime_s) {
                sub_slacktime = strtol(slacktime_s + 10, NULL, 0) / 10;
            }

            s = (wchar_t*)stristr(s, L"Start=");
            if (s) {
                int sec1000 = strtol(s + 6, &s, 0);
                current.start = this->hmsToTime(0, 0, sec1000 / 1000, (sec1000 % 1000) / 10);
                /* eat '>' */
                for (; *s != '>' && *s != '\0'; s++) {
                    ;
                }
                s++;
                state = 1;
                continue;
            }
            break;

        case 1: /* find (optionnal) "<P", skip other TAGs */
            for (; *s == ' ' || *s == '\t'; s++) {
                ;    /* strip blanks, if any */
            }
            if (*s == '\0') {
                break;
            }
            if (*s != '<') {
                state = 3;    /* not a TAG */
                p = text;
                continue;
            }
            s++;
            if (*s == 'P' || *s == 'p') {
                s++;    /* found '<P' */
                state = 2;
                continue;
            }
            for (; *s != '>' && *s != '\0'; s++) {
                ;    /* skip remains of non-<P> TAG */
            }
            if (s == '\0') {
                break;
            }
            s++;
            continue;

        case 2: /* find ">" */
            if ((s = strchr(s, '>')) != NULL) {
                s++;
                state = 3;
                p = text;
                continue;
            }
            break;

        case 3: /* get all text until '<' appears */
            if (*s == '\0') {
                break;
            } else if (!_strnicmp(s, L"<br>", 4)) {
                *p = '\0';
                p = text;
                trail_space(text);
                if (text[0] != '\0') {
                    current.add(text);
                }
                s += 4;
            } else if ((*s == '{') && !sub_no_text_pp) {
                state = 5;
                ++s;
                continue;
            } else if (*s == '<') {
                state = 4;
            } else if (!_strnicmp(s, L"&nbsp;", 6)) {
                *p++ = ' ';
                s += 6;
            } else if (*s == '\t') {
                *p++ = ' ';
                s++;
            } else if (*s == '\r' || *s == '\n') {
                s++;
            } else {
                *p++ = *s++;
            }

            /* skip duplicated space */
            if (p > text + 2) if (*(p - 1) == ' ' && *(p - 2) == ' ') {
                    p--;
                }

            continue;

        case 4: /* get current->end or skip <TAG> */
            q = (wchar_t*)stristr(s, L"Start=");
            if (q) {
                int sec1000 = strtol(q + 6, &q, 0);
                current.stop = this->hmsToTime(0, 0, sec1000 / 1000, (sec1000 % 1000) / 10 - 1);
                *p = '\0';
                trail_space(text);
                if (text[0] != '\0') {
                    current.add(text);
                }
                if (current.size() > 0) {
                    state = 99;
                    break;
                }
                state = 0;
                continue;
            }
            s = strchr(s, '>');
            if (s) {
                s++;
                state = 3;
                continue;
            }
            break;
        case 5: /* get rid of {...} text, but read the alignment code */
            if ((*s == '\\') && (*(s + 1) == 'a') && !sub_no_text_pp) {
                if (stristr(s, L"\\a1") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_BOTTOMLEFT;
                    s = s + 3;
                }
                if (stristr(s, L"\\a2") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_BOTTOMCENTER;
                    s = s + 3;
                } else if (stristr(s, L"\\a3") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_BOTTOMRIGHT;
                    s = s + 3;
                } else if ((stristr(s, L"\\a4") != NULL) || (stristr(s, L"\\a5") != NULL) || (stristr(s, L"\\a8") != NULL)) {
                    //current->alignment = SUB_ALIGNMENT_TOPLEFT;
                    s = s + 3;
                } else if (stristr(s, L"\\a6") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_TOPCENTER;
                    s = s + 3;
                } else if (stristr(s, L"\\a7") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_TOPRIGHT;
                    s = s + 3;
                } else if (stristr(s, L"\\a9") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_MIDDLELEFT;
                    s = s + 3;
                } else if (stristr(s, L"\\a10") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_MIDDLECENTER;
                    s = s + 4;
                } else if (stristr(s, L"\\a11") != NULL) {
                    //current->alignment = SUB_ALIGNMENT_MIDDLERIGHT;
                    s = s + 4;
                }
            }
            if (*s == '}') {
                state = 3;
            }
            ++s;
            continue;
        }

        /* read next line */
        if (state != 99 && (s = fd.fgets(line, this->LINE_LEN)) == NULL) {
            if (current.start > 0) {
                break; // if it is the last subtitle
            } else {
                return NULL;
            }
        }

    } while (state != 99);

    // For the last subtitle
    if (current.stop <= 0) {
        current.stop = current.start + this->hmsToTime(0, 0, sub_slacktime / 1000, (sub_slacktime % 1000) / 10);
        *p = '\0';
        trail_space(text);
        if (text[0] != '\0') {
            current.add(text);
        }
    }
    return store(current);
}
Example #7
0
/* ------------------------------------------------------------------------------------------ */
void checkInstruction(ins *p){
	reg *rz=NULL;
	reg *rx=NULL;
	reg *ry=NULL;
	reg *rt=NULL;	// temporary register (may or not be used)
	ins *ip=NULL;	// auxiliary instruction pointer (for other registers)
	ins *ti=NULL;	// temporary instruction pointer (to be used with the temporary register)
	ins *mi=NULL;	// main instruction pointer (used with the final instruction)


	/*
	 *  >> input: rz = rx <op> ry
	 *
	 *
	 *	rx = ARP + lookup(rx->value)
	 *    	rx = * rx
	 *    	ry = ARP + lookup(ry->value)
	 *    	ry = * ry
	 *    	rt = rx <op> ry
	 *    	rz = ARP + lookup(rz->value)
	 *	*rz = rt
	 */


	if(p == NULL)
		return;

	#ifdef VERBOSE
		printf("\n");
		table_print(registers);
		printf("[checkInstruction] ");
		printInstruction(p);
	#endif



// :: -------------------------------- ::   THE ALGORITHM   ::

// 1st step:  ensure that 'rx' and 'ry' have register
// --

	// checking 'rx'
	if((p->src1[0] != '\0') && !isNumeric(p->src1)){
		rx=reg_search(p->src1);
		if(rx==NULL){
	
			// allocates register
			rx=reg_ensure(p->src1);
			if(isVar(p->src1)){
				
				// loading the local variable from memory
				load(p->src1);
				
				ip = createInstruction(idx++);
				copy(ip->dst, rx->name);
				ip->arp=true;
				ip->offset=lookup(p->src1);
				append(ip);

				ip = createInstruction(idx++);
				copy(ip->dst, rx->name);
				ip->ops1='*';
				copy(ip->src1, rx->name);
				append(ip);
			}
			if(rx!=NULL){
				// set properties for register
				rx->dist=distance(p, rx->value);
				rx->dirty=false;
			}
		}
	} else rx=NULL;

	// checking 'ry'
	if((p->src2[0] != '\0') && !isNumeric(p->src2)){
		ry=reg_search(p->src2);
		if(ry==NULL){

			// allocates register
			ry=reg_ensure(p->src2);
			if(isVar(p->src2)){
				
				// loading the local variable 'ry' from memory
				load(p->src2);
				
				// loading the local variable 'ry' from memory
				ip = createInstruction(idx++);
				copy(ip->dst, ry->name);
				ip->arp=true;
				ip->offset=lookup(p->src2);
				append(ip);
	
				ip = createInstruction(idx++);
				copy(ip->dst, ry->name);
				ip->ops1='*';
				copy(ip->src1, ry->name);
				append(ip);
			}
			if(ry!=NULL){
				// set properties for register
				ry->dist=distance(p, ry->value);
				ry->dirty=true;
			}
		}
	} else ry=NULL;

// 2nd step: allocate the 'rt' temporary register; creates the 'ti' temporary instruction
// --

	ti = createInstruction(idx++);

	// get 'rx'
	if(isNumeric(p->src1))
		copy(ti->src1, p->src1);  // found a constant
	else if(rx!=NULL)
		copy(ti->src1, rx->name); // got the 'rx'

	// get the operator
	ti->ops2=p->ops2;

	// get 'ry'
	if(isNumeric(p->src2))
		copy(ti->src2, p->src2);  // found a constant
	else if(ry!=NULL)
		copy(ti->src2, ry->name); // got the 'ry'

	if((p->dst[0] != '\0') && !isNumeric(p->dst)){

		// allocate the 'rt' register ("r0" by default)
		rt=reg_search("store");
//		rt=reg_get();
		if(rt!=NULL)
			rt->dirty=false;
	} else rt=NULL; // this could lead to an error
	if(rt!=NULL)
		copy(ti->dst, rt->name);

	append(ti);

// 3rd step: frees if possible frees 'rx' and 'ry'
// --

	// free 'rx'
	if((rx!=NULL) && (rx->dist==MAXDIST || rx->dist==-2))
		reg_free(rx);
	// free 'ry'
	if((ry!=NULL) && (ry->dist==MAXDIST || ry->dist==-2))
		reg_free(ry);

// 4th step: allocate the 'rz' register and create the main instruction 'mi'
// --

	mi = createInstruction(idx++);

	// allocate the 'rz' register
	if((p->dst[0] != '\0') && !isNumeric(p->dst)){

		// store
		store(p->dst);
		rz=reg_search(p->dst);
		if(rz==NULL){
			
			// allocates register
			rz=reg_ensure(p->dst);

			if(isVar(p->dst)){
				// loads the local variable for store operation
				ip = createInstruction(idx++);
				copy(ip->dst, rz->name);
				ip->arp=true;
				ip->offset=lookup(p->dst);
				append(ip);
			}
			if(rz!=NULL){
				// set properties for register
				rz->dist=distance(p, rz->value);
				rz->dirty=false;
			}
		}
	} else rz=NULL; // this would be an error
	if(rz!=NULL)
		copy(mi->dst, rz->name);
	if(rt!=NULL)
		copy(mi->src1, rt->name);
	if(isVar(p->dst))
		mi->opd='*';
	append(mi);


// 5th step: frees 'rt'; if possible frees 'rz'
// --

	#ifdef VERBOSE
		if(rt!=NULL) printf(" [rt] store: %s :: (%s)\n", rt->name, rt->value);
		else printf(" [rt] is null\n");
		if(rz!=NULL) printf(" [rz] store: %s :: (%s)\n", rz->name, rz->value);
		else printf(" [rz] is null\n");
	#endif
	// free 'rt'
	if(rt!=NULL) reg_free(rt);
	// free 'rz'
	if((rz!=NULL) && (rz->dist==MAXDIST || rz->dist<0))
		reg_free(rz);

// 6th step: set the dirty property for the registers
// --
	// check 'rx'
	if(rx!=NULL)
		rx->dirty=true;
	// check 'ry'
	if(ry!=NULL)
		ry->dirty=true;
	// check 'rt'
	if(rt!=NULL)
		rt->dirty=true;
	// check 'rz'
	if(rz!=NULL)
		rz->dirty=false;

// nota: um registo e' dirty apenas quando o seu conteudo e' manipulado na memoria !!!!
//      (confirmar e corrigir se necessario o 6o passo)
//      mudar os valores de dirty para oposto:  'false' <-> 'true'

// :: -------------------------------- ::   THE END   ::

	#ifdef VERBOSE
		table_print(registers);
		printf("\n");
	#endif
	return;
}
Example #8
0
int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);

  // Declare a group of options that will be allowed
  // only on the command line
  po::options_description generic("Generic options");
  generic.add_options()
      ("data", po::value<std::string>(), "Path to split data")
      ("rank,k", po::value<int>()->default_value(7), "Rank of the factors")
      ;
      
  // Declare a group of options that will be allowed
  // both on the command line and in a config file
  po::options_description config("Configuration");
  config.add_options()
      ("clients", po::value<int>()->default_value(1), "Number of clients")
      ("id", po::value<int>()->default_value(0), "This client's ID")
      ("workers", po::value<int>()->default_value(3),
       "Number of worker threads per client")
      ("iterations,i", po::value<int>()->default_value(1),
       "Number of iterations")
      ("users", po::value<int>(), "Number of users")
      ("products", po::value<int>(), "Number of products")
      ("words", po::value<int>()->default_value(2938), "Number of words")
      ("seed", po::value<int>()->default_value(0),
       "Random seed")
      ("atol", po::value<float>()->default_value(0.01),
       "Minimum absolute MSE improvement before termination")
      ("rtol", po::value<float>()->default_value(0.01),
       "Minimum relative MSE improvement before termination")
      ("clamp", po::value<bool>()->default_value(false),
       "If true, then use non-negative projection.")
      ("reg", po::value<bool>()->default_value(false),
       "If true, then regularize.")
      ("reg-thr", po::value<int>()->default_value(1),
       "Iteration in which to start regularize")
      ("lambda", po::value<float>()->default_value(0.5),
       "Weight of the l2 regularizer")
      ("stop-tol,s", po::value<int>()->default_value(3), "Stop if no improvement were made in last s iterations")
      ;
       
  po::options_description cmdline_options;
  cmdline_options.add(generic).add(config);
  
  po::options_description config_file_options;
  config_file_options.add(config);

  po::variables_map vm;
  store(po::command_line_parser(argc, argv).options(cmdline_options).run(), vm);
  
  std::string datapath = vm["data"].as<std::string>();
  int rank = vm["rank"].as<int>();
  
  std::ifstream ifs(datapath + "/run_config.cfg");
  store(parse_config_file(ifs, config_file_options), vm);
  //notify(vm);
  
  int client_id = vm["id"].as<int>();
  int num_clients = vm["clients"].as<int>();
  int num_workers = vm["workers"].as<int>();
  int iterations = vm["iterations"].as<int>();
  int num_users = vm["users"].as<int>();
  int num_products = vm["products"].as<int>();
  int num_words = vm["words"].as<int>();
  int seed = vm["seed"].as<int>();
  float atol = vm["atol"].as<float>();
  float rtol = vm["rtol"].as<float>();
  bool clamp = vm["clamp"].as<bool>();
  bool reg = vm["reg"].as<bool>();
  int reg_thr = vm["reg-thr"].as<int>();
  float lambda = vm["lambda"].as<float>();
  int stop_tol = vm["stop-tol"].as<int>();

  // Register row types
  petuum::PSTableGroup::RegisterRow<petuum::DenseRow<float>>(RowType::FLOAT);

  // Initialize group
  petuum::TableGroupConfig table_group_config;
  table_group_config.host_map.insert(
      std::make_pair(0, petuum::HostInfo(0, "127.0.0.1", "10000")));
  table_group_config.consistency_model = petuum::SSP;
  table_group_config.num_tables = 4;
  table_group_config.num_total_clients = num_clients;
  table_group_config.num_local_app_threads = num_workers + 1;
  // Somehow a larger number than 1 leads to hanging at the end while the main
  // thread waits for all seRproder threads to terminate. Apparently one of them is
  // not receiving a kClientShutDown message.
  table_group_config.num_comm_channels_per_client = 1;
  table_group_config.client_id = client_id;
  petuum::PSTableGroup::Init(table_group_config, false);

  // create tables
  gaml::tf::Worker::initTables(Table::U, Table::P, Table::T, Table::SE, RowType::FLOAT, rank,
                               num_users, num_products, num_words, iterations, num_workers);
  petuum::PSTableGroup::CreateTableDone();

  std::vector<std::thread> threads(num_workers);

  // run workers
  for (int i = 0; i < num_workers; i++) {
    int id = client_id * num_workers + i;
    threads[i] = std::thread(&TfThread::run,
                             std::unique_ptr<TfThread>(new TfThread(
                              id, datapath, rank, iterations, stop_tol, lambda, clamp, reg, reg_thr)));
  }

  for (auto& thread : threads) {
    thread.join();
  }

  // Finalize
  petuum::PSTableGroup::ShutDown();

  return 0;
}
void SessionManagerTests::testSessionInfo()
{
	// Create an empty object store
#ifndef _WIN32
	ObjectStore store("./testdir");
#else
	ObjectStore store(".\\testdir");
#endif

	// Create the managers
	SlotManager slotManager(&store);
	SessionManager sessionManager;

	// Get a slot
	CK_SLOT_ID slotID = 0;
	Slot* slot = slotManager.getSlot(slotID);

	// Initialize the token
	ByteString soPIN((unsigned char*)"1234", 4);
	ByteString userPIN((unsigned char*)"1234", 4);
	CK_UTF8CHAR label[33] = "My test token                   ";
	CPPUNIT_ASSERT(slot->initToken(soPIN, label) == CKR_OK);
	CPPUNIT_ASSERT(slot->getToken()->loginSO(soPIN) == CKR_OK);
	CPPUNIT_ASSERT(slot->getToken()->initUserPIN(userPIN) == CKR_OK);
	slot->getToken()->logout();

	// Get a session
	CK_SESSION_HANDLE hSession;
	CK_RV rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// Get session info
	CK_SESSION_INFO info;
	rv = sessionManager.getSessionInfo(CK_INVALID_HANDLE, &info);
	CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID);
	rv = sessionManager.getSessionInfo(hSession, NULL_PTR);
	CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD);
	rv = sessionManager.getSessionInfo(hSession, &info);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// Public RO session info
	CPPUNIT_ASSERT(info.slotID == slotID);
	CPPUNIT_ASSERT(info.state == CKS_RO_PUBLIC_SESSION);
	CPPUNIT_ASSERT(info.flags == CKF_SERIAL_SESSION);

	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// Public RW session info
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	Session* session = sessionManager.getSession(CK_INVALID_HANDLE);
	CPPUNIT_ASSERT(session == NULL);
	session = sessionManager.getSession(hSession);
	CPPUNIT_ASSERT(session != NULL);
	rv = session->getInfo(&info);
	CPPUNIT_ASSERT(rv == CKR_OK);
	CPPUNIT_ASSERT(info.state == CKS_RW_PUBLIC_SESSION);
	CPPUNIT_ASSERT(info.flags == (CKF_SERIAL_SESSION | CKF_RW_SESSION));

	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// User RO session info
	rv = slot->getToken()->loginUser(userPIN);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.getSessionInfo(hSession, &info);
	CPPUNIT_ASSERT(rv == CKR_OK);
	CPPUNIT_ASSERT(info.state == CKS_RO_USER_FUNCTIONS);
	CPPUNIT_ASSERT(info.flags == CKF_SERIAL_SESSION);

	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// User RW session info
	rv = slot->getToken()->loginUser(userPIN);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.getSessionInfo(hSession, &info);
	CPPUNIT_ASSERT(rv == CKR_OK);
	CPPUNIT_ASSERT(info.state == CKS_RW_USER_FUNCTIONS);
	CPPUNIT_ASSERT(info.flags == (CKF_SERIAL_SESSION | CKF_RW_SESSION));

	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// SO RW session info
	rv = slot->getToken()->loginSO(soPIN);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.getSessionInfo(hSession, &info);
	CPPUNIT_ASSERT(rv == CKR_OK);
	CPPUNIT_ASSERT(info.state == CKS_RW_SO_FUNCTIONS);
	CPPUNIT_ASSERT(info.flags == (CKF_SERIAL_SESSION | CKF_RW_SESSION));

	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
}
Example #10
0
bool ECP::DecodePoint(ECP::Point &P, const byte *encodedPoint, size_t encodedPointLen) const
{
	StringStore store(encodedPoint, encodedPointLen);
	return DecodePoint(P, store, encodedPointLen);
}
Example #11
0
 void cleanup()
 {
     Akonadi2::Storage store(Akonadi2::Store::storageLocation(), "org.kde.dummy.testindex", Akonadi2::Storage::ReadWrite);
     store.removeFromDisk();
 }
Example #12
0
 void simulateToRead()
 {
     if (_debug)
         printf("%*s% 7.2lf ", _indent*8, "", _tNextStop/(400.0*256.0));
     int pc = _pch | _memory[2];
     int op = _program->op(pc);
     incrementPC();
     UInt16 r;
     if ((op & 0x800) == 0) {
         _f = op & 0x1f;
         if ((op & 0x400) == 0) {
             bool d = ((op & 0x20) != 0);  // true if destination is f, false if destination is W
             char dc = d ? 'f' : 'W';
             switch (op >> 6) {
                 case 0x0:
                     if (!d)
                         switch (_f) {
                             case 0:
                                 if (_debug) { printf("NOP             "); printf("\n"); }
                                 _f = -1;
                                 break;
                             case 2:
                                 if (_debug) { printf("OPTION          "); printf("\n"); }
                                 _f = -1;
                                 _option = _w;
                                 break;
                             case 3:
                                 if (_debug) { printf("SLEEP           "); printf("\n"); }
                                 _f = -1;
                                 throw Exception(String("SLEEP not supported"));
                                 break;
                             case 4:
                                 if (_debug) { printf("CLRWDT          "); printf("\n"); }
                                 _f = -1;
                                 throw Exception(String("CLRWDT not supported"));
                                 break;
                             case 6:
                                 if (_debug) { printf("TRIS GPIO       "); printf("\n"); }
                                 _f = 0x20;
                                 _data = _w;
                                 break;
                             default:
                                 unrecognizedOpcode(op);
                                 break;
                         }
                     else {
                         if (_debug) { printf("MOVWF 0x%02x      ", _f); printf("\n"); }
                         _data = _w;
                     }
                     break;
                 case 0x1:
                     if (_debug) {
                         if (!d)
                             printf("CLRW            ");
                         else
                             printf("CLRF 0x%02x       ", _f);
                          printf("\n");
                     }
                     storeZ(0, d);
                     break;
                 case 0x2:
                     if (_debug) { printf("SUBWF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     {
                         UInt8 m = readMemory(_f);
                         r = m - _w;
                         if (r & 0x100)
                             _memory[3] |= 1;
                         else
                             _memory[3] &= 0xfe;
                         if ((m & 0xf) - (_w & 0xf) != (r & 0xf))
                             _memory[3] |= 2;
                         else
                             _memory[3] &= 0xfd;
                         storeZ(r, d);
                     }
                     break;
                 case 0x3:
                     if (_debug) { printf("DECF 0x%02x, %c    ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f) - 1, d);
                     break;
                 case 0x4:
                     if (_debug) { printf("IORWF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f) | _w, d);
                     break;
                 case 0x5:
                     if (_debug) { printf("ANDWF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f) & _w, d);
                     break;
                 case 0x6:
                     if (_debug) { printf("XORWF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f) ^ _w, d);
                     break;
                 case 0x7:
                     if (_debug) { printf("ADDWF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     {
                         UInt8 m = readMemory(_f);
                         r = m + _w;
                         if (r & 0x100)
                             _memory[3] |= 1;
                         else
                             _memory[3] &= 0xfe;
                         if ((_w & 0xf) + (m & 0xf) != (r & 0xf))
                             _memory[3] |= 2;
                         else
                             _memory[3] &= 0xfd;
                         storeZ(r, d);
                     }
                     break;
                 case 0x8:
                     if (_debug) { printf("MOVF 0x%02x, %c    ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f), d);
                     break;
                 case 0x9:
                     if (_debug) { printf("COMF 0x%02x, %c    ", _f, dc); printf("\n"); }
                     storeZ(~readMemory(_f), d);
                     break;
                 case 0xa:
                     if (_debug) { printf("INCF 0x%02x, %c    ", _f, dc); printf("\n"); }
                     storeZ(readMemory(_f) + 1, d);
                     break;
                 case 0xb:
                     if (_debug) { printf("DECFSZ 0x%02x, %c  ", _f, dc); printf("\n"); }
                     r = readMemory(_f) - 1;
                     store(r, d);
                     if (r == 0) {
                         incrementPC();
                         _skipping = true;
                     }
                     break;
                 case 0xc:
                     if (_debug) { printf("RRF 0x%02x, %c     ", _f, dc); printf("\n"); }
                     r = readMemory(_f) | ((_memory[3] & 1) << 8);
                     setCarry((r & 1) != 0);
                     store(r >> 1, d);
                     break;
                 case 0xd:
                     if (_debug) { printf("RLF 0x%02x, %c     ", _f, dc); printf("\n"); }
                     r = (readMemory(_f) << 1) | (_memory[3] & 1);
                     setCarry((r & 0x100) != 0);
                     store(r, d);
                     break;
                 case 0xe:
                     if (_debug) { printf("SWAPF 0x%02x, %c   ", _f, dc); printf("\n"); }
                     r = readMemory(_f);
                     store((r >> 4) | (r << 4), d);
                     break;
                 case 0xf:
                     if (_debug) { printf("INCFSF 0x%02x, %c  ", _f, dc); printf("\n"); }
                     r = readMemory(_f) + 1;
                     store(r, d);
                     if (r == 0) {
                         incrementPC();
                         _skipping = true;
                     }
                     break;
             }
         }
Example #13
0
Calibrate::~Calibrate()
{
    store();
}
Example #14
0
void CConfigAISH::store(CConfigManager &ConfMan)const
{
	store(ConfMan.GetSection(_T("AISH")));
}
Example #15
0
Tsubtitle* TsubtitleParserSubviewer::parse(Tstream &fd, int flags, REFERENCE_TIME start, REFERENCE_TIME stop)
{
    wchar_t line[this->LINE_LEN + 1];
    int a1, a2, a3, a4, b1, b2, b3, b4;
    wchar_t *p = NULL;
    int len;
    TsubtitleText current(this->format);
    TsubtitleParser::textformat.resetProps();
    while (!current.size()) {
        if (flags & this->PARSETIME) {
            if (!fd.fgets(line, this->LINE_LEN)) {
                return NULL;
            }
            int li;
            if ((len = swscanf(line, L"%d:%d:%d%[,.:]%d --> %d:%d:%d%[,.:]%d", &a1, &a2, &a3, &li, &a4, &b1, &b2, &b3, &li, &b4)) < 10) {
                continue;
            }
            current.start = this->hmsToTime(a1, a2, a3, a4 / 10);
            current.stop  = this->hmsToTime(b1, b2, b3, b4 / 10);
        }
        current.defProps.tStart = current.defProps.karaokeStart = current.start;
        current.defProps.tStop = current.stop;
        current.defProps.wrapStyle = cfg.wordWrap; // Lines breaks

        for (;;) {
            if (!fd.fgets(line, this->LINE_LEN)) {
                goto end;    //break;
            }
            len = 0;
            for (p = line; *p != '\n' && *p != '\r' && *p; p++, len++) {
                ;
            }
            if (len) {
                int j = 0, skip = 0;
                wchar_t *curptr0, *curptr = curptr0 = (wchar_t*)_alloca((len + 1) * sizeof(wchar_t));
                for (; j < len; j++) {
                    /* let's filter html tags ::atmos */
                    /*
                    if(line[j]=='>') {
                    skip=0;
                    continue;
                    }
                    if(line[j]=='<') {
                    skip=1;
                    continue;
                    }*/
                    if (skip) {
                        continue;
                    }
                    *curptr = line[j];
                    curptr++;
                }
                *curptr = '\0';
                current.add(curptr0);
            } else {
                break;
            }
        }
    }
end:
    return current.empty() ? NULL : store(current);
}
void SessionManagerTests::testOpenClose()
{
	// Create an empty object store
#ifndef _WIN32
	ObjectStore store("./testdir");
#else
	ObjectStore store(".\\testdir");
#endif

	// Create the managers
	SlotManager slotManager(&store);
	SessionManager sessionManager;

	// Get a slot
	CK_SLOT_ID slotID = 0;
	Slot* slot = slotManager.getSlot(slotID);

	// Use some bad data
	CK_SESSION_HANDLE hSession;
	CK_RV rv = sessionManager.openSession(NULL, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID);
	rv = sessionManager.openSession(slot, 0, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_SESSION_PARALLEL_NOT_SUPPORTED);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, NULL_PTR);
	CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD);

	// Try open a slot with an uninitialized token
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_TOKEN_NOT_RECOGNIZED);

	// Initialize the token
	ByteString soPIN((unsigned char*)"1234", 4);
	CK_UTF8CHAR label[33] = "My test token                   ";
	CPPUNIT_ASSERT(slot->initToken(soPIN, label) == CKR_OK);

	// Open a session
	bool haveSession = sessionManager.haveSession(slotID);
	CPPUNIT_ASSERT(haveSession == false);
	bool haveROSession = sessionManager.haveROSession(slotID);
	CPPUNIT_ASSERT(haveROSession == false);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	haveSession = sessionManager.haveSession(slotID);
	CPPUNIT_ASSERT(haveSession == true);
	haveROSession = sessionManager.haveROSession(slotID);
	CPPUNIT_ASSERT(haveROSession == true);

	// Close session
	rv = sessionManager.closeSession(CK_INVALID_HANDLE);
	CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID);
	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID);
	haveSession = sessionManager.haveSession(slotID);
	CPPUNIT_ASSERT(haveSession == false);
	haveROSession = sessionManager.haveROSession(slotID);
	CPPUNIT_ASSERT(haveROSession == false);

	// Try open a Read-Only session when in SO mode
	rv = slot->getToken()->loginSO(soPIN);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_SESSION_READ_WRITE_SO_EXISTS);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	haveSession = sessionManager.haveSession(slotID);
	CPPUNIT_ASSERT(haveSession == true);
	haveROSession = sessionManager.haveROSession(slotID);
	CPPUNIT_ASSERT(haveROSession == false);

	// Close session and check that we are logged out
	bool isLoggedIn = slot->getToken()->isSOLoggedIn();
	CPPUNIT_ASSERT(isLoggedIn == true);
	rv = sessionManager.closeSession(hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);
	isLoggedIn = slot->getToken()->isSOLoggedIn();
	CPPUNIT_ASSERT(isLoggedIn == false);
	haveSession = sessionManager.haveSession(slotID);
	CPPUNIT_ASSERT(haveSession == false);
	haveROSession = sessionManager.haveROSession(slotID);
	CPPUNIT_ASSERT(haveROSession == false);

	// Open a new logged in session
	rv = slot->getToken()->loginSO(soPIN);
	CPPUNIT_ASSERT(rv == CKR_OK);
	rv = sessionManager.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	CPPUNIT_ASSERT(rv == CKR_OK);

	// Close all sessions and check that we are logged out
	isLoggedIn = slot->getToken()->isSOLoggedIn();
	CPPUNIT_ASSERT(isLoggedIn == true);
	rv = sessionManager.closeAllSessions(NULL);
	CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID);
	rv = sessionManager.closeAllSessions(slot);
	CPPUNIT_ASSERT(rv == CKR_OK);
	isLoggedIn = slot->getToken()->isSOLoggedIn();
	CPPUNIT_ASSERT(isLoggedIn == false);
}
Example #17
0
Tsubtitle* TsubtitleParserSSA::parse(Tstream &fd, int flags, REFERENCE_TIME start, REFERENCE_TIME stop)
{
    /*
     * Sub Station Alpha v4 (and v2?) scripts have 9 commas before subtitle
     * other Sub Station Alpha scripts have only 8 commas before subtitle
     * Reading the "ScriptType:" field is not reliable since many scripts appear
     * w/o it
     *
     * http://www.scriptclub.org is a good place to find more examples
     * http://www.eswat.demon.co.uk is where the SSA specs can be found
     */
    wchar_t line0[this->LINE_LEN + 1];
    wchar_t *line = line0;
    int playResXscript = 0, playResYscript = 0;
    while (fd.fgets(line, this->LINE_LEN)) {
#if 0
        DPRINTF(L"%s", line);
#endif
        lineID++;
        if (line[0] == ';') {
            continue;
        }
        wchar_t *cr = strrchr(line, '\n');
        if (cr) {
            *cr = '\0';
        }
        cr = strrchr(line, '\r');
        if (cr) {
            *cr = '\0';
        }
        if (strnicmp(line, L"[Script Info]", 13) == 0) {
            inV4styles = 0;
            inEvents = 0;
            inInfo = 1;
        } else if (inInfo && strnicmp(line, L"PlayResX:", 8) == 0) {
            nmTextSubtitles::strToInt(line + 9, &playResXscript);
        } else if (inInfo && strnicmp(line, L"PlayResY:", 8) == 0) {
            nmTextSubtitles::strToInt(line + 9, &playResYscript);
        } else if (inInfo && strnicmp(line, L"Timer:", 6) == 0) {
            wchar_t *end;
            double t = strtod(line + 7, &end);
            if (*end == '\0' && t != 0) {
                timer = Rational(t / 100.0, _I32_MAX);
            }
        } else if (inInfo && strnicmp(line, L"WrapStyle:", 9) == 0) {
            nmTextSubtitles::strToInt(line + 10, &wrapStyle);
        } else if (inInfo && strnicmp(line, L"ScaledBorderAndShadow:", 21) == 0) {
            nmTextSubtitles::strToInt(line + 22, &scaleBorderAndShadow);
        } else if (strnicmp(line, L"[V4 Styles]", 11) == 0) {
            version = nmTextSubtitles::SSA;
            inV4styles = 2;
            inEvents = 0;
            inInfo = 0;
        } else if (strnicmp(line, L"[V4+ Styles]", 11) == 0) {
            version = nmTextSubtitles::ASS;
            inV4styles = 2;
            inEvents = 0;
            inInfo = 0;
        } else if (strnicmp(line, L"[V4++ Styles]", 11) == 0) {
            version = nmTextSubtitles::ASS2;
            inV4styles = 2;
            inEvents = 0;
            inInfo = 0;
        } else if (strnicmp(line, L"[Events]", 8) == 0) {
            inV4styles = 0;
            inEvents = 2;
            inInfo = 0;
        } else if (inV4styles == 2 && strnicmp(line, L"Format:", 7) == 0) {
            strlwr(line);
            strrmchar(line, L' ');
            typedef std::vector<Tstrpart > Tparts;
            Tparts fields;
            const wchar_t *l = line + 7;
            strtok(l, L",", fields);
            styleFormat.clear();
            for (Tparts::const_iterator f = fields.begin(); f != fields.end(); f++) {
                if (strnicmp(f->first, L"name", 4) == 0) {
                    styleFormat.push_back(&TSSAstyle::name);
                } else if (strnicmp(f->first, L"layer", 5) == 0) {
                    styleFormat.push_back(&TSSAstyle::layer);
                } else if (strnicmp(f->first, L"fontname", 8) == 0) {
                    styleFormat.push_back(&TSSAstyle::fontname);
                } else if (strnicmp(f->first, L"fontsize", 8) == 0) {
                    styleFormat.push_back(&TSSAstyle::fontsize);
                } else if (strnicmp(f->first, L"primaryColour", 13) == 0) {
                    styleFormat.push_back(&TSSAstyle::primaryColour);
                } else if (strnicmp(f->first, L"SecondaryColour", 15) == 0) {
                    styleFormat.push_back(&TSSAstyle::secondaryColour);
                } else if (strnicmp(f->first, L"TertiaryColour", 14) == 0) {
                    styleFormat.push_back(&TSSAstyle::tertiaryColour);
                } else if (strnicmp(f->first, L"OutlineColour", 13) == 0) {
                    styleFormat.push_back(&TSSAstyle::outlineColour);
                } else if (strnicmp(f->first, L"BackColour", 10) == 0) {
                    styleFormat.push_back(&TSSAstyle::backgroundColour);
                } else if (strnicmp(f->first, L"bold", 4) == 0) {
                    styleFormat.push_back(&TSSAstyle::bold);
                } else if (strnicmp(f->first, L"italic", 6) == 0) {
                    styleFormat.push_back(&TSSAstyle::italic);
                } else if (strnicmp(f->first, L"Underline", 9) == 0) {
                    styleFormat.push_back(&TSSAstyle::underline);
                } else if (strnicmp(f->first, L"Strikeout", 9) == 0) {
                    styleFormat.push_back(&TSSAstyle::strikeout);
                } else if (strnicmp(f->first, L"ScaleX", 6) == 0) {
                    styleFormat.push_back(&TSSAstyle::fontScaleX);
                } else if (strnicmp(f->first, L"ScaleY", 6) == 0) {
                    styleFormat.push_back(&TSSAstyle::fontScaleY);
                } else if (strnicmp(f->first, L"Spacing", 7) == 0) {
                    styleFormat.push_back(&TSSAstyle::spacing);
                } else if (strnicmp(f->first, L"Angle", 5) == 0) {
                    styleFormat.push_back(&TSSAstyle::angleZ);
                } else if (strnicmp(f->first, L"outline", 7) == 0) {
                    styleFormat.push_back(&TSSAstyle::outlineWidth);
                } else if (strnicmp(f->first, L"shadow", 6) == 0) {
                    styleFormat.push_back(&TSSAstyle::shadowDepth);
                } else if (strnicmp(f->first, L"alignment", 9) == 0) {
                    styleFormat.push_back(&TSSAstyle::alignment);
                } else if (strnicmp(f->first, L"encoding", 8) == 0) {
                    styleFormat.push_back(&TSSAstyle::encoding);
                } else if (strnicmp(f->first, L"marginl", 7) == 0) {
                    styleFormat.push_back(&TSSAstyle::marginLeft);
                } else if (strnicmp(f->first, L"marginr", 7) == 0) {
                    styleFormat.push_back(&TSSAstyle::marginRight);
                } else if (strnicmp(f->first, L"marginv", 7) == 0) {
                    styleFormat.push_back(&TSSAstyle::marginV);
                } else if (strnicmp(f->first, L"borderstyle", 11) == 0) {
                    styleFormat.push_back(&TSSAstyle::borderStyle);
                } else {
                    styleFormat.push_back(NULL);
                }
            }
            inV4styles = 1;
        } else if (inV4styles && strnicmp(line, L"Style:", 6) == 0) {
            if (inV4styles == 2) {
                styleFormat.clear();
                if (version == nmTextSubtitles::ASS2) {
                    styleFormat.push_back(&TSSAstyle::name);
                    styleFormat.push_back(&TSSAstyle::fontname);
                    styleFormat.push_back(&TSSAstyle::fontsize);
                    styleFormat.push_back(&TSSAstyle::primaryColour);
                    styleFormat.push_back(&TSSAstyle::secondaryColour);
                    styleFormat.push_back(&TSSAstyle::tertiaryColour);
                    styleFormat.push_back(&TSSAstyle::backgroundColour);
                    styleFormat.push_back(&TSSAstyle::bold);
                    styleFormat.push_back(&TSSAstyle::italic);
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::underline);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::strikeout);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::fontScaleX);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::fontScaleY);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::spacing);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        styleFormat.push_back(&TSSAstyle::angleZ);
                    }
                    styleFormat.push_back(&TSSAstyle::borderStyle);
                    styleFormat.push_back(&TSSAstyle::outlineWidth);
                    styleFormat.push_back(&TSSAstyle::shadowDepth);
                    styleFormat.push_back(&TSSAstyle::alignment);
                    styleFormat.push_back(&TSSAstyle::marginLeft);
                    styleFormat.push_back(&TSSAstyle::marginRight);
                    styleFormat.push_back(&TSSAstyle::marginTop);
                    if (version >= nmTextSubtitles::ASS2) {
                        styleFormat.push_back(&TSSAstyle::marginBottom);
                    }
                    styleFormat.push_back(&TSSAstyle::encoding);
                    if (version <= nmTextSubtitles::SSA) {
                        styleFormat.push_back(&TSSAstyle::alpha);
                    }
                    styleFormat.push_back(&TSSAstyle::relativeTo);
                }
                inV4styles = 1;
            }
            strings fields;
            strtok(line + 7, L",", fields);

            // Fix for missing or incomplete movie dimensions in the script
            if (playResXscript == 0 && playResYscript == 0) { // Assume 384x288 like VSFilter
                playResX = 384;
                playResY = 288;
            } else { // At least one of the two is set
                if (playResXscript == 0 || playResYscript == 0) { // Assume 4/3 aspect ratio like VSFilter, but only if one of them is missing
                    if (playResXscript == 0) {
                        playResX = playResYscript * 4 / 3;
                    } else {
                        playResX = playResXscript;
                    }
                    if (playResYscript == 0) {
                        playResY = playResXscript * 3 / 4;
                    } else {
                        playResY = playResYscript;
                    }
                } else { // Both are set, use them
                    playResX = playResXscript;
                    playResY = playResYscript;
                }
            }
            TSSAstyle style(playResX, playResY, version, wrapStyle, scaleBorderAndShadow);
            for (size_t i = 0; i < fields.size() && i < styleFormat.size(); i++)
                if (styleFormat[i]) {
                    style.*(styleFormat[i]) = fields[i];
                }
            styles.add(style);
        } else if (inEvents == 2 && strnicmp(line, L"Format:", 7) == 0) {
            strlwr(line);
            strrmchar(line, L' ');
            typedef std::vector<Tstrpart > Tparts;
            Tparts fields;
            const wchar_t *l = line + 7;
            strtok(l, L",", fields);
            eventFormat.clear();

            // On embedded streams, read order is added as first column
            if (isEmbedded) {
                eventFormat.push_back(&Tevent::readorder);
            }

            for (Tparts::const_iterator f = fields.begin(); f != fields.end(); f++) {
                if (strnicmp(f->first, L"marked", 6) == 0) {
                    eventFormat.push_back(&Tevent::marked);
                } else if (strnicmp(f->first, L"layer", 5) == 0) {
                    eventFormat.push_back(&Tevent::layer);
                } else if (strnicmp(f->first, L"start", 5) == 0) {
                    // On embedded subtitles time is removed
                    if (!isEmbedded) {
                        eventFormat.push_back(&Tevent::start);
                    }
                } else if (strnicmp(f->first, L"end", 3) == 0) {
                    // On embedded subtitles time is removed
                    if (!isEmbedded) {
                        eventFormat.push_back(&Tevent::end);
                    }
                } else if (strnicmp(f->first, L"style", 5) == 0) {
                    eventFormat.push_back(&Tevent::style);
                } else if (strnicmp(f->first, L"name", 4) == 0) {
                    eventFormat.push_back(&Tevent::name);
                } else if (strnicmp(f->first, L"marginL", 7) == 0) {
                    eventFormat.push_back(&Tevent::marginL);
                } else if (strnicmp(f->first, L"marginR", 7) == 0) {
                    eventFormat.push_back(&Tevent::marginR);
                } else if (strnicmp(f->first, L"marginV", 7) == 0) {
                    eventFormat.push_back(&Tevent::marginV);
                } else if (strnicmp(f->first, L"marginR", 7) == 0) {
                    eventFormat.push_back(&Tevent::marginR);
                } else if (strnicmp(f->first, L"effect", 6) == 0) {
                    eventFormat.push_back(&Tevent::effect);
                } else if (strnicmp(f->first, L"text", 4) == 0) {
                    eventFormat.push_back(&Tevent::text);
                } else {
                    eventFormat.push_back(NULL);
                }
            }
            inEvents = 1;
        } else if ((flags & this->SSA_NODIALOGUE) || (inEvents == 1 && strnicmp(line, L"Dialogue:", 8) == 0)) {
            if (eventFormat.empty()) {
                if (!(flags & this->SSA_NODIALOGUE)) {
                    if (version <= nmTextSubtitles::SSA) {
                        eventFormat.push_back(&Tevent::marked);
                    }
                    if (version >= nmTextSubtitles::ASS) {
                        eventFormat.push_back(&Tevent::layer);
                    }
                    eventFormat.push_back(&Tevent::start);
                    eventFormat.push_back(&Tevent::end);
                } else {
                    eventFormat.push_back(&Tevent::readorder);
                    eventFormat.push_back(&Tevent::layer);
                }
                eventFormat.push_back(&Tevent::style);
                eventFormat.push_back(&Tevent::actor);
                eventFormat.push_back(&Tevent::marginL);
                eventFormat.push_back(&Tevent::marginR);
                eventFormat.push_back(&Tevent::marginT);
                if (version >= nmTextSubtitles::ASS2) {
                    eventFormat.push_back(&Tevent::marginB);
                }
                eventFormat.push_back(&Tevent::effect);
                eventFormat.push_back(&Tevent::text);
            }
            strings fields;
            strtok(line + (flags & this->SSA_NODIALOGUE ? 0 : 9), L"," , fields, true, eventFormat.size());
            Tevent event;
            event.dummy = ""; // avoid being optimized.
            for (size_t i = 0; i < fields.size() && i < eventFormat.size(); i++) {
                if (eventFormat[i]) {
                    event.*(eventFormat[i]) = fields[i];
                }
            }
            if (event.text) {
#if 0
                DPRINTF(L"%s", event.text.c_str());
#endif
                int hour1 = 0, min1 = 0, sec1 = 0, hunsec1 = 0;
                int hour2 = 0, min2 = 0, sec2 = 0, hunsec2 = 0;
                if (!(flags & this->PARSETIME) ||
                        (swscanf(event.start.c_str(), L"%d:%d:%d.%d", &hour1, &min1, &sec1, &hunsec1) == 4 &&
                         swscanf(event.end.c_str()  , L"%d:%d:%d.%d", &hour2, &min2, &sec2, &hunsec2) == 4)) {
                    const TSubtitleProps *props = styles.getProps(event.style);
                    TsubtitleText current(this->format, props ? *props : defprops, styles);
                    current.defProps.lineID = lineID;

                    // margins
                    nmTextSubtitles::strToIntMargin(event.marginL, &current.defProps.marginL);
                    nmTextSubtitles::strToIntMargin(event.marginR, &current.defProps.marginR);
                    nmTextSubtitles::strToIntMargin(event.marginV, &current.defProps.marginV);

                    // layer
                    nmTextSubtitles::strToInt(event.layer, &current.defProps.layer);

                    // timestamps
                    if (flags & this->PARSETIME) {
                        current.start = timer.den * this->hmsToTime(hour1, min1, sec1, hunsec1) / timer.num;
                        current.stop = timer.den * this->hmsToTime(hour2, min2, sec2, hunsec2) / timer.num;
                    } else if (start != REFTIME_INVALID && stop != REFTIME_INVALID) {
                        current.start = start;
                        current.stop = stop;
                    }
                    current.defProps.tStart = current.defProps.karaokeStart = current.start;
                    current.defProps.tStop = current.stop;

                    // scroll
                    event.effect = event.effect.ConvertToLowerCase();
                    if (event.effect.find(L"scroll up;") != ffstring::npos) {
                        current.defProps.scroll.directionV = -1;
                    }
                    if (event.effect.find(L"scroll down;") != ffstring::npos) {
                        current.defProps.scroll.directionV = 1;
                    }
                    if (current.defProps.scroll.directionV) {
                        int y1, y2, delay, fadeawayheight = 0;
                        if (swscanf(event.effect.c_str() + event.effect.find(L";"),
                                    L";%d;%d;%d;%d", &y1, &y2, &delay, &fadeawayheight) >= 3) {
                            if (y1 > y2) {
                                std::swap(y1, y2);
                            }
                            current.defProps.scroll.y1 = y1;
                            current.defProps.scroll.y2 = y2;
                            current.defProps.scroll.delay = std::max(delay, 1);
                            current.defProps.scroll.fadeaway = fadeawayheight;
                        }
                    }

                    if (event.effect.find(L"banner;") != ffstring::npos) {
                        current.defProps.scroll.directionV = 0;
                        current.defProps.scroll.directionH = -1;
                        int delay, lefttoright = 0, fadeawaywidth = 0;
                        if (swscanf(event.effect.c_str() + event.effect.find(L";"),
                                    L";%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) >= 1) {
                            current.defProps.scroll.delay = std::max(delay, 1);
                            current.defProps.scroll.directionH = lefttoright ? 1 : -1;
                            current.defProps.scroll.fadeaway = fadeawaywidth;
                        }
                    }

                    // replace \h with non-breaking space (U+00A0).
                    event.text = stringreplace(event.text, L"\\h", L"\xa0", rfReplaceAll);

                    const wchar_t *line2 = event.text.c_str();
                    do {
                        const wchar_t *tmp, *tmp1;
                        int lineBreakReason = 0;
                        do {
                            tmp = strstr(line2, L"\\n");
                            tmp1 = strstr(line2, L"\\N");
                            if (tmp == NULL && tmp1 == NULL) {
                                break;
                            }
                            if (tmp && tmp1) {
                                tmp = std::min(tmp, tmp1);
                            }
                            if (tmp == NULL) {
                                tmp = tmp1;
                            }
                            current.addSSA(line2, tmp - line2, lineBreakReason);
                            lineBreakReason = tmp[1] == 'n' ? 1 : 2;
                            line2 = tmp + 2;
                        } while (1);
                        current.addSSA(line2, lineBreakReason);
                    } while (flags & this->SSA_NODIALOGUE && fd.fgets((wchar_t*)(line2 = line), this->LINE_LEN));
                    textformat.setProps(current.defProps);
                    return store(current);
                }
            }
        }
    }
    return NULL;
}
  void display()
  {
    std::vector<cv::Point2f> pointsColor, pointsIr;
    cv::Mat color, ir, irGrey, depth;
    cv::Mat colorDisp, irDisp;
    bool foundColor = false;
    bool foundIr = false;
    bool save = false;
    bool running = true;

    std::chrono::milliseconds duration(1);
    while(!update && ros::ok())
    {
      std::this_thread::sleep_for(duration);
    }

    for(; ros::ok() && running;)
    {
      if(update)
      {
        lock.lock();
        color = this->color;
        ir = this->ir;
        irGrey = this->irGrey;
        depth = this->depth;
        foundColor = this->foundColor;
        foundIr = this->foundIr;
        pointsColor = this->pointsColor;
        pointsIr = this->pointsIr;
        update = false;
        lock.unlock();

        if(mode == COLOR || mode == SYNC)
        {
          cv::cvtColor(color, colorDisp, CV_GRAY2BGR);
          cv::drawChessboardCorners(colorDisp, boardDims, pointsColor, foundColor);
          //cv::resize(colorDisp, colorDisp, cv::Size(), 0.5, 0.5);
          //cv::flip(colorDisp, colorDisp, 1);
        }
        if(mode == IR || mode == SYNC)
        {
          cv::cvtColor(irGrey, irDisp, CV_GRAY2BGR);
          cv::drawChessboardCorners(irDisp, boardDims, pointsIr, foundIr);
          //cv::resize(irDisp, irDisp, cv::Size(), 0.5, 0.5);
          //cv::flip(irDisp, irDisp, 1);
        }
      }

      switch(mode)
      {
      case COLOR:
        cv::imshow("color", colorDisp);
        break;
      case IR:
        cv::imshow("ir", irDisp);
        break;
      case SYNC:
        cv::imshow("color", colorDisp);
        cv::imshow("ir", irDisp);
        break;
      }

      int key = cv::waitKey(10);
      switch(key & 0xFF)
      {
      case ' ':
      case 's':
        save = true;
        break;
      case 27:
      case 'q':
        running = false;
        break;
      case '1':
        minIr = std::max(0, minIr - 100);
        break;
      case '2':
        minIr = std::min(maxIr - 1, minIr + 100);
        break;
      case '3':
        maxIr = std::max(minIr + 1, maxIr - 100);
        break;
      case '4':
        maxIr = std::min(0xFFFF, maxIr + 100);
        break;
      case 'l':
        minIr = std::max(0, minIr - 100);
        maxIr = std::max(minIr + 1, maxIr - 100);
        break;
      case 'h':
        maxIr = std::min(0x7FFF, maxIr + 100);
        minIr = std::min(maxIr - 1, minIr + 100);
        break;
      }

      if(save && ((mode == COLOR && foundColor) || (mode == IR && foundIr) || (mode == SYNC && foundColor && foundIr)))
      {
        store(color, ir, irGrey, depth, pointsColor, pointsIr);
        save = false;
      }
    }
    cv::destroyAllWindows();
    cv::waitKey(100);
  }
Example #19
0
//! Grows the hash table.
void
dmz::HashTableUInt32::grow (const Int32 Size) {

   Int32 newSize (0);

   if (_state.autoGrow) {

      if (!Size) {

         if (!_state.size) { newSize = 1; }
         else { newSize = _state.size; newSize = newSize << 1; }
      }
      else {

         if (Size > _state.size) {

            newSize = _state.size;
            if (!newSize) { newSize = 1; }
            while ((newSize < Size) && (newSize <= 0x80000000)) {

               newSize = newSize << 1;
            }
         }
      }
   }

   if (newSize) {

      _state.growCount++;

      const Int32 OldSize (_state.size);
      const Int32 OldCount (_state.count);
      DataStruct *table (_state.table);

      _state.size = 0;
      _state.count = 0;
      _state.table = new DataStruct[newSize];

      if (table && _state.table) {

         _state.size = newSize;

         DataStruct *cur (_state.head);
         _state.tail = _state.head = 0;

         while (cur) {

            store (cur->key, cur->data);
            cur = cur->next;
         }

         delete []table; table = 0;
      }
      else if (_state.table) { _state.size = newSize; }
      else if (table) {

         _state.table = table;
         _state.size = OldSize;
         _state.count = OldCount;
      }
   }
}
Example #20
0
void scoped_weapon_info::activate()
{
	if (data_) {
		store(data_);
	}
}
Example #21
0
//词法分析主分析函数 
Result analyse(long * readIndexPtr,char buf[],long length,FILE * outFile,int line){
	printf("readindex: %ld\n",*readIndexPtr);
	int status = 0;
	char token[16] = "";
	char ch;
	for (;(*readIndexPtr) < length;){ 
		
		ch = buf[(*readIndexPtr)++];
		
		//printf("current char: %ld\n",*readIndexPtr);
		if (ch == EOF) {
			store(token,25,outFile);
			return (Result){25,0};
		} 
		//空格
		else if (ch == 32 && status == 0) {
			status = 0;
		}
		//字母
		else if (isLetter(ch)) {
			if (status == 0 || status == 1) {
				linkChar(token,ch);
				status = 1;
				continue; 
			}
			else if (status == 3) {
				status = 4;
				(*readIndexPtr) --;
				//常数 
				store(token,11,outFile);
				return (Result){11,0};
			}
		}
		//数字
		else if (isNumber(ch)) {
			if (status == 1) {
				linkChar(token,ch);
				status = 1;
			}
			else if (status == 0 ||status == 3) {
				linkChar(token,ch);
				status = 3;
			}
		} 
		//非字母/数字 
		else {
			
			if (status == 1) {
				status = 2;
				(*readIndexPtr) --;
				//标示符/保留字的处理
				return identifier(token,outFile); 
				
			} else if (status == 3) {
				status = 4;
				(*readIndexPtr) --;
				//常数 
				store(token,11,outFile);
				return (Result){11,0};
			} else 
			switch (ch) {
				case '=':
					linkChar(token,ch);
					status = 5;
					store(token,12,outFile);
					return (Result){12,0};
					break;
				case '-':
					linkChar(token,ch);
					status = 6;
					store(token,18,outFile);
					return (Result){18,0};
					break;
				case '*':
					linkChar(token,ch);
					status = 7;
					store(token,19,outFile);
					return (Result){19,0};
					break;
				case '(':
					linkChar(token,ch);
					status = 8;
					store(token,21,outFile);
					return (Result){21,0};
					break;
				case ')':
					linkChar(token,ch);
					status = 9;
					store(token,22,outFile);
					return (Result){22,0};
					break;
				case '<':
					linkChar(token,ch);
					status = 10;
					if ((*readIndexPtr) < length) {
						ch = buf[(*readIndexPtr)++];
						switch (ch) {
							case '=':
								linkChar(token,ch);
								status = 11;
								store(token,14,outFile);
								return (Result){14,0};
								break;
							case '>':
								linkChar(token,ch);
								status = 12;
								store(token,13,outFile);
								return (Result){13,0};
								break;
							default:
								status = 13;
								(*readIndexPtr) --;
								store(token,15,outFile);
								return (Result){15,0};
								break;
						}
					}
					
					break;
				case '>':
					linkChar(token,ch);
					status = 14;
					if ((*readIndexPtr) < length) {
						ch = buf[(*readIndexPtr)++];
						switch (ch) {
							case '=':
								linkChar(token,ch);
								status = 15;
								store(token,16,outFile);
								return (Result){16,0};
								break;
							default:
								status = 16;
								(*readIndexPtr) --;
								store(token,17,outFile);
								return (Result){17,0};
								break;
							}
						}
					break;
				case ':':
					linkChar(token,ch);
					status = 17;
					if ((*readIndexPtr) < length) {
						ch = buf[(*readIndexPtr)++];
						switch (ch) {
							case '=':
								linkChar(token,ch);
								status = 18;
								store(token,20,outFile);
								return (Result){20,0};
								break;
							default:
								status = 19;
								(*readIndexPtr) --;
								errorRecord(line);//-----------------error operation
								printf("error: unexpected letter \"%c\"\n",ch);
								return (Result){0,0}; 
								break;
							}
						}
					break;
				case ';':
					linkChar(token,ch);
					status = 20;
					store(token,23,outFile); 
					return (Result){23,0};
					break;
					//回车 
				case '\r':
					ch = buf[(*readIndexPtr)++];
					if(ch == '\n') {
						store(token,24,outFile);
						if((*readIndexPtr) == length) {
							store(token,25,outFile);
						}
						
						return (Result){24,0};
					} else {
						errorRecord(line);//-----------------error operation
						printf("error: expect LF ,but no LF\n");
						return (Result){0,0};
					}
					break;
				default:
					printf("wrong character:\"%c\",ascii code is %d\n",ch,ch);
					status = 21;
					(*readIndexPtr) --;
					if (*readIndexPtr < 0) {
						printf("error! status 21,readIndex < 0\n");
						
					}
					errorRecord(line);//-----------------error operation
					return (Result){0,0};
					break;
			}
		}
		
	}
	//store(token,25,outFile);//EOF
}
Example #22
0
SEXP as_output_dataframe(SEXP sWhat, SEXP sSep, SEXP sNsep, SEXP sRownamesFlag, SEXP sConn, SEXP sRecycle) {
    unsigned long i, j;
    if (TYPEOF(sWhat) != VECSXP)
	Rf_error("object must be a data.frame");
    unsigned long ncol = XLENGTH(sWhat);
    unsigned long nrow = 0;
    unsigned long row_len = 0;
    if (ncol)
	nrow = XLENGTH(VECTOR_ELT(sWhat, 0));
    int rownamesFlag = asInteger(sRownamesFlag);
    if (TYPEOF(sSep) != STRSXP || LENGTH(sSep) != 1)
	Rf_error("sep must be a single string");
    if (TYPEOF(sNsep) != STRSXP || LENGTH(sNsep) != 1)
	Rf_error("nsep must be a single string");
    char sep = CHAR(STRING_ELT(sSep, 0))[0];
    char nsep = CHAR(STRING_ELT(sNsep, 0))[0];
    char lend = '\n';
    SEXP sRnames = getAttrib0(sWhat, R_RowNamesSymbol);
    int isConn = inherits(sConn, "connection"), mod = 0;
    int recycle = (asInteger(sRecycle) > 0) ? 1 : 0;
    SEXP as_character = R_NilValue;
    unsigned long *sizes = 0;
    if (TYPEOF(sRnames) != STRSXP) sRnames = NULL;
    for (j = 0; j < ncol; j++) {
	/* we have to call as.character() for objects with a class
	   since they may require a different representation */
	if (requires_as_character(VECTOR_ELT(sWhat, j))) {
	    /* did we create a modified copy yet? If not, do so */
	    if (!mod) {
		/* shallow copy - we use it only internally so should be ok */
		SEXP sData = PROTECT(allocVector(VECSXP, XLENGTH(sWhat)));
		memcpy(&(VECTOR_ELT(sData, 0)), &(VECTOR_ELT(sWhat, 0)),
		       sizeof(SEXP) * XLENGTH(sWhat));
		sWhat = sData;
		mod = 1;
		as_character = Rf_install("as.character");
	    }
	    SEXP asc = PROTECT(lang2(as_character, VECTOR_ELT(sWhat, j)));
	    SET_VECTOR_ELT(sWhat, j, eval(asc, R_GlobalEnv));
	    UNPROTECT(1);
	}
	row_len += guess_size(TYPEOF(VECTOR_ELT(sWhat, j)));
    }

    if (ncol && recycle) { /* this allows us to support lists directly without requiring for
			      them to be a data frames - in those cases we have to check the length
			      of the columns to determine the longest */
	unsigned long min_len = (unsigned long) XLENGTH(VECTOR_ELT(sWhat, 0));
	for (j = 0; j < ncol; j++) {
	    unsigned long l = 0;
	    SEXP el = VECTOR_ELT(sWhat, j);
	    /* NOTE: we can assume that el must be a scalar vector since anything that isn't
	       will be passed through as.character() */
	    l = (unsigned long) XLENGTH(el);
	    if (l < min_len) min_len = l;
	    if (l > nrow) nrow = l;
	}
	/* if all elements have the smae tlength then we don't need to re-cycle, so treat
	   the list exactly like a data frame */
	if (nrow == min_len)
	    recycle = 0;
	else { /* cache lengths since XLENGTH is actually not a cheap operation */
	    SEXP foo = PROTECT(allocVector(RAWSXP, sizeof(long) * ncol));
	    sizes = (unsigned long*) RAW(foo);
	    for (j = 0; j < ncol; j++)
		sizes[j] = (unsigned long) XLENGTH(VECTOR_ELT(sWhat, j));
	}
    }

    if (rownamesFlag == 1) row_len++;

    SEXP buf = dybuf_alloc(isConn ? DEFAULT_CONN_BUFFER_SIZE : (row_len * nrow), sConn);

    for (i = 0; i < nrow; i++) {
	if (rownamesFlag) {
	    if (sRnames) {
		const char *c = CHAR(STRING_ELT(sRnames, i));
		dybuf_add(buf, c, strlen(c));
	    } else {
		/* FIXME: use sprintf("%d", i) for automatic row names? */
	    }
	    dybuf_add1(buf, nsep);
	}

	if (recycle) /* slower - we need to use modulo to recycle */
	    /* FIXME: modulo is slow for large vectors, should we just keep
	       separate index for every column? It may be worth measuring
	       the impact ... We are already trying to be smart by avoiding modulo
	       for the two most common cases: full-length vectors and vectors of length 1
	       so this will only impact non-trivial recycling */
	    for (j = 0; j < ncol; j++) {
		store(buf, VECTOR_ELT(sWhat, j), (i < sizes[j]) ? i : ((sizes[j] == 1) ? 0 : (i % sizes[j])));
		if (j < ncol - 1)
		    dybuf_add1(buf, (rownamesFlag == 2 && j == 0) ? nsep : sep);
	    }
	else
	    for (j = 0; j < ncol; j++) {
		store(buf, VECTOR_ELT(sWhat, j), i);
		if (j < ncol - 1)
		    dybuf_add1(buf, (rownamesFlag == 2 && j == 0) ? nsep : sep);
	    }
	dybuf_add1(buf, lend);
    }

    if (recycle) UNPROTECT(1); /* sizes cache */
    if (mod) UNPROTECT(1); /* sData */
    SEXP res = dybuf_collect(buf);
    UNPROTECT(1); /* buffer */
    return res;
}
Example #23
0
 int64_t increment_and_get( uint64_t inc ) 
 { 
     auto tmp = aquire() + inc;
     store( tmp );
     return tmp;
 }
Example #24
0
/*
 * This will consume+delete updates from the passed nsTArray.
*/
nsresult
Classifier::ApplyTableUpdates(nsTArray<TableUpdate*>* aUpdates,
                              const nsACString& aTable)
{
  LOG(("Classifier::ApplyTableUpdates(%s)",
       PromiseFlatCString(aTable).get()));

  nsAutoPtr<HashStore> store(new HashStore(aTable, mStoreDirectory));

  if (!store)
    return NS_ERROR_FAILURE;

  // take the quick exit if there is no valid update for us
  // (common case)
  uint32 validupdates = 0;

  for (uint32 i = 0; i < aUpdates->Length(); i++) {
    TableUpdate *update = aUpdates->ElementAt(i);
    if (!update || !update->TableName().Equals(store->TableName()))
      continue;
    if (update->Empty()) {
      aUpdates->ElementAt(i) = nullptr;
      delete update;
      continue;
    }
    validupdates++;
  }

  if (!validupdates) {
    return NS_OK;
  }

  nsresult rv = store->Open();
  NS_ENSURE_SUCCESS(rv, rv);
  rv = store->BeginUpdate();
  NS_ENSURE_SUCCESS(rv, rv);

  // Read the part of the store that is (only) in the cache
  LookupCache *prefixSet = GetLookupCache(store->TableName());
  if (!prefixSet) {
    return NS_ERROR_FAILURE;
  }
  nsTArray<PRUint32> AddPrefixHashes;
  rv = prefixSet->GetPrefixes(&AddPrefixHashes);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = store->AugmentAdds(AddPrefixHashes);
  NS_ENSURE_SUCCESS(rv, rv);
  AddPrefixHashes.Clear();

  uint32 applied = 0;
  bool updateFreshness = false;

  for (uint32 i = 0; i < aUpdates->Length(); i++) {
    TableUpdate *update = aUpdates->ElementAt(i);
    if (!update || !update->TableName().Equals(store->TableName()))
      continue;

    rv = store->ApplyUpdate(*update);
    NS_ENSURE_SUCCESS(rv, rv);

    applied++;

    LOG(("Applied update to table %s:", store->TableName().get()));
    LOG(("  %d add chunks", update->AddChunks().Length()));
    LOG(("  %d add prefixes", update->AddPrefixes().Length()));
    LOG(("  %d add completions", update->AddCompletes().Length()));
    LOG(("  %d sub chunks", update->SubChunks().Length()));
    LOG(("  %d sub prefixes", update->SubPrefixes().Length()));
    LOG(("  %d sub completions", update->SubCompletes().Length()));
    LOG(("  %d add expirations", update->AddExpirations().Length()));
    LOG(("  %d sub expirations", update->SubExpirations().Length()));

    if (!update->IsLocalUpdate()) {
      updateFreshness = true;
      LOG(("Remote update, updating freshness"));
    }

    aUpdates->ElementAt(i) = nullptr;
    delete update;
  }

  LOG(("Applied %d update(s) to %s.", applied, store->TableName().get()));

  rv = store->Rebuild();
  NS_ENSURE_SUCCESS(rv, rv);

  LOG(("Table %s now has:", store->TableName().get()));
  LOG(("  %d add chunks", store->AddChunks().Length()));
  LOG(("  %d add prefixes", store->AddPrefixes().Length()));
  LOG(("  %d add completions", store->AddCompletes().Length()));
  LOG(("  %d sub chunks", store->SubChunks().Length()));
  LOG(("  %d sub prefixes", store->SubPrefixes().Length()));
  LOG(("  %d sub completions", store->SubCompletes().Length()));

  rv = store->WriteFile();
  NS_ENSURE_SUCCESS(rv, rv);

  // At this point the store is updated and written out to disk, but
  // the data is still in memory.  Build our quick-lookup table here.
  rv = prefixSet->Build(store->AddPrefixes(), store->AddCompletes());
  NS_ENSURE_SUCCESS(rv, rv);
#if defined(DEBUG) && defined(PR_LOGGING)
  prefixSet->Dump();
#endif
  rv = prefixSet->WriteFile();
  NS_ENSURE_SUCCESS(rv, rv);

  // This will drop all the temporary storage used during the update.
  rv = store->FinishUpdate();
  NS_ENSURE_SUCCESS(rv, rv);

  if (updateFreshness) {
    PRInt64 now = (PR_Now() / PR_USEC_PER_SEC);
    LOG(("Successfully updated %s", store->TableName().get()));
    mTableFreshness.Put(store->TableName(), now);
  }

  return NS_OK;
}
Example #25
0
void SchedulerCPU::LaunchTasks(const FrameContextEx& context, std::function<jobs::Future<std::any>(const FrameContextEx&, const Pipeline&, lemon::ListDigraph::Node, std::any)> onNode) {
	struct DependencyCounter {
	public:
		explicit DependencyCounter(size_t total = 0) {
			this->total = total;
		}
		void Reset() {
			*counter = 0;
		}
		bool operator++() {
			return (counter->fetch_add(1) + 1) == total;
		}

	private:
		std::shared_ptr<std::atomic_size_t> counter = std::make_shared<std::atomic_size_t>(0);
		std::size_t total = 0;
	};

	lemon::ListDigraph::NodeMap<DependencyCounter> depCounter(m_pipeline->GetTaskGraph());
	for (lemon::ListDigraph::NodeIt nodeIt(m_pipeline->GetTaskGraph()); nodeIt != lemon::INVALID; ++nodeIt) {
		depCounter[nodeIt] = DependencyCounter{ (size_t)lemon::countInArcs(m_pipeline->GetTaskGraph(), nodeIt) };
	}

	auto stopFlag = std::make_shared<std::atomic_bool>(false);
	auto Traverse = [this, &context, stopFlag, &onNode, &depCounter](lemon::ListDigraph::Node node, std::any passThrough, auto self) -> jobs::Future<void> {
		if (stopFlag->load()) {
			co_return;
		}

		try {
			std::any passToNext = co_await onNode(context, *m_pipeline, node, passThrough);

			std::vector<jobs::Future<void>> childJobs;
			for (lemon::ListDigraph::OutArcIt outArc(m_pipeline->GetTaskGraph(), node); outArc != lemon::INVALID; ++outArc) {
				auto nextNode = m_pipeline->GetTaskGraph().target(outArc);

				if (++depCounter[nextNode]) {
					childJobs.push_back(m_scheduler->Enqueue(self, nextNode, passToNext, self));
				}
			}

			for (auto& childFuture : childJobs) {
				co_await childFuture;
			}
		}
		catch (...) {
			stopFlag->store(true);
			throw;
		}
	};

	auto sourceNodes = GetSourceNodes(m_pipeline->GetTaskGraph());
	std::vector<jobs::Future<void>> childJobs;
	for (auto sourceNode : sourceNodes) {
		childJobs.push_back(m_scheduler->Enqueue(Traverse, sourceNode, std::any{}, Traverse));
	}

	std::vector<std::exception_ptr> exceptions;
	for (auto& job : childJobs) {
		try {
			job.get();
		}
		catch (...) {
			exceptions.push_back(std::current_exception());
		}
	}
	if (!exceptions.empty()) {
		// Rest of the exceptions is ignored.
		// TODO: throw some aggregate exception?
		std::rethrow_exception(exceptions[0]);
	}
}
Example #26
0
int
main(int argc, char **argv)
{
    krb5_context ctx;
    krb5_error_code retval;
    const char *progname;

    retval = krb5_init_context(&ctx);
    if (retval) {
        fprintf(stderr, "krb5_init_context returned error %ld\n",
                (long) retval);
        exit(1);
    }
    progname = argv[0];

    /* Parse arguments. */
    argc--; argv++;
    while (argc) {
        if (strcmp(*argv, "dump") == 0) {
            /*
             * Without going through the rcache interface, dump a
             * named dfl-format rcache file to stdout.  Takes a full
             * pathname argument.
             */
            const char *filename;

            argc--; argv++;
            if (!argc) usage(progname);
            filename = *argv;
            dump_rcache(filename);
        } else if (strcmp(*argv, "store") == 0) {
            /*
             * Using the rcache interface, store a replay record.
             * Takes an rcache spec like dfl:host as the first
             * argument.  If non-empty, the "msg" argument will be
             * hashed and provided in the replay record.  The
             * now-timestamp argument can be 0 to use the current
             * time.
             */
            char *rcspec, *client, *server, *msg;
            krb5_timestamp timestamp, now_timestamp;
            krb5_int32 usec, now_usec;

            argc--; argv++;
            if (!argc) usage(progname);
            rcspec = *argv;
            argc--; argv++;
            if (!argc) usage(progname);
            client = *argv;
            argc--; argv++;
            if (!argc) usage(progname);
            server = *argv;
            argc--; argv++;
            if (!argc) usage(progname);
            msg = (**argv) ? *argv : NULL;
            argc--; argv++;
            if (!argc) usage(progname);
            timestamp = (krb5_timestamp) atoll(*argv);
            argc--; argv++;
            if (!argc) usage(progname);
            usec = (krb5_int32) atol(*argv);
            argc--; argv++;
            if (!argc) usage(progname);
            now_timestamp = (krb5_timestamp) atoll(*argv);
            argc--; argv++;
            if (!argc) usage(progname);
            now_usec = (krb5_int32) atol(*argv);

            store(ctx, rcspec, client, server, msg, timestamp, usec,
                  now_timestamp, now_usec);
        } else if (strcmp(*argv, "expunge") == 0) {
            /*
             * Using the rcache interface, expunge a replay cache.
             * The now-timestamp argument can be 0 to use the current
             * time.
             */
            char *rcspec;
            krb5_timestamp now_timestamp;
            krb5_int32 now_usec;

            argc--; argv++;
            if (!argc) usage(progname);
            rcspec = *argv;
            argc--; argv++;
            if (!argc) usage(progname);
            now_timestamp = (krb5_timestamp) atoll(*argv);
            argc--; argv++;
            if (!argc) usage(progname);
            now_usec = (krb5_int32) atol(*argv);
            expunge(ctx, rcspec, now_timestamp, now_usec);
        } else
            usage(progname);
        argc--; argv++;
    }

    krb5_free_context(ctx);

    return 0;
}
void Configuration::store()
{
    if (this->filename.size() > 0) {
        store(this->filename);
    }
}
Example #28
0
int main (int argc, char **argv)
try {
  // Process the command line arguments
  std::string descString(argv[0]);
  descString += " option [options]\n\n";
  descString += "Prints descriptions of the allowed/required parameters used to\n";
  descString += "configure plugins. Output is ordered by plugin name. Within a\n";
  descString += "plugin, the labels and parameters are ordered based on the order\n";
  descString += "declared by the plugin. Formatted as follows:\n\n";
  descString += "PluginName (PluginType) Library\n";
  descString += "  ModuleLabel\n";
  descString += "    Details of parameters corresponding to this module label\n\n";
  descString += "For more information about the output format see:\n";
  descString += "https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideConfigurationValidationAndHelp\n\n";

  descString += "At least one of the following options must be used: -p, -l, -a, -q, or -t\n\n";
  descString += "Allowed options:";
  boost::program_options::options_description desc(descString);   
  desc.add_options()
                  (kHelpCommandOpt, "produce help message")
                  (kPluginCommandOpt,
                   boost::program_options::value<std::string>(),
                   "only print descriptions for this plugin")
                  (kLibraryCommandOpt,
                   boost::program_options::value<std::string>(),
                   "only print descriptions for plugins in this library")
                  (kAllLibrariesCommandOpt,
                   "allows the program to run without selecting a plugin or library. "
                   "This will take a significant amount of time.")
                  (kModuleLabelCommandOpt,
                   boost::program_options::value<std::string>(),
                   "only print descriptions for this module label")
                  (kBriefCommandOpt,
                   "do not print comments, more compact format, suppress text"
                   " added to help the user understand what the output means")
                  (kPrintOnlyLabelsCommandOpt,
                   "do not print parameter descriptions, just list module labels matching selection criteria")
                  (kPrintOnlyPluginsCommandOpt,
                   "do not print parameter descriptions or module labels, just list plugins matching selection criteria")
                  (kLineWidthCommandOpt,
                   boost::program_options::value<unsigned>(),
                   "try to limit lines to this length by inserting newlines between words in comments. Long words or names can cause the line length to exceed this limit. Defaults to terminal screen width or 80")
                  (kTopLevelCommandOpt, boost::program_options::value<std::string>(),
                   "print only the description for the top level parameter set with this name. Allowed names are 'options', 'maxEvents', 'maxLuminosityBlocks', and 'maxSecondsUntilRampdown'.");

  boost::program_options::variables_map vm;
  try {
    store(boost::program_options::command_line_parser(argc,argv).options(desc).run(),vm);
    notify(vm);
  } catch(boost::program_options::error const& iException) {
    std::cerr << "Exception from command line processing: "
              << iException.what() << "\n";
    std::cerr << desc << std::endl;
    return 1;
  }     

  if(vm.count(kHelpOpt)) {
    std::cout << desc << std::endl;
    return 0;
  }

  std::string plugin;
  std::string library;
  std::string moduleLabel;
  bool brief = false;
  bool printOnlyLabels = false;
  bool printOnlyPlugins = false;
  std::string printOnlyTopLevel;

  if (vm.count(kPluginOpt)) {
    plugin = vm[kPluginOpt].as<std::string>();
  }
  if (vm.count(kLibraryOpt)) {
    library = vm[kLibraryOpt].as<std::string>();
  }
  if (!vm.count(kAllLibrariesOpt)) {
    if (!vm.count(kPluginOpt) &&
        !vm.count(kLibraryOpt) &&
        !vm.count(kPrintOnlyPluginsOpt) &&
        !vm.count(kTopLevelOpt)) {
      std::cerr << "\nERROR: At least one of the following options must be used: -p, -l, -a, -q, or -t\n\n";
      std::cerr << desc << std::endl;
      return 1;
    }
  }
  if (vm.count(kModuleLabelOpt)) {
    moduleLabel = vm[kModuleLabelOpt].as<std::string>();
  }
  if (vm.count(kBriefOpt)) {
    brief = true;
  }
  if (vm.count(kPrintOnlyLabelsOpt)) {
    printOnlyLabels = true;
  }
  if (vm.count(kPrintOnlyPluginsOpt)) {
    printOnlyPlugins = true;
  }

  unsigned lineWidth = 80U;

  // This next little bit of code was sent to me.  It gets the number
  // of characters per line that show up on the display terminal in
  // use.  It is not standard C++ code and I do not understand sys/ioctl.h
  // very well.  From what I got via google, it should work on any UNIX platform,
  // which as far as I know is all we need to support.  If this code causes
  // problems, then deleting it and just having the default be 80 should
  // work fine.  Or someone could add the appropriate #ifdef for the
  // OS/platform/compiler where this fails.

  if (isatty(2)) {
#ifdef TIOCGWINSZ
    {
      struct winsize w;
      if (ioctl(2, TIOCGWINSZ, &w) == 0)
      {
        if (w.ws_col > 0)
        lineWidth = w.ws_col;
      }
    }
#else
#ifdef WIOCGETD
    {
      struct uwdata w;
      if (ioctl(2, WIOCGETD, &w) == 0)
      {
        if (w.uw_width > 0)
        lineWidth = w.uw_width / w.uw_hs;
      }
    }
#endif
#endif
  }

  if (vm.count(kLineWidthOpt)) {
    lineWidth = vm[kLineWidthOpt].as<unsigned>();
  }

  if (vm.count(kTopLevelOpt)) {
    printOnlyTopLevel = vm[kTopLevelOpt].as<std::string>();
    printTopLevelParameterSets(brief, lineWidth, printOnlyTopLevel);
    return 0;
  }

  // Get the list of plugins from the plugin cache

  edm::ParameterSetDescriptionFillerPluginFactory* factory;
  std::vector<edmplugin::PluginInfo> infos;

  try {

    edmplugin::PluginManager::configure(edmplugin::standard::config());
    typedef edmplugin::PluginManager::CategoryToInfos CatToInfos;
    CatToInfos const& catToInfos = edmplugin::PluginManager::get()->categoryToInfos();
    factory = edm::ParameterSetDescriptionFillerPluginFactory::get();

    CatToInfos::const_iterator itPlugins = catToInfos.find(factory->category());
    if(itPlugins == catToInfos.end() ) {
      return 0;
    }
    infos = itPlugins->second;

  } catch(cms::Exception& e) {
    std::cerr << "The executable \"edmPluginHelp\" failed while retrieving the list of parameter description plugins from the cache.\n"
              << "The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  } catch(const std::exception& e) {
    std::cerr << "The executable \"edmPluginHelp\" failed while retrieving the list of parameter description plugins from the cache.\n"
              << "The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  }

  // Select the plugins that match the library and plugin names if
  // any are specified in the command line arguments

  std::vector<edmplugin::PluginInfo> matchingInfos;

  try {

    std::string previousName;

    edm::for_all(infos, std::bind(&getMatchingPlugins,
                                    std::placeholders::_1,
                                    std::ref(matchingInfos),
                                    std::ref(previousName),
                                    std::cref(library),
                                    std::cref(plugin)));
  }
  catch(cms::Exception& e) {
    std::cerr << "The executable \"edmPluginHelp\" failed while selecting plugins.\n"
              << "The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  }
  catch(const std::exception& e) {
    std::cerr << "The executable \"edmPluginHelp\" failed while selecting plugins.\n"
              << "The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  }

  // For each selected plugin, fill the ParameterSetDescription for all defined
  // module labels and then print out the details of the description.
  try {

    int iPlugin = 0;
 
    edm::for_all(matchingInfos, std::bind(&writeDocForPlugin,
                                            std::placeholders::_1,
                                            factory,
                                            std::cref(moduleLabel),
                                            brief,
                                            printOnlyLabels,
                                            printOnlyPlugins,
                                            lineWidth,
                                            std::ref(iPlugin)));
  } catch(cms::Exception& e) {
    std::cerr << "\nThe executable \"edmPluginHelp\" failed. The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  } catch(const std::exception& e) {
    std::cerr << "\nThe executable \"edmPluginHelp\" failed. The following problem occurred:\n" 
              << e.what() << std::endl;
    return 1;
  }

  return 0;
} catch(cms::Exception const& e) {
  std::cerr << e.explainSelf() << std::endl;
  return 1;
} catch(std::exception const& e) {
  std::cerr << e.what() << std::endl;
  return 1;
}
	void close_store() {
		store(outfile);
	}
Example #30
0
entry main_40() {
new_env(0, 3);
ildc(1);
newobj(2);
ildc(0);
call(List_28);
store();
pop();
ildc(0);
ildc(1);
store();
pop();
label6:
ildc(0);
load();
ildc(6);
ilt();
jz(label7);
ildc(1);
ildc(1);
load();
ildc(0);
load();
call(push_front_30);
store();
pop();
label8:
ildc(0);
dup();
load();
swap();
dup();
load();
ildc(1);
iadd();
store();
pop();
pop();
jmp(label6);
label7:
ildc(1);
load();
call(print_36);
pop();
ildc(6);
call(print_13);
pop();
ildc(1);
load();
call(length_34);
call(println_15);
pop();
ildc(9);
call(print_13);
pop();
ildc(1);
load();
call(sum_35);
call(println_15);
pop();
ildc(2);
newobj(2);
ildc(1);
load();
call(get_element_29);
call(List_28);
store();
pop();
ildc(1);
ildc(1);
load();
call(pop_front_33);
store();
pop();
label9:
ildc(1);
load();
null();
onotequal();
jz(label10);
ildc(2);
ildc(2);
load();
ildc(1);
load();
call(get_element_29);
call(push_front_30);
store();
pop();
ildc(1);
ildc(1);
load();
call(pop_front_33);
store();
pop();
jmp(label9);
label10:
ildc(2);
load();
call(print_36);
pop();
ildc(11);
call(print_13);
pop();
ildc(2);
load();
call(length_34);
call(println_15);
pop();
ildc(14);
call(print_13);
pop();
ildc(2);
load();
call(sum_35);
call(println_15);
pop();
null();
ret();
}