示例#1
0
		Result Tracker::RecordMovie(Machine& emulator,StdStream const stream,const bool append)
		{
			if (!emulator.Is(Api::Machine::GAME))
				return RESULT_ERR_NOT_READY;

			UpdateRewinderState( false );

			Result result;

			try
			{
				if (movie == NULL)
				{
					movie = new Movie
					(
						emulator,
						&Machine::LoadState,
						&Machine::SaveState,
						emulator.cpu,
						emulator.image->GetPrgCrc()
					);
				}

				return movie->Record( stream, append ) ? RESULT_OK : RESULT_NOP;
			}
			catch (Result r)
			{
				result = r;
			}
			catch (const std::bad_alloc&)
			{
				result = RESULT_ERR_OUT_OF_MEMORY;
			}
			catch (...)
			{
				result = RESULT_ERR_GENERIC;
			}

			StopMovie();

			return result;
		}
示例#2
0
void getHeapLocation(const std::string & str, const unsigned stringStart, Token & token, Machine & machine)
{
    unsigned location = 0, previousLocation = 0;
    for (unsigned i = stringStart; i < str.size(); ++i)
    {
        char c = str[i];
        if (!isdigit(c))
            throw(std::runtime_error("Lexer::getHeapLocation: Invalid heap location specified "
                                     "(must only contain digits)"));
        previousLocation = location;
        location = (location * 10) + (int)(c - '0');

        // check for overflow
        if (location < previousLocation)
            throw(std::runtime_error("Lexer::getHeapLocation: Heap location specified is too large"));
    }

    token.locationData = &machine.unmanagedHeap().blockAt(location);
    token.type = Token::T_OPERAND_STATIC_LOCATION;
}
示例#3
0
 int PeekInt(Machine& machine, int pos)
 {
     Data d = machine.stack.Peek(pos);
     if (d == nullptr)
     {
         throw std::exception("Stack underflow");
     }
     if (d->IsVariable())
     {
         std::string name;
         d->GetVariable(name);
         machine.GetVariable(name, d);
     }
     if (d->IsInt() == false)
     {
         throw std::exception("Argument not a int");
     }
     int n;
     d->GetInt(n);
     return n;
 }
示例#4
0
文件: radio.cpp 项目: RuneHeick/APK15
int main()
{
  /* Instantiate State machine and make it process some relevant events... */
	Machine sm;
	sm.initiate();
	std::cout << "A\n";
	sm.process_event(EvFMTuner());
	std::cout << "B\n";
	sm.process_event(EvAMTuner());
	std::cout << "C\n";
	sm.process_event(EvAMTuner());
	std::cout << "D\n";
	sm.process_event(EvFMTuner());
	std::cout << "F\n";
  return 0;
}
示例#5
0
int main() {
	
	Machine machine;
	
	machine.install(script);
	while(!machine.finished()) machine.step();
	
	while(true){
		
		red = yellow = green = false;
		button = Pins::button.check();
		
		machine.run();
		while(!machine.finished()) machine.step();
		
		red    ? Pins::led0.high() : Pins::led0.low();
		yellow ? Pins::led1.high() : Pins::led1.low();
		green  ? Pins::led2.high() : Pins::led2.low();
		
	}
	
}
示例#6
0
/**
 * This should be executed before any other instruction.
 *
 * \param Int8 The export length. (This parameter is currently not used.)
 * \param Int8 The number of exports.
 * \param Int16 The number of globals.
 * \param Int8 The number of state variables.
 * \param Int16 The size of the execution stack.
 * \param Int8 The size of the environment stack.
 */
