GIFError CGIFFile::WriteImage(GIFFrameBuffer &frame, long top, long left) { if (frame.pBuffer == 0) return GIF_InvalidPointer; if (m_IsInput) return GIF_WriteToInputFile; if (top < 0) top = 0; if (left < 0) left = 0; WORD width = WORD(frame.Width); WORD height = WORD(frame.Height); if (width > (m_ImageWidth - left)) width = WORD(m_ImageWidth - left); if (height > (m_ImageHeight - top)) height = WORD(m_ImageHeight - top); if ((width < 1) || (height < 1)) return GIF_InvalidImageSize; // When there are multiple frames, there needs to be a control extension // between each frame to indicate the duration of the delay between // displaying the sequential frames. if (m_FrameCount > 0) writeControlExtension(); GIFError status; BYTE imageDescriptor = 0x2C; status = writeToFile(&imageDescriptor, sizeof(imageDescriptor)); if (status != GIF_Success) return status; GIFImageDescriptor image; image.LeftPosition = 0; image.TopPosition = 0; image.Width = width; image.Height = height; image.PackedFields = 0; if (frame.ColorMapEntryCount > 0) { DWORD highest = highestBit(frame.ColorMapEntryCount); if (highest < 3) highest = 1; else highest -= 2; image.PackedFields |= GIFLocalMapPresent; image.PackedFields |= highest; // color table size } status = writeToFile(&image, sizeof(image)); if (status != GIF_Success) return status; if (frame.ColorMapEntryCount > 0) { DWORD entryCount = frame.ColorMapEntryCount; if (entryCount > 256) entryCount = 256; status = writeToFile(frame.ColorMap, entryCount * 3); if (status != GIF_Success) return status; } status = encodeStream(frame, top, left, width, height); if (status != GIF_Success) return status; ++m_FrameCount; return GIF_Success; }
bool Game::introStart() { initscr(); noecho(); nodelay(stdscr, true); curs_set(FALSE); start_color(); init_pair(1, COLOR_WHITE, COLOR_RED); init_pair(2, COLOR_GREEN, COLOR_GREEN); init_pair(3, COLOR_WHITE, COLOR_BLACK); getmaxyx(stdscr, parent_y, parent_x); vector<string> tempOne; vector<string> tempTwo; char animationOne[ROWS][COLUMNS] = {0}, animationTwo[ROWS][COLUMNS] = {0}; string tempStr = ""; ifstream file; ifstream file1; file.open("src/intro.txt"); file1.open("src/intro1.txt"); bool fileExists1 = false, fileExists2 = false; if(file.good()) { int counter = 0; while(getline(file, tempStr)) { tempOne.push_back(tempStr); } file.close(); fileExists1 = true; } else { writeToFile("intro.txt not found!\n"); } if(file1.good()) { while(getline(file1, tempStr)) { tempTwo.push_back(tempStr); } file1.close(); fileExists2 = true; } else { writeToFile("intro1.txt not found!\n"); } if(fileExists1 == true || fileExists2 == true) { for(int x = 0;x<tempOne.size();x++) { for(int y = 0;y<tempOne[x].length();y++) { animationOne[x][y] = tempOne[x][y]; animationTwo[x][y] = tempTwo[x][y]; } } bool animation = true; while(1) { bool loop = true; while(loop == true) { time_t newtime = time(NULL); char piece = ' '; if(DEBUG == true) writeToFile("Animation: %i | Time: %i > %i\n", animation, newtime, rawtime); for(int x = 0;x<ROWS;x++) { for(int y = 0;y<COLUMNS;y++) { wmove(stdscr, x, y); if(animation == true) { piece = animationOne[x][y]; } else if(animation == false) { piece = animationTwo[x][y]; } switch(piece) { //border case '+': case '-': case '|': waddch(stdscr, piece | COLOR_PAIR(1)); break; case '%': waddch(stdscr, piece | COLOR_PAIR(2)); break; case '#': case ' ': waddch(stdscr, piece); break; default: waddch(stdscr, piece | COLOR_PAIR(3)); break; } //waddch(stdscr, animationTwo[x][y]); } } if(newtime > rawtime) { writeToFile("animation = %i\n", animation); if(animation == true) animation = false; else if(animation == false) animation = true; rawtime = newtime; } char ch = getch(); switch(ch) { case '\n': loop = false; break; case KEY_UP: wrefresh(stdscr); default: break; } } break; } endwin(); Game::cursesMain(); } }
void JUnitTestOutput::writeProperties() { writeToFile("<properties>\n"); writeToFile("</properties>\n"); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QCommandLineParser cmdline; cmdline.setApplicationDescription("C++ type placeholder generator."); cmdline.addHelpOption(); QCommandLineOption inputHeader("i", QCoreApplication::translate("main", "Input header file name."), QCoreApplication::translate("main", "file name")); cmdline.addOption(inputHeader); QCommandLineOption dependencyInclude("d", QCoreApplication::translate("main", "Header included for depencencies."), QCoreApplication::translate("main", "file name")); cmdline.addOption(dependencyInclude); QCommandLineOption buildInclude("b", QCoreApplication::translate("main", "Header included for build."), QCoreApplication::translate("main", "file name[,file,...]")); cmdline.addOption(buildInclude); QCommandLineOption className("c", QCoreApplication::translate("main", "Input class name."), QCoreApplication::translate("main", "class name")); cmdline.addOption(className); QCommandLineOption outputSource("source", QCoreApplication::translate("main", "Output source file name."), QCoreApplication::translate("main", "file name")); cmdline.addOption(outputSource); QCommandLineOption outputHeader("header", QCoreApplication::translate("main", "Output header file name."), QCoreApplication::translate("main", "file name")); cmdline.addOption(outputHeader); QCommandLineOption outputClass("class", QCoreApplication::translate("main", "Output class name."), QCoreApplication::translate("main", "class name")); cmdline.addOption(outputClass); cmdline.process(a.arguments()); bool requiredGiven = true; if (!cmdline.isSet(inputHeader)) { requiredGiven = false; qWarning() << "Input header name must be given."; } if (!cmdline.isSet(className)) { requiredGiven = false; qWarning() << "Input class name must be given."; } if (!cmdline.isSet(outputSource)) { requiredGiven = false; qWarning() << "Output source file name must be given."; } if (!cmdline.isSet(outputHeader)) { requiredGiven = false; qWarning() << "Output header file name must be given."; } if (!cmdline.isSet(outputClass)) { requiredGiven = false; qWarning() << "Output class name must be given."; } if (!requiredGiven) return 5; QStringList listIn; QStringList listOut; listIn << "Q_OBJECT"; listOut << "Q_OBJECT;"; listIn << "Q_SLOTS"; listOut << "slots"; listIn << "Q_SIGNALS"; listOut << "signals"; ClassParser parser; parser.setPreDefines(listIn, listOut); SClassParserMacroBeginForMember sMacroBegin; sMacroBegin.m_bRequiresBrackets = true; sMacroBegin.m_strMacroBegin = "Q_REVISION"; parser.add(sMacroBegin); QString input = cmdline.value(inputHeader); QString inputClassName(cmdline.value(className)); ClassParserInformation *info = getClassInfo(input, inputClassName, parser); if (!info) { qWarning() << "No" << inputClassName << "info found in" << input; return 3; } QStringList buildIncludeList, dependencyIncludeList; if (cmdline.isSet(buildInclude)) buildIncludeList = cmdline.value(buildInclude).split(",", QString::SkipEmptyParts); if (cmdline.isSet(dependencyInclude)) dependencyIncludeList = cmdline.value(dependencyInclude).split(",", QString::SkipEmptyParts); QStringList header, source; QString headerName = cmdline.value(outputHeader); QString sourceName = cmdline.value(outputSource); QString outputClassName = cmdline.value(outputClass); if (!generateFileContents(header, source, inputClassName, outputClassName, dependencyIncludeList, buildIncludeList, headerName, *info)) { qWarning() << "Output files not generated."; return 4; } writeToFile(sourceName, source); writeToFile(headerName, header); return 0; }
// Call the private menber function writeToFile(). bool Storage::sync(void) { return writeToFile("agenda.data"); }
void DBConfigDialog::on_runButton_clicked() { bool isLocal; bool isDbExist = false; if(ui->cbImport->isChecked() && (ui->lePath->text().isEmpty() || !ui->lePath->text().contains(".sql"))) { QMessageBox::information(this,tr("Informacja"), tr("Nie poprawna scieżka do importu bazy danych.")); return; } setGrayOut(true); if(ui->rbLocalDB->isChecked()) { Database::purgeDatabase(); if(createMode){ if(ui->cbImport->isChecked()){ if(createDatabase("\"" + QDir::currentPath() + "\\\"" + "mysqlRun -h127.0.0.1 -P3306 -uroot -pPASSWORD -f"+importPath+"")) { QMessageBox::information(this,tr("Informacja"), tr("Baza danych już istnieje.")); isDbExist = true; } } else { if(createDatabase("\"" + QDir::currentPath() + "\\\"" + "mysqlRun -h127.0.0.1 -P3306 -uroot -pPASSWORD -dsigmacars")) { QMessageBox::information(this,tr("Informacja"), tr("Baza danych już istnieje.")); isDbExist = true; } } } Database::setParameters("127.0.0.1", 3306,"sigmacars", "root","PASSWORD"); isLocal = true; } else if (ui->rbRemoteDB->isChecked()) { if(dataIsEmpty()){ setGrayOut(false); return; } Database::purgeDatabase(); if(createMode){ if(ui->cbImport->isChecked()){ if(createDatabase("\"" + QDir::currentPath() + "\\\"" + "mysqlRun -h" + ui->leAddress->text() + " -P" + ui->lePort->text() + " -u" + ui->leUser->text() + " -p" + ui->lePassword->text() + " -f"+importPath)) { QMessageBox::information(this,tr("Informacja"), tr("Baza danych już istnieje.")); isDbExist = true; } } else { if(createDatabase("\"" + QDir::currentPath() + "\\\"" + "mysqlRun -h" + ui->leAddress->text() + " -P" + ui->lePort->text() + " -u" + ui->leUser->text() + " -p" + ui->lePassword->text() + " -dsigmacars")) { QMessageBox::information(this,tr("Informacja"), tr("Baza danych już istnieje.")); isDbExist = true; } } } Database::setParameters(ui->leAddress->text(), ui->lePort->text().toInt(),"sigmacars", ui->leUser->text(),ui->lePassword->text()); isLocal = false; } if(Database::connectToDatabase()) { if(!createMode)QMessageBox::information(this,tr("Informacja"), tr("Pomyślnie połączono z bazą danych.")); else if(isDbExist) QMessageBox::information(this,tr("Informacja"), tr("Pomyślnie połączono z bazą danych.")); else QMessageBox::information(this,tr("Informacja"), tr("Pomyślnie dodano bazę danych.")); if(isLocal) { if(!writeToFile("127.0.0.1", 3306, "sigmacars", "root","PASSWORD")) return; user="******"; password="******"; currentAddress="127.0.0.1"; } else { if(!writeToFile(ui->leAddress->text(), ui->lePort->text().toInt(), "sigmacars", ui->leUser->text(),ui->lePassword->text())) return; user=ui->leUser->text(); password=ui->lePassword->text(); currentAddress=ui->leAddress->text(); } setGrayOut(false); MainWindow::isDatabase = true; Database::isLocal = isLocal; emit connectedToDB(false); this->accept(); } else { QMessageBox::critical(this,tr("Błąd!"), tr("Nie połączono z bazą danych!")); setGrayOut(false); MainWindow::isDatabase = false; emit changeStatusBar("Nie można połączyć z bazą danych"); emit connectedToDB(false); return; } }
//------------------------------------------------------------------------------ // Reserve a section out of the output buffer for the application code to begin // using to store data destined for the database. // startRowId (in) - starting RID for the rows to be stored in this section // nRowsIn (in) - desired number of rows to be stored in this section // secRowCnt (out) - number of rows that the returned ColumnBufferSection can // hold. This may be smaller than nRowsIn (for dictionary // column) if the rows cross an extent boundary. // The application code will need to make a second call // later, to create a section to handle the remaining rows // that this section could not hold. // cbs (out) - reserved section pointer // lastInputRowInExtent(out) - last input Row number (relative to start of job) // that can go into the current extent we are loading. // // Basic algorithm: // 1. Wait to ensure that ColumnBufferSection allocations are made in input // row order // 2. Wait for any pending output buffer expansion to be completed // 3. If buffer does not have enough room to contain nRowsIn of data, then // a. If there are any ColumnBufferSections in use, then // wait for these ColumnBufferSections to be released // b. If there is any data in the output buffer, then // flush the data (rounded down to nearest 8192-byte block) // c. Expand the output buffer, and // copy the remaining data to the front of the newly expanded buffer // // @bug 3456 // Note that when determining whether the output buffer has enough room or // not, we are comparing to remainingSpace-1 and not remainingSpace. We // don't want output buffer to get completely full, because we can't // distinguish between a buffer that is full, and one that is empty; // as both cases are indicated by fBufFreeOffset == fBufWriteOffset. // If we allow output buffer to get exactly full, then we end up // losing track of data because we will think the buffer is empty. // // 6. Allocate new ColumnBufferSection // 7. Update fBufFreeOffset, fSectionsInUse, fMaxRowId //------------------------------------------------------------------------------ int ColumnBufferManager::reserveSection( RID startRowId, uint32_t nRowsIn, uint32_t& secRowCnt, ColumnBufferSection** cbs, RID& lastInputRowInExtent) { #ifdef PROFILE Stats::startParseEvent(WE_STATS_WAIT_TO_RESERVE_OUT_BUF); #endif *cbs = 0; boost::posix_time::seconds wait_seconds(COND_WAIT_SECONDS); boost::mutex::scoped_lock lock(fColInfo->colMutex()); //..Ensure that ColumnBufferSection allocations are made in input row order bool bWaitedForInSequence = false; while (1) { RID startRowTest = (std::numeric_limits<WriteEngine::RID>::max() == fMaxRowId) ? 0 : fMaxRowId + 1; if (startRowTest == startRowId) break; if (fLog->isDebug( DEBUG_3 )) { bWaitedForInSequence = true; std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Waiting for in-sequence"; fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } fOutOfSequence.timed_wait(lock, wait_seconds); // See if JobStatus has been set to terminate by another thread if (BulkStatus::getJobStatus() == EXIT_FAILURE) { throw SecondaryShutdownException( "ColumnBufferManager::" "reserveSection(1) responding to job termination"); } } if (fLog->isDebug( DEBUG_3 )) { if (bWaitedForInSequence) { std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Resume after waiting for in-sequence"; fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } } //..Check/wait for any pending output buffer expansion to be completed bool bWaitedForResize = false; while (fResizePending) { if (fLog->isDebug( DEBUG_3 )) { bWaitedForResize = true; std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Waiting for pending resize"; fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } fResizeInProgress.timed_wait(lock, wait_seconds); // See if JobStatus has been set to terminate by another thread if (BulkStatus::getJobStatus() == EXIT_FAILURE) { throw SecondaryShutdownException( "ColumnBufferManager::" "reserveSection(2) responding to job termination"); } } if (fLog->isDebug( DEBUG_3 )) { if (bWaitedForResize) { std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Resume after waiting for pending resize"; fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } } #ifdef PROFILE Stats::stopParseEvent(WE_STATS_WAIT_TO_RESERVE_OUT_BUF); #endif // Through the use of the mutex lock and the fResizePending flag, nobody // should be changing the buffer size out from under us; so okay to save in // local variable till we call resizeColumnBuffer() to expand the buffer. int bufferSize = fCBuf->getSize(); int remainingSpace = 0; if(bufferSize > 0) { //Calculate remaining space remainingSpace = bufferSize - (fBufFreeOffset + bufferSize - fBufWriteOffset) % bufferSize; } //..Restrict the new section to the extent boundary if applicable. // We assume here that the colMutex() lock will assure the integrity // of the values used in evaluating or recalculating spaceRequired. int nRows = 0; RETURN_ON_ERROR( rowsExtentCheck( nRowsIn, nRows ) ); int spaceRequired = nRows * fColWidth; if (nRows > 0) { //..If not enough room to add nRows to output buffer, wait for pending // sections to be released, so that we can flush and resize the buffer. //..@bug 3456: compare to remainingSpace-1 and not remainingSpace. // See note in function description that precedes this function. if (spaceRequired > (remainingSpace-1)) { //#ifdef PROFILE // Stats::startParseEvent(WE_STATS_WAIT_TO_RESIZE_OUT_BUF); //#endif fResizePending = true; bool bWaitedForSectionsInUse = false; // Wait for all other threads to finish writing pending sections // to the output buffer, before we resize the buffer while(fSectionsInUse.size() > 0) { if (fLog->isDebug( DEBUG_3 )) { bWaitedForSectionsInUse = true; std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Waiting to resize output buffer; " "sections in-use: " << fSectionsInUse.size(); fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } fBufInUse.timed_wait(lock, wait_seconds); // See if JobStatus has been set to quit by another thread if (BulkStatus::getJobStatus() == EXIT_FAILURE) { throw SecondaryShutdownException( "ColumnBufferManager::" "reserveSection(3) responding to job termination"); } } //#ifdef PROFILE // Stats::stopParseEvent(WE_STATS_WAIT_TO_RESIZE_OUT_BUF); // Stats::startParseEvent(WE_STATS_RESIZE_OUT_BUF); //#endif if (fLog->isDebug( DEBUG_3 )) { if (bWaitedForSectionsInUse) { std::ostringstream oss; oss << "OID-" << fColInfo->curCol.dataFile.fid << "; Resume after waiting to resize output buffer"; fLog->logMsg( oss.str(), MSGLVL_INFO2 ); } } // @bug 1977 correct problem; writing extra blocks // Flush remaining data blocks to disk "if" buffer contains data if(bufferSize > 0) { if (fBufFreeOffset != fBufWriteOffset) RETURN_ON_ERROR( writeToFile( (fBufFreeOffset + bufferSize - 1)%bufferSize) ); } resizeColumnBuffer(spaceRequired); bufferSize = fCBuf->getSize(); // update bufferSize after resize- // ColumnBuffer() expanded the buffer fResizePending = false; fResizeInProgress.notify_all(); //#ifdef PROFILE // Stats::stopParseEvent(WE_STATS_RESIZE_OUT_BUF); //#endif } // (spaceRequired > remainingSpace-1) *cbs = new ColumnBufferSection( fCBuf, startRowId, startRowId + nRows - 1, fColWidth, fBufFreeOffset); fBufFreeOffset = (fBufFreeOffset + nRows * fColWidth) % bufferSize; fSectionsInUse.push_back(*cbs); fMaxRowId = startRowId + nRows - 1; fOutOfSequence.notify_all(); } // (nRows > 0) secRowCnt = nRows; // Get/return last input Row number for the extent this buffer goes in. // If we determine this set of rows will cross over to the next extent, // then we tell ColumnInfo to bump the last Row to the end of the next // extent, in preparation for the next Read buffer going into the next // extent. We do this even though we have not yet allocated the next // extent from the extent map. lastInputRowInExtent = fColInfo->lastInputRowInExtent( ); if ((startRowId + nRowsIn) > lastInputRowInExtent) fColInfo->lastInputRowInExtentInc( ); return NO_ERROR; }
/** * Handle a new connection * * @param {int} newSocketFd */ void handleConnection(int newSocketFd) { char ioBuffer[256]; memset(ioBuffer, '\0', 256); // reset the ioBuffer for i/o attemptRead(newSocketFd, ioBuffer, 255); printf("Before call to isValidClientId(), "); printClients(); int clientId = atoi(ioBuffer); int isValidId = isValidClientId(clientId); printf("Checking for valid client id...\n"); if (isValidId == 0) { attemptWrite(newSocketFd, INVALID_CLIENT_ID, strlen(INVALID_CLIENT_ID)); return; } else { attemptWrite(newSocketFd, VALID_CLIENT_ID, strlen(VALID_CLIENT_ID)); memset(ioBuffer, '\0', 256); // reset the ioBuffer for i/o attemptRead(newSocketFd, ioBuffer, 255); printf("%s\n", ioBuffer); // print client id response message from client addClient(clientId); printf("After call to addClient(), "); printClients(); attemptWrite(newSocketFd, WELCOME_MESSAGE, strlen(WELCOME_MESSAGE)); printf("New client #%d\n", clientId); while (1) { printf("Waiting for command from client #%d...\n", clientId); char opFile[256]; // read opFile from client memset(ioBuffer, '\0', 256); // reset the ioBuffer for i/o attemptRead(newSocketFd, ioBuffer, 255); strcpy(opFile, ioBuffer); // if client requests, end session if (strcmp(ioBuffer, END_SESSION) == 0) { printf("Terminating client #%d\n", clientId); removeClient(clientId); return; } // otherwise, send continue response attemptWrite(newSocketFd, CONTINUE, strlen(CONTINUE)); // read opCode from client memset(ioBuffer, '\0', 256); // reset the ioBuffer for i/o attemptRead(newSocketFd, ioBuffer, 255); // proceed based on opCode if (strcmp(ioBuffer, PROCESS_READ) == 0) { printf("Processing read for file: `%s`\n", opFile); readFile(opFile, newSocketFd); // send file to client } else if (strcmp(ioBuffer, PROCESS_WRITE) == 0) { printf("Processing write for file: `%s`\n", opFile); attemptWrite(newSocketFd, CONTINUE, strlen(CONTINUE)); memset(ioBuffer, '\0', 256); attemptRead(newSocketFd, ioBuffer, 255); // read file contents writeToFile(opFile, ioBuffer); } } } }
bool Storage::sync(void) { bool judge = writeToFile("./"); return judge; }
// // write struct to file // this is just used for dbging // void write_entries_to_file(FILE *output, dbEntries *self) { for (unsigned int i=0; i<self->numEntries; i++) { writeToFile(output, self->entries[i]); } }
void EditorMenuManager::saveData() { auto floatObject = Float::create(0.0f); auto root = Dictionary::create(); auto string = String::create("string element value"); root->setObject(string, "string element key"); #pragma mark INPUT auto player = dynamic_cast<GameLogic*>(getParent())->getPlayer(); auto inputDict = Dictionary::create(); auto inputMenu = dynamic_cast<InputMenuItem*>(this->getChildByTag(INPUT_MENU)); if (player && inputMenu) { auto horizontalImpulse = dynamic_cast<cocos2d::extension::ControlSlider*>(inputMenu->getChildByTag(TYPE_INPUT_HORIZONTAL_IMPULSE)); floatObject = Float::create(horizontalImpulse->getValue()); inputDict->setObject(floatObject, "horizontalImpulse"); auto verticalImpulse = dynamic_cast<cocos2d::extension::ControlSlider*>(inputMenu->getChildByTag(TYPE_INPUT_VERTICAL_IMPULSE)); floatObject = Float::create(verticalImpulse->getValue()); inputDict->setObject(floatObject, "verticalImpulse"); auto horizontalLimit = dynamic_cast<cocos2d::extension::ControlSlider*>(inputMenu->getChildByTag(TYPE_INPUT_HORIZONTAL_LIMIT)); floatObject = Float::create(horizontalLimit->getValue()); inputDict->setObject(floatObject, "horizontalLimit"); } else { auto value = Utility::loadDataFromFile("Input", "horizontalImpulse", "0.3"); floatObject = Float::create(atof(value->getCString())); inputDict->setObject(floatObject, "horizontalImpulse"); value = Utility::loadDataFromFile("Input", "verticalImpulse", "12.35"); floatObject = Float::create(atof(value->getCString())); inputDict->setObject(floatObject, "verticalImpulse"); value = Utility::loadDataFromFile("Input", "horizontalLimit", "8.0"); floatObject = Float::create(atof(value->getCString())); inputDict->setObject(floatObject, "horizontalLimit"); } root->setObject(inputDict, "Input"); #pragma mark SHEEP auto sheepDict = Dictionary::create(); auto sheepMenu = dynamic_cast<SheepMenuItem*>(this->getChildByTag(SHEEP_MENU)); if (sheepMenu) { auto sheepHorizontalImpulse = dynamic_cast<cocos2d::extension::ControlSlider*>(sheepMenu->getChildByTag(TYPE_SHEEP_HORIZONTAL_IMPULSE)); floatObject = Float::create(sheepHorizontalImpulse->getValue()); sheepDict->setObject(floatObject, "horizontalImpulse"); auto sheepVerticalImpulse = dynamic_cast<cocos2d::extension::ControlSlider*>(sheepMenu->getChildByTag(TYPE_SHEEP_VERTICAL_IMPULSE)); floatObject = Float::create(sheepVerticalImpulse->getValue()); sheepDict->setObject(floatObject, "verticalImpulse"); auto sheepHorizontalLimit = dynamic_cast<cocos2d::extension::ControlSlider*>(sheepMenu->getChildByTag(TYPE_SHEEP_HORIZONTAL_LIMIT)); floatObject = Float::create(sheepHorizontalLimit->getValue()); sheepDict->setObject(floatObject, "horizontalLimit"); auto sheepDistance = dynamic_cast<cocos2d::extension::ControlSlider*>(sheepMenu->getChildByTag(TYPE_SHEEP_DISTANCE)); floatObject = Float::create(sheepDistance->getValue()); sheepDict->setObject(floatObject, "sheepDistance"); } else { auto value = Utility::loadDataFromFile("Sheep", "horizontalImpulse", "0.5"); floatObject = Float::create(atof(value->getCString())); sheepDict->setObject(floatObject, "horizontalImpulse"); value = Utility::loadDataFromFile("Sheep", "verticalImpulse", "8.4"); floatObject = Float::create(atof(value->getCString())); sheepDict->setObject(floatObject, "verticalImpulse"); value = Utility::loadDataFromFile("Sheep", "horizontalLimit", "6.0"); floatObject = Float::create(atof(value->getCString())); sheepDict->setObject(floatObject, "horizontalLimit"); value = Utility::loadDataFromFile("Sheep", "sheepDistance", "0.2"); floatObject = Float::create(atof(value->getCString())); sheepDict->setObject(floatObject, "sheepDistance"); } root->setObject(sheepDict, "Sheep"); #pragma mark NOTE auto noteDict = Dictionary::create(); auto noteMenu = dynamic_cast<NoteMenuItem*>(this->getChildByTag(NOTE_MENU)); if (noteMenu) { auto noteDistance = dynamic_cast<cocos2d::extension::ControlSlider*>(noteMenu->getChildByTag(TYPE_NOTE_DISTANCE)); floatObject = Float::create(noteDistance->getValue()); noteDict->setObject(floatObject, "noteDistance"); auto particleScale = dynamic_cast<cocos2d::extension::ControlSlider*>(noteMenu->getChildByTag(TYPE_PARTICLE_SCALE)); floatObject = Float::create(particleScale->getValue()); noteDict->setObject(floatObject, "particleScale"); auto sheepPanDistanceScale = dynamic_cast<cocos2d::extension::ControlSlider*>(noteMenu->getChildByTag(TYPE_SHEEP_PAN_DISTANCE)); floatObject = Float::create(sheepPanDistanceScale->getValue()); noteDict->setObject(floatObject, "sheepPanDistance"); auto noteDurationScale = dynamic_cast<cocos2d::extension::ControlSlider*>(noteMenu->getChildByTag(TYPE_NOTE_DURATION)); floatObject = Float::create(noteDurationScale->getValue()); noteDict->setObject(floatObject, "noteDuration"); } else { auto value = Utility::loadDataFromFile("Note", "noteDistance", "9.5"); floatObject = Float::create(atof(value->getCString())); noteDict->setObject(floatObject, "noteDistance"); value = Utility::loadDataFromFile("Note", "particleScale", "1.25"); floatObject = Float::create(atof(value->getCString())); noteDict->setObject(floatObject, "particleScale"); value = Utility::loadDataFromFile("Note", "sheepPanDistance", "1.5"); floatObject = Float::create(atof(value->getCString())); noteDict->setObject(floatObject, "sheepPanDistance"); value = Utility::loadDataFromFile("Note", "noteDuration", "10.0"); floatObject = Float::create(atof(value->getCString())); noteDict->setObject(floatObject, "noteDuration"); } root->setObject(noteDict, "Note"); #pragma mark GOATSKIN auto goatskinDict = Dictionary::create(); auto goatskinMenu = dynamic_cast<GoatskinMenuItem*>(this->getChildByTag(GOATSKIN_MENU)); if (goatskinMenu) { auto goatskinRange = dynamic_cast<cocos2d::extension::ControlSlider*>(goatskinMenu->getChildByTag(TYPE_GOATSKIN_RANGE)); floatObject = Float::create(goatskinRange->getValue()); goatskinDict->setObject(floatObject, "range"); } else { auto value = Utility::loadDataFromFile("Goatskin", "range", "200.0"); floatObject = Float::create(atof(value->getCString())); goatskinDict->setObject(floatObject, "range"); } root->setObject(goatskinDict, "Goatskin"); std::string writablePath = FileUtils::getInstance()->getWritablePath(); std::string fullPath = writablePath + "SOP.plist"; root->writeToFile(fullPath.c_str()); }
int main(int argc, char **argv) { int my_rank=0; /* My process rank */ int p; /* The number of processes */ //clock time recording variables double start_time,end_time,comm_time_start,comm_time_end,total_comm_time=0.0; /* Let the system do what it needs to start up MPI */ MPI_Init(&argc, &argv); /* Get my process rank */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); /* Find out how many processes are being used */ MPI_Comm_size(MPI_COMM_WORLD, &p); float dataA[N][N], dataB[N][N]; complex A[N][N], B[N][N]; //create MPI type for complex datatype MPI_Aint displ[2]; displ[0] = 0; displ[1] = sizeof(float); MPI_Datatype mpi_complex,types[2]; types[0] = MPI_FLOAT; types[1] = MPI_FLOAT; int block_len[2]; block_len[0]= 1; block_len[1]= 1; MPI_Type_struct(2, block_len, displ, types,&mpi_complex); MPI_Type_commit(&mpi_complex); //create 4 communicators by splitting the default one MPI_Comm new_comm; /* Find out how many processes are being used */ int color = my_rank / 2; MPI_Comm_split(MPI_COMM_WORLD, color, my_rank, &new_comm); int row_rank, row_size; MPI_Comm_rank(new_comm, &row_rank); MPI_Comm_size(new_comm, &row_size); //we will read the files by corresponding processes if(my_rank==0) { readFromFile("data/1_im1", dataA); convertToComplex(A, dataA); } else if(my_rank==2) { readFromFile("data/1_im2", dataB); convertToComplex(B, dataB); } if(my_rank==6) { //Start clock and record the start time. start_time = MPI_Wtime(); } int local_n = N/row_size; int rows_per_process = N/row_size; complex local_A[N/row_size][N]; complex local_B[N/row_size][N]; //broadcast the number of ros each process will work on MPI_Bcast(&rows_per_process , 1, MPI_INT, 0,MPI_COMM_WORLD); //process 0 and 1 work on Matrix A if(my_rank<2) { if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_fft2d(&local_A[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_A, N*rows_per_process, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } if(row_rank==0) transpose(A); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_fft2d(&local_A[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_A, N*rows_per_process, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } MPI_Barrier(new_comm); if(row_rank==0) { transpose(A); comm_time_start=MPI_Wtime(); //send the intermediate matrix to process 4 MPI_Send(A, N*N, mpi_complex, 4,11,MPI_COMM_WORLD); comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } } if(my_rank>=2 && my_rank<4) //process 2 and 3 work on Matrix B { //printf(" %d ",rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&B[0][0], N*rows_per_process, mpi_complex, &local_B, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_fft2d(&local_B[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_B, N*local_n, mpi_complex, &B[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } if(row_rank==0) transpose(B); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&B[0][0], N*rows_per_process, mpi_complex, &local_B, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_fft2d(&local_B[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_B, N*local_n, mpi_complex, &B[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } MPI_Barrier(new_comm); if(row_rank==0) { transpose(B); //lets send intermediate matrix B to process 4 MPI_Send(B, N*N, mpi_complex, 4, 12,MPI_COMM_WORLD); } } if(my_rank==4) //process 4 multiplies the two matrices { MPI_Status status; comm_time_start=MPI_Wtime(); MPI_Recv(A, N*N, mpi_complex, 0, 11, MPI_COMM_WORLD, &status); MPI_Recv(B, N*N, mpi_complex, 2, 12, MPI_COMM_WORLD, &status); comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; mmul_point(A,B); if(row_rank==0) { comm_time_start=MPI_Wtime(); MPI_Send(A, N*N, mpi_complex, 6, 13,MPI_COMM_WORLD); comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } } if(my_rank>=6 && my_rank<8) //process 6 and 7 does inverse transform on result { MPI_Status status; if(row_rank==0) { comm_time_start=MPI_Wtime(); MPI_Recv(A, N*N, mpi_complex, 4, 13, MPI_COMM_WORLD, &status); comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_inv_fft2d(&local_A[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_A, N*rows_per_process, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } if(row_rank==0) transpose(A); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } c_rowwise_inv_fft2d(&local_A[0][0],rows_per_process); if(row_rank==0) { comm_time_start=MPI_Wtime(); } MPI_Gather(&local_A, N*rows_per_process, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, new_comm); if(row_rank==0) { comm_time_end=MPI_Wtime(); total_comm_time+=comm_time_end-comm_time_start; } if(row_rank==0) { transpose(A); //Stop clock as operation is finished. end_time = MPI_Wtime(); //print the execution time for performance analysis purpose. printf("\n\nThe total execution time as recorded on process 0 = %f seconds!!\n!",end_time-start_time); convertToReal(dataA,A); writeToFile("final_output.txt", dataA); } } MPI_Barrier(MPI_COMM_WORLD); //get a total of communication cost recorded by all processes MPI_Reduce(&total_comm_time, &total_comm_time, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); if(my_rank ==0) { printf("\n\nThe total Communication time = %f seconds!!\n!",total_comm_time); } MPI_Comm_free(&new_comm); MPI_Finalize(); return 0; }
static bool writeTime(PlatformFileHandle file, const time_t& time) { return writeToFile(file, reinterpret_cast<const char*>(&time), sizeof(time_t)) == sizeof(time_t); }
static bool writeUTF8String(PlatformFileHandle file, const String& string) { CString utf8String = string.utf8(); int length = utf8String.length() + 1; return writeToFile(file, utf8String.data(), length) == length; }
void mw::XMLParserTestFixture::testLoadDictionaryInDictionary() { CPPUNIT_ASSERT(testVar->getValue().getFloat() == 0.0); const char *xml_text = "<?xml version=\"1.0\"?>" "<monkeyml version=\"1.1\">" " <variable_assignments>" " <variable_assignment variable=\"testVar\">" " <dictionary>" " <dictionary_element>" " <key>one</key>" " <value>" " <dictionary>" " <dictionary_element>" " <key>four</key>" " <value type=\"integer\">14</value>" " </dictionary_element>" " <dictionary_element>" " <key>six</key>" " <value type=\"integer\">16</value>" " </dictionary_element>" " </dictionary>" " </value>" " </dictionary_element>" " <dictionary_element>" " <key>two</key>" " <value>" " <dictionary>" " <dictionary_element>" " <key>four</key>" " <value type=\"integer\">24</value>" " </dictionary_element>" " <dictionary_element>" " <key>six</key>" " <value type=\"integer\">26</value>" " </dictionary_element>" " </dictionary>" " </value>" " </dictionary_element>" " </dictionary>" " </variable_assignment>" " </variable_assignments>" "</monkeyml>"; writeToFile(xml_text); mw::VariableLoad::loadExperimentwideVariables(temp_xml_file_path); mw::Data sub_dict1(M_DICTIONARY, 2); sub_dict1.addElement("four", mw::Data(14L)); sub_dict1.addElement("six", mw::Data(16L)); mw::Data sub_dict2(M_DICTIONARY, 2); sub_dict2.addElement("four", mw::Data(24L)); sub_dict2.addElement("six", mw::Data(26L)); mw::Data main_dict(M_DICTIONARY, 2); main_dict.addElement("one", sub_dict1); main_dict.addElement("two", sub_dict2); CPPUNIT_ASSERT(testVar->getValue() == main_dict); }
void Cvode::solve(const SOLVERCALL action) { bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeSolveFunctionHandler, "solve"); if(MeasureTime::getInstance() != NULL) { MEASURETIME_START(solveFunctionStartValues, cvodeSolveFunctionHandler, "solve"); } #endif if (_cvodesettings && _system) { // Solver und System für Integration vorbereiten if ((action & RECORDCALL) && (action & FIRST_CALL)) { #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeInitializeHandler, "CVodeInitialize"); if(MeasureTime::getInstance() != NULL) { MEASURETIME_START(measuredFunctionStartValues, cvodeInitializeHandler, "CVodeInitialize"); } #endif initialize(); #ifdef RUNTIME_PROFILING if(MeasureTime::getInstance() != NULL) { MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[4], cvodeInitializeHandler); } #endif if (writeOutput) writeToFile(0, _tCurrent, _h); _tLastWrite = 0; return; } if ((action & RECORDCALL) && !(action & FIRST_CALL)) { writeToFile(_accStps, _tCurrent, _h); return; } // Nach einem TimeEvent wird der neue Zustand recorded if (action & RECALL) { _firstStep = true; if (writeEventOutput) writeToFile(0, _tCurrent, _h); if (writeOutput) writeCVodeOutput(_tCurrent, _h, _locStps); _continuous_system->getContinuousStates(_z); } // Solver soll fortfahren _solverStatus = ISolver::CONTINUE; while ((_solverStatus & ISolver::CONTINUE) && !_interrupt ) { // Zuvor wurde initialize aufgerufen und hat funktioniert => RESET IDID if (_idid == 5000) _idid = 0; // Solveraufruf if (_idid == 0) { // Zähler zurücksetzen _accStps = 0; _locStps = 0; // Solverstart CVodeCore(); } // Integration war nicht erfolgreich und wurde auch nicht vom User unterbrochen if (_idid != 0 && _idid != 1) { _solverStatus = ISolver::SOLVERERROR; //throw ModelicaSimulationError(SOLVER,_idid,_tCurrent,"CVode::solve()"); throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } // Abbruchkriterium (erreichen der Endzeit) else if ((_tEnd - _tCurrent) <= dynamic_cast<ISolverSettings*>(_cvodesettings)->getEndTimeTol()) _solverStatus = DONE; } _firstCall = false; } else { throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } #ifdef RUNTIME_PROFILING if(MeasureTime::getInstance() != NULL) { MEASURETIME_END(solveFunctionStartValues, solveFunctionEndValues, (*measureTimeFunctionsArray)[1], cvodeSolveFunctionHandler); long int nst, nfe, nsetups, netf, nni, ncfn; int qlast, qcur; realtype h0u, hlast, hcur, tcur; int flag; flag = CVodeGetIntegratorStats(_cvodeMem, &nst, &nfe, &nsetups, &netf, &qlast, &qcur, &h0u, &hlast, &hcur, &tcur); flag = CVodeGetNonlinSolvStats(_cvodeMem, &nni, &ncfn); MeasureTimeValuesSolver solverVals = MeasureTimeValuesSolver(nfe, netf); (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->_numCalcs += nst; (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->add(&solverVals); } #endif }
void init_file(FILE* src){ if ( (src = fopen("/ISG/uart/port4.txt", "w+") ) < 0) {exit(FILE_ERROR);} writeToFile(src, "init log file\n"); fclose(src); }
void Cvode::CVodeCore() { _idid = CVodeReInit(_cvodeMem, _tCurrent, _CV_y); _idid = CVodeSetStopTime(_cvodeMem, _tEnd); _idid = CVodeSetInitStep(_cvodeMem, 1e-12); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::ReInit"); bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); while ((_solverStatus & ISolver::CONTINUE) && !_interrupt ) { _cv_rt = CVode(_cvodeMem, _tEnd, _CV_y, &_tCurrent, CV_ONE_STEP); _idid = CVodeGetNumSteps(_cvodeMem, &_locStps); if (_idid != CV_SUCCESS) throw ModelicaSimulationError(SOLVER,"CVodeGetNumSteps failed. The cvode mem pointer is NULL"); _idid = CVodeGetLastStep(_cvodeMem, &_h); if (_idid != CV_SUCCESS) throw ModelicaSimulationError(SOLVER,"CVodeGetLastStep failed. The cvode mem pointer is NULL"); //set completed step to system and check if terminate was called if(_continuous_system->stepCompleted(_tCurrent)) _solverStatus = DONE; //Check if there was at least one output-point within the last solver interval // -> Write output if true if (writeOutput) { writeCVodeOutput(_tCurrent, _h, _locStps); } #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeStepCompletedHandler, "CVodeStepCompleted"); if(MeasureTime::getInstance() != NULL) { MEASURETIME_START(measuredFunctionStartValues, cvodeStepCompletedHandler, "CVodeStepCompleted"); } #endif #ifdef RUNTIME_PROFILING if(MeasureTime::getInstance() != NULL) { MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[5], cvodeStepCompletedHandler); } #endif // Perform state selection bool state_selection = stateSelection(); if (state_selection) _continuous_system->getContinuousStates(_z); _zeroFound = false; // Check if step was successful if (check_flag(&_cv_rt, "CVode", 1)) { _solverStatus = ISolver::SOLVERERROR; break; } // A root was found if ((_cv_rt == CV_ROOT_RETURN) && !isInterrupted()) { // CVode is setting _tCurrent to the time where the first event occurred double _abs = fabs(_tLastEvent - _tCurrent); _zeroFound = true; if ((_abs < 1e-3) && _event_n == 0) { _tLastEvent = _tCurrent; _event_n++; } else if ((_abs < 1e-3) && (_event_n >= 1 && _event_n < 500)) { _event_n++; } else if ((_abs >= 1e-3)) { //restart event counter _tLastEvent = _tCurrent; _event_n = 0; } else throw ModelicaSimulationError(EVENT_HANDLING,"Number of events exceeded in time interval " + to_string(_abs) + " at time " + to_string(_tCurrent)); // CVode has interpolated the states at time 'tCurrent' _time_system->setTime(_tCurrent); // To get steep steps in the result file, two value points (P1 and P2) must be added // // Y | (P2) X........... // | : // | : // |........X (P1) // |----------------------------------> // | ^ t // _tCurrent // Write the values of (P1) if (writeEventOutput) { _continuous_system->evaluateAll(IContinuous::CONTINUOUS); writeToFile(0, _tCurrent, _h); } _idid = CVodeGetRootInfo(_cvodeMem, _zeroSign); for (int i = 0; i < _dimZeroFunc; i++) _events[i] = bool(_zeroSign[i]); if (_mixed_system->handleSystemEvents(_events)) { // State variables were reinitialized, thus we have to give these values to the cvode-solver // Take care about the memory regions, _z is the same like _CV_y _continuous_system->getContinuousStates(_z); } } if ((_zeroFound || state_selection)&& !isInterrupted()) { // Write the values of (P2) if (writeEventOutput) { // If we want to write the event-results, we should evaluate the whole system again _continuous_system->evaluateAll(IContinuous::CONTINUOUS); writeToFile(0, _tCurrent, _h); } _idid = CVodeReInit(_cvodeMem, _tCurrent, _CV_y); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::ReInit()"); // Der Eventzeitpunkt kann auf der Endzeit liegen (Time-Events). In diesem Fall wird der Solver beendet, da CVode sonst eine interne Warnung schmeißt if (_tCurrent == _tEnd) _cv_rt = CV_TSTOP_RETURN; if(_continuous_system->stepCompleted(_tCurrent)) _solverStatus = DONE; } // Zähler für die Anzahl der ausgegebenen Schritte erhöhen ++_outStps; _tLastSuccess = _tCurrent; if (_cv_rt == CV_TSTOP_RETURN) { _time_system->setTime(_tEnd); //Solver has finished calculation - calculate the final values _continuous_system->setContinuousStates(NV_DATA_S(_CV_y)); _continuous_system->evaluateAll(IContinuous::CONTINUOUS); if(writeOutput) writeToFile(0, _tEnd, _h); _accStps += _locStps; _solverStatus = DONE; } } }
/* Process the content data. Returns < 0 on error == 0 when more data is needed == 1 when data successfully written */ static int processUploadData(HttpQueue *q) { HttpConn *conn; HttpPacket *packet; MprBuf *content; Upload *up; ssize size, dataLen; bool pureData; char *data, *bp, *key; conn = q->conn; up = q->queueData; content = q->first->content; packet = 0; size = mprGetBufLength(content); if (size < up->boundaryLen) { /* Incomplete boundary. Return and get more data */ return 0; } bp = getBoundary(mprGetBufStart(content), size, up->boundary, up->boundaryLen, &pureData); if (bp == 0) { if (up->clientFilename) { /* No signature found yet. probably more data to come. Must handle split boundaries. */ data = mprGetBufStart(content); dataLen = pureData ? size : (size - (up->boundaryLen - 1)); if (dataLen > 0) { if (writeToFile(q, mprGetBufStart(content), dataLen) < 0) { return MPR_ERR_CANT_WRITE; } } mprAdjustBufStart(content, dataLen); return 0; /* Get more data */ } } data = mprGetBufStart(content); dataLen = (bp) ? (bp - data) : mprGetBufLength(content); if (dataLen > 0) { mprAdjustBufStart(content, dataLen); /* This is the CRLF before the boundary */ if (dataLen >= 2 && data[dataLen - 2] == '\r' && data[dataLen - 1] == '\n') { dataLen -= 2; } if (up->clientFilename) { /* Write the last bit of file data and add to the list of files and define environment variables */ if (writeToFile(q, data, dataLen) < 0) { return MPR_ERR_CANT_WRITE; } defineFileFields(q, up); } else { /* Normal string form data variables */ data[dataLen] = '\0'; #if KEEP httpTrace(conn, "request.upload.variables", "context", "'%s':'%s'", up->name, data); #endif key = mprUriDecode(up->name); data = mprUriDecode(data); httpSetParam(conn, key, data); if (packet == 0) { packet = httpCreatePacket(ME_MAX_BUFFER); } if (httpGetPacketLength(packet) > 0) { /* Need to add www-form-urlencoding separators */ mprPutCharToBuf(packet->content, '&'); } else { conn->rx->mimeType = sclone("application/x-www-form-urlencoded"); } mprPutToBuf(packet->content, "%s=%s", up->name, data); } } if (up->clientFilename) { /* Now have all the data (we've seen the boundary) */ mprCloseFile(up->file); up->file = 0; up->clientFilename = 0; } if (packet) { httpPutPacketToNext(q, packet); } up->contentState = HTTP_UPLOAD_BOUNDARY; return 0; }
Statistic::~Statistic() { if (config->has(opt::server::performance_log)) writeToFile(config->get<string>(opt::server::performance_log).c_str()); }
int main (int argc, char* argv[]) { ApplicationsLib::LogogSetup logog_setup; TCLAP::CmdLine cmd("Computes ids of mesh nodes that are in polygonal " "regions and resides on the top surface. The polygonal regions have to " "be given in a gml- or gli-file. The found mesh nodes and the associated" " area are written as txt and csv data." "The documentation is available at https://docs.opengeosys.org/docs/tools/model-preparation/computesurfacenodeidsinpolygonalregion", ' ', "0.1"); TCLAP::ValueArg<std::string> mesh_in("m", "mesh-input-file", "the name of the file containing the input mesh", true, "", "file name of input mesh"); cmd.add(mesh_in); TCLAP::ValueArg<std::string> geo_in("g", "geo-file", "the name of the gml file containing the polygons", true, "", "file name of input geometry"); cmd.add(geo_in); cmd.parse(argc, argv); std::unique_ptr<MeshLib::Mesh const> mesh(MeshLib::IO::readMeshFromFile(mesh_in.getValue())); INFO("Mesh read: %u nodes, %u elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); GeoLib::GEOObjects geo_objs; GeoLib::IO::readGeometryFromFile(geo_in.getValue(), geo_objs); std::vector<std::string> geo_names; geo_objs.getGeometryNames(geo_names); INFO("Geometry \"%s\" read: %u points, %u polylines.", geo_names[0].c_str(), geo_objs.getPointVec(geo_names[0])->size(), geo_objs.getPolylineVec(geo_names[0])->size()); MathLib::Vector3 const dir(0.0, 0.0, -1.0); double angle(90); auto computeElementTopSurfaceAreas = [](MeshLib::Mesh const& mesh, MathLib::Vector3 const& d, double angle) { std::unique_ptr<MeshLib::Mesh> surface_mesh( MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, d, angle)); return MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes( *surface_mesh.get()); }; std::vector<double> areas(computeElementTopSurfaceAreas(*mesh, dir, angle)); std::vector<GeoLib::Point*> all_sfc_pnts( MeshLib::MeshSurfaceExtraction::getSurfaceNodes(*mesh, dir, angle) ); std::for_each(all_sfc_pnts.begin(), all_sfc_pnts.end(), [](GeoLib::Point* p) { (*p)[2] = 0.0; }); std::vector<MeshLib::Node*> const& mesh_nodes(mesh->getNodes()); GeoLib::PolylineVec const* ply_vec( geo_objs.getPolylineVecObj(geo_names[0]) ); std::vector<GeoLib::Polyline*> const& plys(*(ply_vec->getVector())); for (std::size_t j(0); j<plys.size(); j++) { if (! plys[j]->isClosed()) { continue; } std::string polygon_name; ply_vec->getNameOfElement(plys[j], polygon_name); if (polygon_name.empty()) polygon_name = "Polygon-" + std::to_string(j); // create Polygon from Polyline GeoLib::Polygon const& polygon(*(plys[j])); // ids of mesh nodes on surface that are within the given polygon std::vector<std::pair<std::size_t, double>> ids_and_areas; for (std::size_t k(0); k<all_sfc_pnts.size(); k++) { GeoLib::Point const& pnt(*(all_sfc_pnts[k])); if (polygon.isPntInPolygon(pnt)) { ids_and_areas.push_back(std::make_pair(pnt.getID(), areas[k])); } } if (ids_and_areas.empty()) { ERR("Polygonal part of surface \"%s\" doesn't contains nodes. No " "output will be generated.", polygon_name.c_str()); continue; } std::string const out_path(BaseLib::extractPath(geo_in.getValue())); std::string id_and_area_fname(out_path + polygon_name); std::string csv_fname(out_path + polygon_name); id_and_area_fname += std::to_string(j) + ".txt"; csv_fname += std::to_string(j) + ".csv"; INFO("Polygonal part of surface \"%s\" contains %ul nodes. Writting to" " files \"%s\" and \"%s\".", polygon_name.c_str(), ids_and_areas.size(), id_and_area_fname.c_str(), csv_fname.c_str() ); writeToFile(id_and_area_fname, csv_fname, ids_and_areas, mesh_nodes); } std::for_each(all_sfc_pnts.begin(), all_sfc_pnts.end(), std::default_delete<GeoLib::Point>()); return 0; }
int main (int argc, char* argv[]) { ApplicationsLib::LogogSetup logog_setup; TCLAP::CmdLine cmd("The tool computes the area per node of the surface mesh" " and writes the information as txt and csv data.", ' ', "0.1"); TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", "the name of the file containing the input mesh", true, "", "file name of input mesh"); cmd.add(mesh_in); TCLAP::ValueArg<std::string> id_prop_name("", "id-prop-name", "the name of the property containing the id information", false, "OriginalSubsurfaceNodeIDs", "property name"); cmd.add(id_prop_name); TCLAP::ValueArg<std::string> out_base_fname("p", "output-base-name", "the path and base file name the output will be written to", false, "", "output path and base name as one string"); cmd.add(out_base_fname); cmd.parse(argc, argv); std::unique_ptr<MeshLib::Mesh> surface_mesh( MeshLib::IO::readMeshFromFile(mesh_in.getValue())); INFO("Mesh read: %u nodes, %u elements.", surface_mesh->getNNodes(), surface_mesh->getNElements()); // ToDo check if mesh is read correct and if the mesh is a surface mesh // check if a node property containing the subsurface ids is available boost::optional<MeshLib::PropertyVector<std::size_t> const&> orig_node_ids( surface_mesh->getProperties().getPropertyVector<std::size_t>( id_prop_name.getValue())); // if the node property is not available generate it if (!orig_node_ids) { boost::optional<MeshLib::PropertyVector<std::size_t>&> node_ids( surface_mesh->getProperties().createNewPropertyVector<std::size_t>( id_prop_name.getValue(), MeshLib::MeshItemType::Node, 1)); if (!node_ids) { ERR("Fatal error: could not create property."); return EXIT_FAILURE; } node_ids->resize(surface_mesh->getNNodes()); std::iota(node_ids->begin(), node_ids->end(), 0); orig_node_ids = node_ids; } std::vector<double> areas( MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(*surface_mesh)); // pack area and node id together std::vector<std::pair<std::size_t, double>> ids_and_areas; std::transform(orig_node_ids->cbegin(), orig_node_ids->cend(), areas.cbegin(), std::back_inserter(ids_and_areas), std::make_pair<std::size_t const&, double const&>); // generate file names for output std::string path(out_base_fname.getValue()); if (path.empty()) path = BaseLib::dropFileExtension(mesh_in.getValue()); std::string const id_and_area_fname(path+".txt"); std::string const csv_fname(path+".csv"); writeToFile(id_and_area_fname, csv_fname, ids_and_areas, surface_mesh->getNodes()); return EXIT_SUCCESS; }
/** * main * Initilises an tree with a single node with a null value. * * @param * @return 0 */ int main() { SearchTree Tree; char menuChoice; int intElement; int i=0; char stringElement [22]; int stringValue=0; // Initilise tree with a null element Tree = MakeEmpty( NULL ); Tree = readFromFile(Tree); temparray = ((char*)malloc(22*sizeof(char))); strcpy(temparray,"null"); Print(Tree); writeToFile(Tree); //printf("\n Temp Array : %s\n",temparray); /* do { // Do while the user does not want to exit the program menuChoice = menu(menuChoice); stringValue=0; switch( menuChoice ) { case 'a': { printf("\n Inserting String : "); scanf(" %s",stringElement); for(i=0;i<strlen(stringElement);i++) { stringValue += *stringElement; } printf("\n String : %s\n",stringElement); printf(" At Node : %d\n",stringValue); strcpy(temparray,stringElement); Tree = Insert( stringElement, stringValue, Tree ); break; } case 'b': { // Searcing the tree for an integer int valueAtTree; printf("\n Search for integer : "); scanf(" %d",&intElement); Tree = Find( intElement, Tree ); if(Tree!=NULL) { valueAtTree = Retrieve( Tree ); printf("\n Element : %d is present in Tree \n",valueAtTree ); } else { printf("\n Element : %d is not present in Tree \n",intElement ); } break; } case 'c': { // Printing the current tree inorder printf("\n Printing Current Tree inorder :\n"); Print(Tree); writeToFile(Tree); break; } case 'd': { // Emptying tree and creating a new tree printf("\n Emptying Tree and initialising new tree."); Tree = MakeEmpty( NULL ); printf("\n"); break; } case 'e': { printf(" \n Exit."); break; } default : { printf("\n Invalid Selection %d",menuChoice); break; } } }while(menuChoice!='E'); */ printf("\n\n Program Complete."); return 0; }
int main(int argc, char **argv) { int my_rank=0; /* My process rank */ int p; /* The number of processes */ //clock time recording variables double start_time,end_time,comm_time_start,comm_time_end,total_comm_time=0.0; /* Let the system do what it needs to start up MPI */ MPI_Init(&argc, &argv); /* Get my process rank */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); /* Find out how many processes are being used */ MPI_Comm_size(MPI_COMM_WORLD, &p); float dataA[N][N], dataB[N][N]; complex A[N][N], B[N][N]; MPI_Aint displ[2]; displ[0] = 0; displ[1] = sizeof(float); MPI_Datatype mpi_complex,types[2]; types[0] = MPI_FLOAT; types[1] = MPI_FLOAT; int block_len[2]; block_len[0]= 1; block_len[1]= 1; MPI_Type_struct(2, block_len, displ, types,&mpi_complex); MPI_Type_commit(&mpi_complex); if(my_rank==0) { readFromFile("data/1_im1", dataA); readFromFile("data/1_im2", dataB); convertToComplex(A, dataA); convertToComplex(B, dataB); //Start clock and record the start time. start_time = MPI_Wtime(); } int local_n = N/p; int rows_per_process = N/p; complex local_A[N/p][N]; MPI_Bcast(&rows_per_process , 1, MPI_INT, 0,MPI_COMM_WORLD); //scatter A matrix aross all processes startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_fft2d(&local_A[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_A, N*local_n, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); complex local_B[N/p][N]; //scatter A matrix aross all processes startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&B[0][0], N*rows_per_process, mpi_complex, &local_B, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_fft2d(&local_B[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_B, N*local_n, mpi_complex, &B[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); if(my_rank==0) { transpose(A); transpose(B); } //scatter A matrix aross all processes for inverse transform startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_fft2d(&local_A[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_A, N*local_n, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&B[0][0], N*rows_per_process, mpi_complex, &local_B, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_fft2d(&local_B[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_B, N*local_n, mpi_complex, &B[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); if(my_rank==0) { transpose(A); transpose(B); mmul_point(A,B); } startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_inv_fft2d(&local_A[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_A, N*local_n, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); if(my_rank==0) { transpose(A); } startCommTimer(my_rank,&comm_time_start); MPI_Scatter(&A[0][0], N*rows_per_process, mpi_complex, &local_A, N*local_n, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); c_rowwise_inv_fft2d(&local_A[0][0],local_n); startCommTimer(my_rank,&comm_time_start); MPI_Gather(&local_A, N*local_n, mpi_complex, &A[0][0], N*rows_per_process, mpi_complex, 0, MPI_COMM_WORLD); stopCommTimer(my_rank,&total_comm_time,comm_time_start); if(my_rank==0) { transpose(A); //Stop clock as operation is finished. end_time = MPI_Wtime(); //print the execution time for performance analysis purpose. printf("\n\nThe total execution time as recorded on process 0 = %f seconds!!\n!",end_time-start_time); printf("\n\nThe total communication time = %f seconds!!\n!",total_comm_time); convertToReal(dataA,A); } writeToFile("final_output.txt", dataA); MPI_Finalize(); return 0; }
bool Game::cursesMain() { initscr(); noecho(); curs_set(FALSE); nodelay(stdscr, TRUE); keypad(stdscr,TRUE); srand(time(NULL)); // Coloring the screen start_color(); init_pair(1, COLOR_WHITE, COLOR_RED); // border init_pair(2, COLOR_GREEN, COLOR_GREEN); // barrier init_pair(3, COLOR_GREEN, COLOR_BLACK); // player init_pair(4, COLOR_RED, COLOR_BLACK); // boss // set up initial windows getmaxyx(stdscr, parent_y, parent_x); //set default space player.lives = 3; player.score = 0; player.x = 14; player.y = parent_y - (score_size + 3); WINDOW *field = newwin(parent_y - score_size, parent_x, 0, 0); WINDOW *score = newwin(score_size, parent_x, parent_y - score_size, 0); drawBorders(score); buildGame(board); int alienCount = 0; for(int i = 0; i < BOARDROWSIZE;i++) { for(int j = 0; j < BOARDCOLUMNSIZE;j++) { char temp = board[i][j]; wmove(field, i, j); waddch(field, temp); if(temp == ALIEN1 || temp == ALIEN2 || temp == ALIEN3) alienCount++; // mvwprintw(field, i, j, "%c", board[i][j]); } } numberOfAliens = alienCount; rawtime = time(NULL); alienGroup.waitTime = rawtime+8; // uncomment for cout // /* while(1) { getmaxyx(stdscr, new_y, new_x); if (new_y != parent_y || new_x != parent_x) { parent_x = new_x; parent_y = new_y; wresize(field, new_y - score_size, new_x); wresize(score, score_size, new_x); mvwin(score, new_y - score_size, 0); wclear(stdscr); wclear(field); wclear(score); drawBorders(score); } // board[20][18] = 'O'; // draw to our windows for(int i = 0; i < BOARDROWSIZE;i++) { for(int j = 0; j < BOARDCOLUMNSIZE;j++) { char piece = board[i][j]; // writeToFile("%c", piece); wmove(field, i, j); // check if our bullet should be seen if(board[i][j] == BULLET && player.bullet.enabled == true) waddch(field, board[i][j]); // if it shouldnt be seen then we remove it else if(board[i][j] == BULLET && player.bullet.enabled == false) { waddch(field, ' '); board[i][j] = ' '; wmove(field, i-1, j); waddch(field, ' '); board[i-1][j] = ' '; wmove(field, i, j); } // print everything else else { // color certain pieces switch(piece) { //border case '+': case '-': case '|': waddch(field, piece | COLOR_PAIR(1)); break; // barriers case '/': case '\\': case '#': waddch(field, piece | COLOR_PAIR(2)); break; //player case 'A': waddch(field, piece | COLOR_PAIR(3)); default: waddch(field, piece); } } } // writeToFile("\n"); } // Draw score board mvwprintw(score, 1, 2, "Score: "); mvwprintw(score, 1, 9, itoa(player.score, buffer, 10)); mvwprintw(score, 1, 70, "Lives: "); mvwprintw(score, 1, 77, itoa(player.lives, buffer, 10)); if(DEBUG == true) { string screensizex = itoa(new_x, buffer, 10); string screensizey = itoa(parent_y, buffer, 10); mvwprintw(score, 1, 30, "X: "); mvwprintw(score, 1, 34, screensizex.c_str()); mvwprintw(score, 1, 40, "Y: "); mvwprintw(score, 1, 44, screensizey.c_str()); } bool aliensMovement = true; aliensMovement = moveAliens(rawtime); alienShoot(); if(player.bullet.enabled == true) { if(player.bullet.direction == 'U') // safety check { timerCheck = clock()-timer; if(timerCheck > 15) { if(DEBUG == true) writeToFile("Current: %i,%i | New: %i,%i\n", player.bullet.x, player.bullet.y, player.bullet.x-1, player.bullet.y); char temp = board[player.bullet.x-1][player.bullet.y]; char temp2 = board[player.bullet.x-1][player.bullet.y+1]; switch(temp) { // all these will trigger the last case case 'S': case '@': case '%': case '&': case '#': case '/': case '\\': case '+': // most likely never reach here case '|': if(DEBUG == true) writeToFile("Collision with [%c]\n", temp); if(temp == ALIEN1) { player.score += 10; numberOfAliens--; } else if(temp == ALIEN2) { player.score += 20; numberOfAliens--; } else if(temp == ALIEN3) { player.score += 40; numberOfAliens--; } else if(temp == BOSS) { player.score += 150; } temp = ' '; temp2 = ' '; player.bullet.enabled = false; break; case '-': if(DEBUG == true) writeToFile("Bullet hits wall\n"); player.bullet.enabled = false; board[player.bullet.x][player.bullet.y] = ' '; break; default: // spaces and whatnot if(DEBUG == true) writeToFile("%i,%i = %c\n%i,%i\n",player.bullet.x,player.bullet.y-1,board[player.bullet.x][player.bullet.y],player.bullet.x,player.bullet.y); board[player.bullet.x-1][player.bullet.y] = BULLET; board[player.bullet.x][player.bullet.y] = ' '; player.bullet.x = player.bullet.x-1; break; } timer = clock(); } } } for(int x = 1;x<5;x++) { timerCheck = clock()-timer; if(timerCheck > 50) { char temp = ' '; switch(x) { case 1: temp = board[alienGroup.alienBullet1.x+1][alienGroup.alienBullet1.y]; if(alienGroup.alienBullet1.enabled == true) { switch(temp) { case '/': case '\\': case '#': temp = ' '; alienGroup.alienBullet1.enabled = false; board[alienGroup.alienBullet1.x][alienGroup.alienBullet1.y] = ' '; alienGroup.missles--; break; case 'A': player.lives--; board[player.x][player.y]= ' '; player.x = 14; player.y = parent_y - (score_size + 3); board[player.x][player.y] = PLAYER; alienGroup.missles--; break; case '-': if(DEBUG == true) writeToFile("Bullet hits wall\n"); alienGroup.alienBullet1.enabled = false; board[alienGroup.alienBullet1.x][alienGroup.alienBullet1.y] = ' '; alienGroup.missles--; break; default: if(DEBUG == true) writeToFile("%i,%i = %c\n%i,%i\n",player.bullet.x,player.bullet.y-1,board[player.bullet.x][player.bullet.y],player.bullet.x,player.bullet.y); board[alienGroup.alienBullet1.x+1][alienGroup.alienBullet1.y] = ALIENBULLET; board[alienGroup.alienBullet1.x][alienGroup.alienBullet1.y] = ' '; alienGroup.alienBullet1.x = alienGroup.alienBullet1.x+1; break; } /* if(temp == PLAYER) { player.lives--; player.x = 14; player.y = parent_y - (score_size + 3); board[player.x][player.y] = PLAYER; alienGroup.alienBullet1.enabled = false; alienGroup.missles--; } else if(temp == BARRIERCORNER1 || temp == BARRIERCORNER2 || temp == BARRIERMAIN) { temp = ' '; alienGroup.alienBullet1.enabled = false; alienGroup.missles--; } else if(temp == '-') { alienGroup.alienBullet1.enabled = false; alienGroup.missles--; } else { temp = BULLET; board[alienGroup.alienBullet1.x][alienGroup.alienBullet1.y] = ' '; alienGroup.alienBullet1.y += 1; }*/ } // case 2: // case 3: // case 4: default: break; } } } if(keyHit()) { key = getch(); keyChecker = keyCheck(key); if(keyChecker == true) break; // have code in CP } // refresh each window wrefresh(field); wrefresh(score); if(numberOfAliens == 0) break; } endwin(); // */ return true; }
void MovieCollection::sync() { if(m_dirty) writeToFile(); }
void JUnitTestOutput::writeXmlHeader() { writeToFile("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); }
int main(void){ Properties p; p.put("Kalle", 1); p.put("Ank1", "anka"); p.put("Ank2", "anka"); p.put("Ank3", "anka"); p.put("Ank4", "anka"); putALot(p); Properties tmp; tmp.put("Type", "TCP"); tmp.put("OwnNodeId", 1); tmp.put("RemoteNodeId", 2); tmp.put("OwnHostName", "local"); tmp.put("RemoteHostName", "remote"); tmp.put("SendSignalId", 1); tmp.put("Compression", (Uint32)false); tmp.put("Checksum", 1); tmp.put64("SendBufferSize", 2000); tmp.put64("MaxReceiveSize", 1000); tmp.put("PortNumber", 1233); putALot(tmp); p.put("Connection", 1, &tmp); p.put("NoOfConnections", 2); p.put("NoOfConnection2", 2); p.put("kalle", 3); p.put("anka", "kalle"); Properties p2; p2.put("kalle", "anka"); p.put("prop", &p2); p.put("Connection", 2, &tmp); p.put("Connection", 3, &tmp); p.put("Connection", 4, &tmp); /* */ Uint32 a = 99; const char * b; const Properties * p3; Properties * p4; bool bb = p.get("kalle", &a); bool cc = p.get("anka", &b); bool dd = p.get("prop", &p3); if(p.getCopy("prop", &p4)) delete p4; p2.put("p2", &p2); p.put("prop2", &p2); /* */ p.print(stdout, "testing 1: "); writeToFile(p, "A_1"); writeToFile(p, "B_1", false); Properties r1; readFromFile(r1, "A_1"); writeToFile(r1, "A_3"); //r1.print(stdout, "testing 2: "); Properties r2; readFromFile(r2, "A_1"); writeToFile(r2, "A_4"); Properties r3; readFromFile(r3, "B_1", false); writeToFile(r3, "A_5"); r3.print(stdout, "testing 3: "); return 0; }
void JUnitTestOutput::writeFileEnding() { writeToFile("<system-out></system-out>\n"); writeToFile("<system-err></system-err>\n"); writeToFile("</testsuite>"); }
GIFError CGIFFile::InitOutput(long width, long height) { if (!m_File.IsOpen()) return GIF_FileNotOpen; if (m_IsInput) return GIF_WriteToInputFile; m_ImageWidth = width; m_ImageHeight = height; GIFError status; status = writeToFile("GIF87a", 6); if (status != GIF_Success) return status; GIFScreenDescriptor screen; screen.Width = WORD(m_ImageWidth); screen.Height = WORD(m_ImageHeight); screen.PackedFields = 0; if (m_GlobalColorMapEntryCount > 0) { DWORD highest = highestBit(m_GlobalColorMapEntryCount); if (highest < 3) highest = 1; else highest -= 2; screen.PackedFields |= (BYTE)GIFGlobalMapPresent; screen.PackedFields |= highest; // color table size screen.PackedFields |= highest << 4; // color resolution } screen.BackgroundIndex = 0; screen.AspectRatio = 0; status = writeToFile(&screen, sizeof(screen)); if (status != GIF_Success) return status; if (m_GlobalColorMapEntryCount > 0) { status = writeToFile(m_GlobalColorMap, m_GlobalColorMapEntryCount * 3); if (status != GIF_Success) return status; } if (m_pCommentBuffer != 0) { BYTE extension = 0x21; status = writeToFile(&extension, sizeof(extension)); if (status != GIF_Success) return status; BYTE commentExtension = 0xFE; status = writeToFile(&commentExtension, sizeof(commentExtension)); if (status != GIF_Success) return status; BYTE comLen; int commentLength = m_CommentBufferSize; int commentOffset = 0; do { if (commentLength > 255) comLen = BYTE(255); else comLen = BYTE(commentLength); status = writeToFile(&comLen, sizeof(comLen)); if (status != GIF_Success) return status; status = writeToFile(&(m_pCommentBuffer[commentOffset]), comLen); if (status != GIF_Success) return status; commentLength -= comLen; commentOffset += comLen; } while (commentLength > 0); comLen = 0; status = writeToFile(&comLen, sizeof(comLen)); if (status != GIF_Success) return status; } return GIF_Success; }