void DEF_VM(Machine & machine) {
    /*Size export_length    =*/ machine.nextInt8 (); //TODO: ...
    Size     exports_size = machine.nextInt8 ();
    Size     globals_size = machine.nextInt16();
    Size       state_size = machine.nextInt8 ();
    Size       stack_size = machine.nextInt16();
    Size environment_size = machine.nextInt8 ();

    machine.       hood.reset(    exports_size);
    machine.    globals.reset(    globals_size);
    machine.      state.reset(      state_size);
    machine.      stack.reset(    stack_size+1);
    machine.environment.reset(environment_size);

    machine.hood.add(machine.id);

    Instruction callback = machine.callbacks.pop();
    machine.callbacks.reset(3); //TODO: ...
    machine.callbacks.push(callback);
}
示例#7
0
文件: Main.cpp 项目: malpiatko/enigma
int main(int argc, char **argv){
	Machine machine;
	string line;
	argv = &argv[1];
	argc--;
	char letter;
	machine.initialisePlugboard(argv[argc-1]);
	if(argc!=1){
		machine.initialiseRotors(argc - 1, argv);
	}
	machine.initialiseReflector();
	while(getline(cin, line)){
		for(int i = 0; i <line.length(); i++){
			if(line[i]>='A'&&line[i]<='Z'){
				cout << machine.encodeLetter(line[i]);
			}
		}
	}
	machine.deallocMemmory();
  	return 0;
}
// PRIVATE METHODS
QVector<Machine> MachineRepository::queryToMachines(QSqlQuery query) {
    // This is just a helper method to take a query and convert into
    // a vector of people

    QVector<Machine> machines;

    while(query.next()) {

        Machine m;

        m.setId(query.value(0).toInt());
        m.setName(query.value(1).toString());
        m.setYearConstructed(QDate::fromString(query.value(2).toString(), QString(database::FIELD_YEAR_STORE_FORMAT)));
        m.setType(query.value(3).toString());
        m.setWasBuilt(query.value(4).toInt() == 1 ? true : false);

        machines.push_back(m);
    }

    return machines;
}
// PUBLIC METHODS
void MachineRepository::addEditMachine(bool &error, Machine &machine) {
    // takes a person to add/edit. performs an update on a record in the db if the person id is set

    QSqlDatabase db = QSqlDatabase::database();
    QString queryString; 
    QSqlQuery query;
    error = false;

    // if the user has a valid id, we upate, otherwise insert
    if(machine.getId() != database::BLANK_RECORD_ID) {
        
        queryString = "UPDATE machine SET Name=:name, YearConstructed=:year, Type=:type, WasBuilt=:wasBuilt ";
        queryString += "WHERE ID=:id";

        query.prepare(queryString);
        query.bindValue(":id", machine.getId());
    
    } else {

        queryString = "INSERT INTO machine (Name, YearConstructed, Type, WasBuilt) VALUES ";
        queryString += "(:name, :year, :type, :wasBuilt)";

        query.prepare(queryString);

    }

    query.bindValue(":name", machine.getName());
    query.bindValue(":year", machine.getYearConstructed().toString(QString(database::FIELD_YEAR_STORE_FORMAT)));
    query.bindValue(":type", machine.getType());
    query.bindValue(":wasBuilt", machine.getWasBuilt() ? 1 : 0);

    query.exec();

    if(query.lastError().isValid()) {
        error = true;
        return;
    }

    return;
}
void Management::addBuildToSlave(int machineId, int BuildID, QString buildName){

    Machine *machine = getMachineById(machineId);

    if(machine == 0)
        return;

    Build *trueBuild = getBuildByID(BuildID);

    if(trueBuild == 0){
        //this point the build does not exist
        emit slaveGotBuild(machine, BuildID, buildName, false);
        //this point that machine has a build it is not suppose to have...go and delete it
        machine->deleteBuild(BuildID);

        //notify the slave that it should delete the build
        machine->deleteBuildNotify(BuildID);
    }
    else{
        Build *buildToAdd = new Build(BuildID, buildName, "", trueBuild->getBuildDirectory());

        bool existMachineWithBuild = machineWithBuild(machine->getMachineID(), buildToAdd->getBuildID());

        //if there already exist that build for the machine, don't add it twice
        if(existMachineWithBuild == false)
            machine->addBuild(buildToAdd);
        else
            return;

        emit slaveGotBuild(machine, BuildID, buildName, true);

        //check if the build name corrolate with the information on the
        //slave side
        if(buildName.compare(trueBuild->getBuildName())){
            machine->updateBuildName(buildToAdd->getBuildID(), trueBuild->getBuildName());
        }
    }

}
示例#11
0
文件: FileIO.cpp 项目: Kampbell/qfsm
/**
 * Performs the actual saving of project @a p.
 */
bool FileIO::doSave(Project* p)
{
    Machine* m = p->machine;
    if (!m)
      return FALSE;

    QList<GState*> list;
    QList<GTransition*> tlist; 
    GState *state;
    State* dest_state;
    GTransition* t;

    QFile file(act_file);
    if (!file.open(QIODevice::WriteOnly))
    {
      Error::info(tr("File cannot be written."));
      qDebug("file cannot be opened for writing");
      return FALSE;
    }
    Q3TextStream s(&file);

    list = m->getSList();
    QMutableListIterator<GState*> i(list);
    AppInfo info(main);
    double xpos, ypos;
    double c1x, c1y, c2x, c2y;
    double endx, endy;
    int initial;
//    int canvasw, canvash;
    QString transio;
    
    s << info.getVersionMajor() << " ";
    s << info.getVersionMinor() << endl;
    s << m->getName() << endl;
    s << m->getVersion() << endl;
    s << m->getAuthor() << endl;
    s << m->getDescription() << endl;
    s << m->getType() << " ";
    s << m->getNumMooreOutputs() << " ";
    s << m->getNumInputs() << " ";
    s << m->getNumOutputs() << endl;
    s << m->getMooreOutputNames() << endl;
    s << m->getMealyInputNames() << endl;
    s << m->getMealyOutputNames() << endl;
    s << m->countStates() << endl;
    state = m->getInitialState();
    if (state)
      initial= state->getEncoding();
    else
      initial=-1;

    s << initial << endl;
//    m->getCanvasSize(canvasw, canvash);
//    s << canvasw << " " << canvash << endl;
    s << m->getSFont().family() << endl << m->getSFont().pointSize() << endl;
    s << m->getTFont().family() << endl << m->getTFont().pointSize() << endl;
    s << m->getArrowType() << endl;
    s << endl;

    for(; i.hasNext();)
    {

      state = i.next();
      state->getPos(xpos, ypos);
      
      s.setf(Q3TextStream::bin);
      s << state->getEncoding() << endl;
      s << state->getMooreOutputsStr() << endl;
      s.setf(Q3TextStream::dec);

      s << state->getStateName() << endl;
      s << state->getDescription() << endl;
      s << xpos << " " << ypos << " " << state->getRadius() << endl;
      s << state->getPen().color().rgb() << " " << state->getLineWidth() << endl;
      s << state->getBrush().color().rgb() << endl;
      s << state->isFinalState() << endl;
      s << endl;
    }
    s << endl;

    i.toFront();

    for(; i.hasNext();)
    {
      state = i.next();

      s.setf(Q3TextStream::bin);
      s << state->getEncoding() << endl;
      s.setf(Q3TextStream::dec);

      tlist = state->tlist;
      QMutableListIterator<GTransition*> j(tlist);

      s << state->countTransitions() << endl;

      for(; j.hasNext();)
      {
        t = j.next();

        dest_state = t->getEnd();

	s.setf(Q3TextStream::bin);
	if (dest_state)
	  s << dest_state->getEncoding() << endl;
	else
	  s << -1 << endl;
	s.setf(Q3TextStream::dec);

        s << t->getInfo()->getType() << endl;
        s << t->getDescription() << endl;
//	if (t->getInfo()->getType()==Binary)
	{
          s << t->getInfo()->getInputsStr(NULL) << " ";
          transio = t->getInfo()->getOutputsStr(NULL);
	  if (transio.isEmpty())
	    transio="<noout>";
	  s << transio << endl;
        }
	
        t->getPos(xpos, ypos);
	t->getEndPos(endx, endy);
	t->getCPoint1(c1x, c1y);
	t->getCPoint2(c2x, c2y);
	
	s << xpos << " " << ypos << " ";
	s << c1x << " " << c1y << " " << c2x << " " << c2y << " ";
	s << endx << " " << endy << " ";
	s << (int)t->isStraight() << endl;
        
	s << endl;
      }
      s << endl;
    }

    // phantom state
    state = m->getPhantomState();

    tlist = state->tlist;
    QMutableListIterator<GTransition*> ph(tlist);

    s << state->countTransitions() << endl;

    for(; ph.hasNext();)
    {
      t = ph.next();

      dest_state = t->getEnd();

      s.setf(Q3TextStream::bin);
      if (dest_state)
	s << dest_state->getEncoding() << endl;
      else
	s << -1 << endl;
      s.setf(Q3TextStream::dec);

      s << t->getInfo()->getType() << endl;
      s << t->getDescription() << endl;
//      if (t->getInfo()->getType()==Binary)
      {
	s << t->getInfo()->getInputsStr(NULL) << " ";
	transio = t->getInfo()->getOutputsStr(NULL);
	if (transio.isEmpty())
	  transio="<noout>";
	s << transio << endl;
      }
      t->getPos(xpos, ypos);
      t->getEndPos(endx, endy);
      t->getCPoint1(c1x, c1y);
      t->getCPoint2(c2x, c2y);
      
      s << xpos << " " << ypos << " ";
      s << c1x << " " << c1y << " " << c2x << " " << c2y << " ";
      s << endx << " " << endy << " ";
      s << (int)t->isStraight() << endl;
      
      s << endl;
    }

    file.close();

    p->setChanged(FALSE);
    return TRUE;
}
示例#12
0
	/**
	 * \param Int8 The number of zero's to put in the tuple.
	 * \return Tuple A tuple filled with zero's.
	 */
	void FAB_NUM_VEC(Machine & machine){
		Size elements = machine.nextInt8();
		Tuple tuple(elements);
		for(Index i = 0; i < elements; i++) tuple.push(0);
		machine.stack.push(tuple);
	}
示例#13
0
	void NBR_RANGE(Machine & machine){
		float x = machine.currentNeighbour().x;
		float y = machine.currentNeighbour().y;
		float z = machine.currentNeighbour().z;
		machine.stack.push(sqrt(x*x + y*y + z*z));
	}
int main(int argc, char** argv)
{
    if(argc != 2)
    {
        std::cout << "usage: ./sim <filename>\n";
        return 0;

    }

    std::string filename = argv[1];

    std::fstream f;
    f.open(filename.c_str());
    if(!f)
    {
        std::cout << "failed to open: " << filename << "\n";

    }

    Machine machine;

    std::string line;

    bool first = true;

    while(std::getline(f, line))
    {
        int addr = 0;
        int instr = 0;
        if(first)
        {
            int start = hexStrToInt(line);
            machine.PC.stored = start;
            std::cout << "start: " << start << "\n";
            first = false;
            continue;

        }

        if(line.find(" ") != std::string::npos)
        {
            addr = hexStrToInt(line.substr(0, line.find(" ")));
            instr = hexStrToInt(line.substr(line.find(" ")+1));

        }
        else if(line.find("\t") != std::string::npos)
        {
            addr = hexStrToInt(line.substr(0, line.find("\t")));
            instr = hexStrToInt(line.substr(line.find("\t")+1));

        }

        if(addr == 0 && instr == 0)
        {
            break;

        }

        addr /= 4;

        machine.mmu.memory[addr] = instr;

    }

    machine.PC.invoke();

    
    int i = 0;
    while(machine.cpu.state != 1 || (machine.cpu.state == 1 && machine.mmu.memory[machine.PC.stored/4] != 0))
    {
        while(machine.cpu.state != 0)
        {
            std::cout << "\n//////////\nSTATE: " << machine.cpu.state << "\n//////////\n";
            machine.update();
            machine.print();

        }

        i++;
        std::cout << "\n//////////\nSTATE: " << machine.cpu.state << "\n//////////\n";
        machine.update();
        machine.print();

    }

    while(machine.cpu.state != 0)
    {
        std::cout << "\n//////////\nSTATE: " << machine.cpu.state << "\n//////////\n";
        machine.update();
        machine.print();

    }


    machine.regs.printContents();

    return 0;

}
示例#15
0
	/**
	 * \param Int The index of the state variable.
	 * \param Data The new value for the state variable.
	 * 
	 * \return Data The new value of the state variable.
	 */
	void SET_FEEDBACK(Machine & machine){
		Index state_index = machine.nextInt();
		machine.state[state_index].data = machine.stack.peek();
		machine.state[state_index].is_executed = true;
	}
示例#16
0
文件: m4.cpp 项目: St0rmcrow/scummvm
Common::Error M4Engine::run() {
	// Set up the graphics mode
	initGraphics(640, 480, true);

	// Necessary pre-initialisation
	_resourceManager = new M4ResourceManager(this);

	// Set up needed common functionality
	MadsM4Engine::run();

	// M4 specific initialisation
	_converse = new Converse(this);

	_scene = new M4Scene(this);
	_script->open("m4.dat");

#ifdef SCRIPT_TEST

#if 0
	ScriptFunction *func = _script->loadFunction("room_parser_142");
	_script->runFunction(func);
#endif

#if 1
	ScriptFunction *func = _script->loadFunction("room_daemon_951");
	for (int i = 1; i < 58; i++) {
		_vm->_kernel->trigger = i;
		_script->runFunction(func);
		debugCN(kDebugCore, "=================================\n");
	}
#endif

	return Common::kNoError;
#endif

	// Set up the inventory

	// Set up the game interface view
	//_interfaceView->inventoryAdd("Money", "", 55);	// Sample item

	if (getGameType() == GType_Burger) {
		for (int i = 0; i < ARRAYSIZE(burger_inventory); i++) {
			char* itemName = strdup(burger_inventory[i].name);
			_inventory->registerObject(itemName, burger_inventory[i].scene,
									   burger_inventory[i].icon);
			_inventory->addToBackpack(i);	// debug: this adds ALL objects to the player's backpack
		}
	}

	// Show intro

	if (getGameType() == GType_Burger) {
		_kernel->newRoom = TITLE_SCENE_BURGER;
	} else {
		_scene->getBackgroundSurface()->loadBackgroundRiddle("main menu");
		_ws->setBackgroundSurface(_scene->getBackgroundSurface());
	}

	_viewManager->addView(_scene);

	// Setup game wide hotkeys. Note that Orion Burger used F2/F3 for Save/Restore,
	// but for standardisation with most other games, F5/F7 are also mapped

	_viewManager->systemHotkeys().add(Common::KEYCODE_ESCAPE, &escapeHotkeyHandler);
	_viewManager->systemHotkeys().add(Common::KEYCODE_F2, &saveGameHotkeyHandler);
	_viewManager->systemHotkeys().add(Common::KEYCODE_F3, &loadGameHotkeyHandler);
	_viewManager->systemHotkeys().add(Common::KEYCODE_F5, &saveGameHotkeyHandler);
	_viewManager->systemHotkeys().add(Common::KEYCODE_F7, &loadGameHotkeyHandler);
	_viewManager->systemHotkeys().add(Common::KEYCODE_F9, &gameMenuHotkeyHandler);

	// Start playing Orion Burger intro music
	//_midi->playMusic("999intro", 255, false, -1, -1);

	// TODO: start playing intro animations

	// TODO: Master Lu

	// Test for mouse
	_mouse->init("cursor", NULL);
	_mouse->setCursorNum(0);
	_mouse->cursorOn();

	_ws->assets()->loadAsset("SHOW SCRIPT", NULL);
	_ws->assets()->loadAsset("STREAM SCRIPT", NULL);

#ifdef INTRO_TEST
	int curPart = 0;
	Machine *mach = NULL;
#endif

	_ws->setSurfaceView(_scene);

	uint32 nextFrame = g_system->getMillis();
	while (!_events->quitFlag) {

		// This should probably be moved to either Scene or Kernel
		if (_kernel->currentRoom != _kernel->newRoom) {

			_ws->clear();

			_kernel->currentSection = _kernel->newRoom / 100;
			_kernel->currentRoom = _kernel->newRoom;

			_scene->loadScene(_kernel->currentRoom);

			_ws->setBackgroundSurface(_scene->getBackgroundSurface());
			_ws->setInverseColorTable(scene()->getInverseColorTable());

			_kernel->loadSectionScriptFunctions();
			_kernel->loadRoomScriptFunctions();

			_kernel->roomInit();

			_scene->show();

#ifdef INTRO_TEST
			if (_kernel->currentRoom == 951) {
				curPart = 0;
				mach = _ws->streamSeries("PLANET X HILLTOP A", 1, 0x1000, 0);
			}
#endif

		}

		eventHandler();

		// Call the updateState method of all views
		_viewManager->updateState();

		// Handle frame updates
		if (g_system->getMillis() >= nextFrame) {
#ifdef INTRO_TEST
			// Orion Burger intro test (scene 951)
			// This is ugly and bad, machine is not deleted so there's a huge memory
			// leak too. But hey, we can see some of the intro!
			if (mach && mach->getState() == -1) {
				if (curPart == 0)
					mach = _ws->streamSeries("Planet X Low Ground Shot", 1, 0x1000, 0);
				else if (curPart == 1)
					mach = _ws->streamSeries("Planet X Hilltop B", 1, 0x1000, 0);
				else if (curPart == 2)
					mach = _ws->streamSeries("Space Station Panorama A", 1, 0x1000, 0);
				else if (curPart == 3)
					mach = _ws->streamSeries("Cargo Transfer Area A", 1, 0x1000, 0);
				else if (curPart == 4)
					mach = _ws->streamSeries("VP's Office A", 1, 0x1000, 0);
				else if (curPart == 5)
					mach = _ws->streamSeries("Hologram", 1, 0x1000, 0);
				else if (curPart == 6)
					mach = _ws->streamSeries("VP's Office B", 1, 0x1000, 0);
				else if (curPart == 7)
					mach = _ws->streamSeries("Cargo Transfer Area B", 1, 0x1000, 0);
				else if (curPart == 8)
					mach = _ws->streamSeries("Cargo Transfer Controls", 1, 0x1000, 0);
				else if (curPart == 9)
					mach = _ws->streamSeries("Space Station Panorama B", 1, 0x1000, 0);
				// This last scene is from the rolling demo
				//else if (curPart == 10)
				//	mach = _ws->streamSeries("Call To Action", 1, 0x1000, 0);
				curPart++;
			}
#endif
			_ws->update();
			_viewManager->refreshAll();
			nextFrame = g_system->getMillis();// + GAME_FRAME_DELAY;

			// TEST STUFF ONLY
			if (_player->commandReady) {
				_kernel->roomParser();
				_player->commandReady = false;
			}

		}

		g_system->delayMillis(10);
	}

	return Common::kNoError;
}
示例#17
0
void MachineOperation::operator () (osg::Object* object)
{
    Machine* machine = dynamic_cast<Machine*>(object);
    if (machine)
    {
        std::string application;
        if (_task->getProperty("application",application))
        {
            osg::Timer_t startTick = osg::Timer::instance()->tick();

            _task->setProperty("hostname",machine->getHostName());
            _task->setStatus(Task::RUNNING);
            _task->setWithCurrentDate("date");
            _task->write();
            
            // machine->log(osg::NOTICE,"machine=%s running task=%s",machine->getHostName().c_str(),_task->getFileName().c_str());

            machine->startedTask(_task.get());

            int result = machine->exec(application);
            
            machine->endedTask(_task.get());

            // read any updates to the task written to file by the application.
            _task->read();
            
            double duration;
            if (!_task->getProperty("duration",duration))
            {
                duration = osg::Timer::instance()->delta_s(startTick, osg::Timer::instance()->tick());
            }

            if (result==0)
            {
                // success
                _task->setStatus(Task::COMPLETED);
                _task->write();

                // need to update taskmanger with any new file lists
                if (machine->getMachinePool() && machine->getMachinePool()->getTaskManager())
                {
                    std::string fileListBaseName;
                    if (_task->getProperty("fileListBaseName",fileListBaseName))
                    {
                        machine->getMachinePool()->getTaskManager()->addRevisionFileList(fileListBaseName+".added");
                        machine->getMachinePool()->getTaskManager()->addRevisionFileList(fileListBaseName+".removed");
                        machine->getMachinePool()->getTaskManager()->addRevisionFileList(fileListBaseName+".modified");
                    }
                }
            }
            else
            {
                // failure
                _task->setStatus(Task::FAILED);
                _task->write();
                
                // tell the machine about this task failure.
                machine->taskFailed(_task.get(), result);
            }
            
            // machine->log(osg::NOTICE,"machine=%s completed task=%s in %f seconds, result=%d",machine->getHostName().c_str(),_task->getFileName().c_str(),duration,result);
        }

    }
}
void Solution::reassignProcess(Process* p, Machine* m){


    if(p->getMachine() == m) return;

	//update check variables
	if(m != 0) {
		nmb_processes_from_service_on_machine_[p->getService()->getId()][m->getId()] ++;
		if(nmb_processes_from_service_on_machine_[p->getService()->getId()][m->getId()] == 2)
			nmb_of_conflicted_machines_++;
	}

	if(p->getMachine() != 0) {
	    nmb_processes_from_service_on_machine_[p->getService()->getId()][p->getMachineId()] --;
	    if(nmb_processes_from_service_on_machine_[p->getService()->getId()][p->getMachineId()] == 1)
	    	nmb_of_conflicted_machines_--;
	}


	int number_of_moved_processes_before = p->getService()->getNumberOfMovedProcesses();
	bool checkSpreadBefore = p->getService()->checkSpread();
	bool checkCapacityOnMachine1Before, checkCapacityOnMachine2Before;

	Machine* oldMachine = p->getMachine();
	if(p->getMachine() != 0)  checkCapacityOnMachine1Before = !p->getMachine()->hasNegativeRemainingCapacity();
    if(m != 0)                checkCapacityOnMachine2Before = !m->hasNegativeRemainingCapacity();



    //update cost variables


	int64 oldMachine1LoadCost = 0;
	int64 oldMachine1BalanceCost = 0;

	if(p->getMachine() != 0)
	{
		oldMachine1LoadCost = p->getMachine()->getLoadCost();
		oldMachine1BalanceCost = p->getMachine()->getBalanceCost();
	}

	int64 oldMachine2LoadCost = 0;
	int64 oldMachine2BalanceCost = 0;

	if(m != 0)
	{
		oldMachine2LoadCost = m->getLoadCost();
		oldMachine2BalanceCost = m->getBalanceCost();
	}


	//*****************************
      p->assign(m);
    //*****************************

	if(!p->getService()->checkSpread() &&  checkSpreadBefore) nmb_of_services_with_small_spread_++;
	if(p->getService()->checkSpread()  && !checkSpreadBefore) nmb_of_services_with_small_spread_--;

	if(oldMachine != 0 && !checkCapacityOnMachine1Before && !oldMachine->hasNegativeRemainingCapacity())
		nmb_of_machines_with_violated_capacity_--;
	if(m != 0 && checkCapacityOnMachine2Before && m->hasNegativeRemainingCapacity())
		nmb_of_machines_with_violated_capacity_++;


	if(m != 0)
	{
		load_cost_    =    load_cost_ + (m->getLoadCost()    - oldMachine2LoadCost);
		balance_cost_ = balance_cost_ + (m->getBalanceCost() - oldMachine2BalanceCost);
	}

	if(oldMachine != 0)
	{
		load_cost_    =    load_cost_ + (oldMachine->getLoadCost()    - oldMachine1LoadCost);
		balance_cost_ = balance_cost_ + (oldMachine->getBalanceCost() - oldMachine1BalanceCost);
	}


	if(p->getInitialMachine() != m && p->getInitialMachine() == oldMachine)
		process_move_cost_ += data_->getProcessMoveCostWeight();

	if(p->getInitialMachine() == m)
		process_move_cost_ -= data_->getProcessMoveCostWeight();

	machine_move_cost_ = machine_move_cost_ + data_->getMachineMoveCostWeight() *
	  (p->getInitialMachine()->getToMachineMoveCost(m) - p->getInitialMachine()->getToMachineMoveCost(oldMachine));


	//data_->calculateProcessesPositionsByRemovingValue();

    //***********************************************************************
    // update number of max number of processes
	// (used for calculating service move cost difference)

	int number_of_moved_processes_after =
			p->getService()->getNumberOfMovedProcesses();
	if(number_of_moved_processes_after > max_number_of_moved_processes_)
	{
		max_number_of_moved_processes_ =
				p->getService()->getNumberOfMovedProcesses();
		number_of_services_with_max_number_of_moved_processes_ = 1;
	}
	else
    if(number_of_moved_processes_after == max_number_of_moved_processes_ &&
       number_of_moved_processes_after > number_of_moved_processes_before)
    {
	  number_of_services_with_max_number_of_moved_processes_ ++;
    }
    else
	if(number_of_moved_processes_after < max_number_of_moved_processes_ &&
	   number_of_moved_processes_before == max_number_of_moved_processes_)
	{
	  if(number_of_services_with_max_number_of_moved_processes_ > 1)
		  number_of_services_with_max_number_of_moved_processes_--;
	  else
	  {
		  // calculate number of moved processes for each service again
		 max_number_of_moved_processes_= 0;
		 number_of_services_with_max_number_of_moved_processes_ = 0;
		 for(vector<Service*>::iterator it = services_.begin();
				 it != services_.end(); it++)
		   if((*it)->getNumberOfMovedProcesses() > max_number_of_moved_processes_)
		   {
			 max_number_of_moved_processes_ = (*it)->getNumberOfMovedProcesses();
			 number_of_services_with_max_number_of_moved_processes_ = 1;
		   }
		   else if((*it)->getNumberOfMovedProcesses() ==
				   max_number_of_moved_processes_)
			   number_of_services_with_max_number_of_moved_processes_++;
	  }
	}
    //*************************************************************************


}
示例#19
0
void MachinePool::reportTimingStatus()
{
    unsigned int numTasksPending = _operationQueue->getNumOperationsInQueue();

    unsigned int numTasksCompleted = 0;
    double totalComputeTime = 0.0;
    unsigned int numCores = 0;
    
    for(Machines::iterator itr = _machines.begin();
        itr != _machines.end();
        ++itr)
    {
        Machine* machine = itr->get();
        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(machine->getRunningTasksMutex());

        TaskStatsMap& taskStatsMap = machine->getTaskStatsMap();
        for(TaskStatsMap::iterator titr = taskStatsMap.begin();
            titr != taskStatsMap.end();
            ++titr)
        {
            TaskStats& stats = titr->second;
            
            numTasksCompleted += stats.numTasks();
            totalComputeTime += stats.totalTime();
        }
        numCores += getNumThreads();
    }
        
    double averageTaskTime = (numTasksCompleted!=0) ? (totalComputeTime/ double(numTasksCompleted)) : 0;

    double currentTime = osg::Timer::instance()->time_s();
    double estimatedTimeOfLastCompletion = currentTime;
    unsigned int numTasksRunning = 0;
    for(Machines::iterator itr = _machines.begin();
        itr != _machines.end();
        ++itr)
    {
        Machine* machine = itr->get();
        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(machine->getRunningTasksMutex());
        
        Machine::RunningTasks& runningTasks = machine->getRunningTasks();
        numTasksRunning += runningTasks.size();
        for(Machine::RunningTasks::iterator ritr = runningTasks.begin();
            ritr != runningTasks.end();
            ++ritr)
        {
            double startTime = ritr->second;
            double elapsedTime = currentTime - startTime;
            double estimatedEndTime = (elapsedTime < averageTaskTime) ? startTime + averageTaskTime : currentTime+1.0;
            if (estimatedTimeOfLastCompletion < estimatedEndTime) estimatedTimeOfLastCompletion = estimatedEndTime;
        }
    }
    
    double numTaskPendingAcrossAllCores = (numTasksPending>0) ? ceil(double(numTasksPending) / double(numCores)) : 0;
    estimatedTimeOfLastCompletion += numTaskPendingAcrossAllCores*averageTaskTime;
    double estimateTimeToCompletion = estimatedTimeOfLastCompletion-currentTime;

    double daysToCompletion = floor(estimateTimeToCompletion / (24.0*60.0*60.0) );
    double secondsRemainder = estimateTimeToCompletion - daysToCompletion*24.0*60.0*60.0;
    double hoursToCompletion = floor(secondsRemainder / (60.0*60.0));
    secondsRemainder = secondsRemainder - hoursToCompletion*60.0*60.0;
    
    double minutesToCompletion = floor(secondsRemainder / 60.0);
    secondsRemainder = secondsRemainder - minutesToCompletion*60.0;

    if (daysToCompletion>0.0)
    {
        log(osg::NOTICE,"Number of tasks completed %i, running %i, pending %i. Estimated time to completion %d days, %d hours, %d minutes, %2.1f percent done.",
            numTasksCompleted, numTasksRunning, numTasksPending, 
            int(daysToCompletion), int(hoursToCompletion), int(minutesToCompletion),
            100.0*currentTime/estimatedTimeOfLastCompletion);
    }
    else if (hoursToCompletion>0.0)
    {
        log(osg::NOTICE,"Number of tasks completed %i, running %i, pending %i. Estimated time to completion %d hours, %d minutes, %2.1f percent done.",
            numTasksCompleted, numTasksRunning, numTasksPending, 
            int(hoursToCompletion), int(minutesToCompletion),
            100.0*currentTime/estimatedTimeOfLastCompletion);
    }
    else if (minutesToCompletion>0.0)
    {
        log(osg::NOTICE,"Number of tasks completed %i, running %i, pending %i. Estimated time to completion %d minutes, %d seconds, %2.1f percent done.",
            numTasksCompleted, numTasksRunning, numTasksPending, 
            int(minutesToCompletion),int(secondsRemainder),
            100.0*currentTime/estimatedTimeOfLastCompletion);
    }
    else
    {
        log(osg::NOTICE,"Number of tasks completed %i, running %i, pending %i. Estimated time to completion %d seconds, %2.1f percent done.",
            numTasksCompleted, numTasksRunning, numTasksPending, 
            int(secondsRemainder),
            100.0*currentTime/estimatedTimeOfLastCompletion);
    }

}
示例#20
0
	/**
	 * The address of the next instruction is pushed on the globals list
	 * and execution continues after the function definition.
	 * 
	 * \param Inti16 The number of (following) bytes that define the function.
	 * 
	 * \deprecated_mitproto{DEF_FUN}
	 */
	void DEF_FUN16(Machine & machine){
		Size size = machine.nextInt16();
		machine.globals.push(machine.currentAddress());
		machine.skip(size);
	}
示例#21
0
/// Undo changing the machine properties.
void UndoBuffer::undoChangeMachine(Undo* u)
{
  Project* p;
  p = u->getProject();

  Machine* m;
  QString n;
  int nb, ni, no;
  QFont sf, tf;
  int at, t;
  QStringList ilist, olist, olistm;
  bool dit;

  u->getMachineInfo(m, n, t, nb, olistm, ni, ilist, no, olist, sf, tf, at, dit);

  m->setName(n);
  m->setType(t);
  m->setNumMooreOutputs(nb);
  m->setNumInputs(ni);
  m->setNumOutputs(no);
  m->setMooreOutputList(olistm);
  m->setInputNameList(ilist);
  m->setOutputNameList(olist);
  m->setSFont(sf);
  m->setTFont(tf);
  m->setArrowType(at);
  m->setDrawITrans(dit);
}
示例#22
0
	/// \deprecated_mitproto
	void DEF_TUP(Machine & machine){
		machine.execute(FAB_TUP);
		machine.globals.push(machine.stack.pop());
	}
// decrease machine capacities and set process requirements
// to zero if process can be assigned to one machine only
Data* preprocesData(Solution* sol)
{

	  Data* data = sol->getData();

	  int number_of_removed_processes = 0;

	  while(sol->getNumberOfProcessesThatCanBeAssignedToOnlyOneMachine() > 0)
	  {

		  for(int p = 0; p < data->getNumberOfProcesses(); p++)
		  {
			  int n = sol->getNumberOfMachinesProcessCanBeAssignedTo(p);
			  if(n == 1)
			  {

				  Process* process = data->getProcess(p);

				  int machine_index = -1;
				  for(int m = 0; m < sol->getNumberOfMachines(); m++)
					if(sol->matrix_[p][m] == true) {
						machine_index =  m;
						break;
					}

				   Machine* machine = data->getMachine(machine_index);

				   //decrease capacities
				   for(int r = 0; r < data->getNumberOfResources(); r++)
				   {

					   machine->getMachineResource(r)->decreaseCapacity(process->getRequirement(r));
					   machine->getMachineResource(r)->decreaseSafetyCapacity(process->getRequirement(r) );

				 	   data->getResource(r)->setTotalCapacity(
				 			  data->getResource(r)->total_capacity  - process->getRequirement(r));
				 	   data->getResource(r)->setTotalRequirement(
				 			  data->getResource(r)->total_requirement - process->getRequirement(r));
				 	   data->getResource(r)->setTotalSafetyCapacity(
				 			  data->getResource(r)->total_safety_capacity - process->getRequirement(r));


					   process->setRequirement(r, 0);

					   number_of_removed_processes++;
				   }



				   for(int p2_i = 0; p2_i < process->getService()->getNumberOfProcesses(); p2_i++)
				   {
					   int p2 = process->getService()->getProcess(p2_i)->getId();
					   int n2 = sol->getNumberOfMachinesProcessCanBeAssignedTo(p2);
					   if(n2 >= 2)
					   {
						   if(sol->matrix_[p2][machine_index] &&
						      sol->getProcess(p2)->getService() == sol->getProcess(p)->getService())
						   {
							   sol->matrix_[p2][machine_index] = false;
						   }
					   }
				   }
			  }
		  }

          sol->fillMatrix();

          for(int p = 0; p < sol->getNumberOfProcesses(); p++)
          {
        	  bool empty_process = true;
        	  for(int r = 0; r < data->getNumberOfResources(); r++)
        		  if(sol->getProcess(p)->getRequirement(r) > 0)
        		  {
        			  empty_process = false;
        			  break;
        		  }
        	  if(empty_process)
        	  {
        		  for(int m = 0; m < sol->getNumberOfMachines(); m++)
        			 sol->matrix_[p][m] = false;
        	  }
          }
	  }


      for(int p = 0; p < sol->getNumberOfProcesses(); p++)
   		  sol->matrix_[p][sol->getProcess(p)->getInitialMachine()->getId()] = true;

	  return data;

}
示例#24
0
	/// \deprecated_mitproto
	void DEF_NUM_VEC(Machine & machine){
		machine.execute(FAB_NUM_VEC);
		machine.globals.push(machine.stack.pop());
	}
示例#25
0
void Next::execute(Machine &machine, unsigned int &instruction) const
{
    machine.shr();
    ++instruction;
}
示例#26
0
	/**
	 * \param Int16 The index of the global in the gobals list.
	 * \return The value of the global variable.
	 * 
	 * \deprecated_mitproto{GLO_REF}
	 */
	void GLO_REF16(Machine & machine){
		Index index = machine.nextInt16();
		machine.stack.push(machine.globals[index]);
	}
示例#27
0
	void NBR_LAG(Machine & machine){
		machine.stack.push(machine.currentNeighbour().lag);
	}
示例#28
0
	void DEF_FUN_N(Machine & machine){
		machine.globals.push(machine.currentAddress());
		machine.skip(size);
	}
示例#29
0
	void NBR_BEARING(Machine & machine){
		float x = machine.currentNeighbour().x;
		float y = machine.currentNeighbour().y;
		machine.stack.push(atan2(y,x));
	}
示例#30
0
std::vector<typename Machine::State> simulatePortNumberedDDA(
	const Network& network,
	const Machine& machine,
	const std::vector<typename Machine::Input>& inputs,
	Listener& listener = EmptyListener<Machine>::instance
) {
	typedef typename Machine::State State;
	typedef typename Machine::Message Message;
	
	std::size_t n = network.size();
	if(n != inputs.size()) {
		throw std::runtime_error(
			"simulatePortNumberedDDA: Wrong number of inputs given."
		);
	}
	
	std::vector<State> states;
	
	// Initialize all states from init function.
	for(std::size_t i = 0; i < n; ++i) {
		states.emplace_back(machine.init(network[i].size(), inputs[i]));
	}
	
	std::vector<std::vector<Message>> msgs(n);
	
	std::size_t round = 0;
	while(true) {
		listener.start(round, (const std::vector<State>&)states);
		
		// If all states are stopped, we are done.
		bool done = true;
		for(const State& state : states) {
			if(!machine.stopped(state)) {
				done = false;
				break;
			}
		}
		if(done) break;
		
		// Send all messages.
		for(std::size_t i = 0; i < n; ++i) {
			msgs[i].clear();
			machine.send(states[i], msgs[i]);
			if(msgs[i].size() != network[i].size()) {
				throw std::runtime_error(
					"simulatePortNumberedDDA: "
					"'send' function wrote wrong number of messages."
				);
			}
		}
		
		listener.send(
			round,
			(const std::vector<State>&)states,
			(const std::vector<std::vector<Message>>&)msgs
		);
		
		// Swap messages for each port.
		for(std::size_t i = 0; i < n; ++i) {
			for(std::size_t ei = 0; ei < network[i].size(); ++ei) {
				Edge edge = network[i][ei];
				
				// Swap only once.
				if(std::make_pair(i, ei) < std::make_pair(edge.dest, edge.back_index)) {
					continue;
				}
				
				std::swap(msgs[i][ei], msgs[edge.dest][edge.back_index]);
			}
		}
		
		listener.receive(
			round,
			(const std::vector<State>&)states,
			(const std::vector<std::vector<Message>>&)msgs
		);
		
		// Receive all messages and update states.
		for(std::size_t i = 0; i < n; ++i) {
			states[i] = machine.receive(states[i], msgs[i]);
		}
		
		++round;
	}
	
	return states;
}