static int premia_treat_input_file ( Planning *pt_plan, Model **models, Family **families, Pricing **pricings, int user, char FileRead[MAX_LINE][MAX_CHAR_LINE]) { Model* pt_model; Option* pt_option; Pricing* pt_pricing; PricingMethod* pt_method; DynamicTest* pt_test; PricingMethod* pt_methods_available[MAX_METHODS]; pt_plan->Action=FChooseAction(FileRead); if (OutputFile(&out_stream)!=OK) return FAIL; if (FSelectModel(FileRead,user,pt_plan,models,&pt_model)!=OK) return FAIL; if (FSelectOption(FileRead,user,pt_plan,families,pt_model,pricings,&pt_option)!=OK) return FAIL; if (FSelectPricing(FileRead,user,pt_model,pt_option,pricings,&pt_pricing)!=OK) return FAIL; while(1){ if (FSelectMethod(FileRead,user,pt_plan,pt_pricing,pt_option,pt_model,&pt_method)!=OK) return FAIL; if (FSelectTest(FileRead,user,pt_plan,pt_pricing,pt_option,pt_model,pt_method,&pt_test)!=OK) return FAIL; if (FGetTimeInfo(FileRead,user,pt_plan,&computation_time_info)!=OK) return FAIL; if ((pt_plan->Action=='p')||(( pt_plan->Action=='t'))){ (void)ShowPlanning(NAMEONLYTOFILE,pt_plan); (void)Action(pt_model,pt_option,pt_pricing, pt_method,pt_test,NAMEONLYTOFILE,pt_plan,&computation_time_info); Fprintf(TOSCREEN,"\nComputing...\n"); Iterate(pt_plan,&(pt_plan->Par[0]),0,pt_plan->Action,pt_model, pt_option,pt_pricing,pt_method,pt_test,TOFILE,&computation_time_info); pt_methods_available[pt_plan->NumberOfMethods]=pt_method; if (pt_plan->Action=='t' || FMoreAction(FileRead,&(pt_plan->NumberOfMethods))==FAIL) break; else free_premia_method(pt_method); } } fclose(out_stream); if ((pt_plan->Action=='p') && (pt_plan->VarNumber>0)) (void)BuildGnuStuff(pt_plan,pt_model,pt_option,pt_pricing,pt_methods_available); if (pt_plan->Action=='t') { (void)FreeTest(pt_test); (void)BuildGnuStuffTest(pt_model,pt_option,pt_pricing,pt_method,pt_test); } free_premia_model(pt_model); free_premia_option(pt_option); free_premia_method(pt_method); return OK; }
void WriteDebugLog(DWORD dwLastError, LPCSTR file, int codeLine, LOG_LEVEL level, LPCTSTR content, ...) { //格式化日志 TCHAR logContent[ODS_LOG_MAXLENGTH + 1] = {0}; DWORD dwThreadID = ::GetCurrentThreadId(); std::string ansiCodefile = file; std::string::size_type pos = ansiCodefile.find_last_of('\\'); if (pos != std::string::npos && pos + 1 < ansiCodefile.size()) ansiCodefile = ansiCodefile.substr(pos + 1); tstring codeFile = s2ws(ansiCodefile); tstring strLevel; switch (level) { case ODSLEVEL_DEBUG: strLevel = _T("debug"); break; case ODSLEVEL_INFO: strLevel = _T("info"); break; case ODSLEVEL_ERROR: strLevel = _T("error"); break; default: strLevel = _T("unknown"); break; } int iWritten = _stprintf_s(logContent, _T("%s [%s:%d] %u "), strLevel.c_str(), codeFile.c_str(), codeLine, dwThreadID); va_list ap; va_start(ap, content); _vsntprintf_s(logContent + iWritten, ODS_LOG_MAXLENGTH - iWritten, _TRUNCATE, content, ap); va_end(ap); if (dwLastError != 0) { TCHAR lastError[16] = {0}; _stprintf_s(lastError, 15, _T(" E%u"), dwLastError); size_t len = _tcslen(logContent); if (len + _tcslen(lastError) < ODS_LOG_MAXLENGTH) { _tcscat_s(logContent, lastError); } } // //写入日志 // #ifdef ODS_OUTPUT_STD printf("%s\n", t2a(logContent)); // #endif #ifdef ODS_OUTPUT_FILE OutputFile(logContent); #endif OutputDebugString(logContent); }
void Settings::Save(QString IFileName) { QDomDocument Document; QDomElement Root = Document.createElement(XML_ROOT_TAG); Document.appendChild(Root); for(int i=0; i<UserList.length(); ++i) Root.appendChild(UserList[i].ToXML(&Document)); QFile OutputFile(IFileName); OutputFile.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream OutStream(&OutputFile); OutStream << Document.toString(); OutputFile.close(); }
void ConvertFastFrameData(string cUserFileName, string cUserColSep, Bool_t bIsGermanDecimal){ // +++ open Fast Frame data file +++ ifstream UserDataFile(cUserFileName.c_str()); // open data file if(UserDataFile.fail()){ // if opening fails, exit cerr << "Failed to open " << cUserFileName << "!" << endl; exit (-1); } // +++ create ROOT output file +++ string cOutputFileName = cUserFileName + ".root"; // append .root to existing file name TFile OutputFile(cOutputFileName.c_str(),"RECREATE"); // create new ROOT file, if existing already it will be overwritten if (OutputFile.IsZombie()) { // if creating new ROOT file fails, exit program cout << "Error opening file" << endl; UserDataFile.close(); exit(-1); } // +++ parse header information +++ FASTFRAME_HEADER FastFrameHeaderData; TTree *tFastFrameHeaderData = ParseForHeaderData(&UserDataFile,&FastFrameHeaderData,cUserColSep,bIsGermanDecimal); if(tFastFrameHeaderData==NULL){ cerr << "Error while parsing header data!" << endl; exit (-1); } // +++ parse timestamp data +++ TTree *tFastFrameTimestamps = ParseForTimestampData(&UserDataFile,FastFrameHeaderData.nRecordLength,cUserColSep,bIsGermanDecimal); if(tFastFrameTimestamps==NULL){ cerr << "Error while parsing timestamp data!" << endl; exit (-1); } // +++ parse amplitude data +++ TTree *tFastFrameAmplitudes = ParseForAmplitudeData(&UserDataFile,FastFrameHeaderData.nRecordLength,cUserColSep,bIsGermanDecimal); if(tFastFrameAmplitudes==NULL){ cerr << "Error while parsing amplitude data!" << endl; exit (-1); } if(FastFrameHeaderData.nFastFrameCount!=tFastFrameAmplitudes->GetEntries()){ cerr << "Mismatch of decoded event numbers!" << endl; exit (-1); } // +++ write TTrees to output file +++ OutputFile.cd(); tFastFrameHeaderData->Write(); tFastFrameTimestamps->Write(); tFastFrameAmplitudes->Write(); // +++ cleaning up +++ UserDataFile.close(); delete tFastFrameHeaderData; delete tFastFrameTimestamps; delete tFastFrameAmplitudes; }
void VarMGCTM::RunEM(CorpusC &test, MGCTM* m) { MGSS ss; ss.CorpusInit(cor_, *m); MStep(ss, m); LOG(INFO) << m->pi.transpose(); for (int i = 0; i < converged_.em_max_iter_; i++) { std::vector<MGVar> vars(cor_.Len()); VReal likelihoods(cor_.Len()); #pragma omp parallel for for (size_t d = 0; d < cor_.Len(); d++) { likelihoods[d] = Infer(cor_.docs[d], *m, &vars[d]); } double likelihood = 0; VStr etas(cor_.Len()); ss.SetZero(m->GTopicNum(), m->LTopicNum1(), m->LTopicNum2(), m->TermNum()); for (size_t d = 0; d < cor_.Len(); d++) { DocC &doc = cor_.docs[d]; for (size_t n = 0; n < doc.ULen(); n++) { for (int k = 0; k < m->GTopicNum(); k++) { ss.g_topic(k, doc.Word(n)) += doc.Count(n)*vars[d].g_z(k, n)* (1 - vars[d].delta[n]); ss.g_topic_sum[k] += doc.Count(n)*vars[d].g_z(k, n)*(1 - vars[d].delta[n]); } } for (int j = 0; j < m->LTopicNum1(); j++) { for (size_t n = 0; n < doc.ULen(); n++) { for (int k = 0; k < m->LTopicNum2(); k++) { ss.l_topic[j](k, doc.Word(n)) += doc.Count(n)*vars[d].l_z[j](k, n) *vars[d].delta[n]*vars[d].eta[j]; ss.l_topic_sum(k, j) += doc.Count(n)*vars[d].l_z[j](k, n) * vars[d].delta[n] * vars[d].eta[j]; } } } for (int j = 0; j < m->LTopicNum1(); j++) { ss.pi[j] += vars[d].eta[j]; } etas[d] = EVecToStr(vars[d].eta); likelihood += likelihoods[d]; } MStep(ss, m); LOG(INFO) << m->pi.transpose(); OutputFile(*m, Join(etas,"\n"), i); // LOG(INFO) <<"perplexity: " <<Infer(test,*m); } }
int main () { printf ("Results of stdout_test:\n"); fflush (stdout); try { OutputFile ("/io/stdout").Write (MESSAGE,strlen (MESSAGE)); } catch (std::exception& exception) { printf ("Exception: %s\n",exception.what ()); fflush (stdout); } return 0; }
// ----------------------------------------------------------------------- bool ProcessFolder(const QString &Input_, const QString &Output_, TProcessor &Processor_) { QDir InputFolder(Input_); if(!InputFolder.exists()) { std::cerr << "Error accessing folder '" << (const char*)Input_.toLocal8Bit() << "'."; return false; } // QDir OutputFolder(Output_); if(!OutputFolder.exists()) { if(!OutputFolder.mkpath(Output_)) { std::cerr << "Can't create folder '" << (const char*)Output_.toLocal8Bit() << "'."; return false; } } // Processing files QStringList FilesList = InputFolder.entryList(QDir::Files | QDir::Hidden | QDir::System); for(QStringList::iterator it = FilesList.begin(); it != FilesList.end(); ++it) { QString InputFile(Input_ + *it), OutputFile(Output_ + *it); if(QFile::exists(OutputFile)) { if(!QFile::remove(OutputFile)) { std::cerr << "Can't write file '" << (const char*)OutputFile.toLocal8Bit() << "'."; return false; } } bool Result = Processor_.isExcluded(*it)? QFile::copy(InputFile, OutputFile): Processor_.processFile(InputFile, OutputFile); // if(!Result) { std::cerr << "Can't write file '" << (const char*)OutputFile.toLocal8Bit() << "'."; return false; } } // Processing folders FilesList = InputFolder.entryList(QDir::Dirs | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot | QDir::NoSymLinks); for(QStringList::iterator it = FilesList.begin(); it != FilesList.end(); ++it) { if(!ProcessFolder(Input_ + *it + QDir::separator(), Output_ + *it + QDir::separator(), Processor_)) return false; } return true; }
void UCheatManager::LogOutBugItGoToLogFile( const FString& InScreenShotDesc, const FString& InGoString, const FString& InLocString ) { #if ALLOW_DEBUG_FILES // Create folder if not already there const FString OutputDir = FPaths::BugItDir() + InScreenShotDesc + TEXT("/"); IFileManager::Get().MakeDirectory( *OutputDir ); // Create archive for log data. // we have to +1 on the GScreenshotBitmapIndex as it will be incremented by the bugitscreenshot which is processed next tick const FString DescPlusExtension = FString::Printf( TEXT("%s%i.txt"), *InScreenShotDesc, GScreenshotBitmapIndex ); const FString TxtFileName = CreateProfileFilename( DescPlusExtension, false ); //FString::Printf( TEXT("BugIt%s-%s%05i"), *GEngineVersion.ToString(), *InScreenShotDesc, GScreenshotBitmapIndex+1 ) + TEXT( ".txt" ); const FString FullFileName = OutputDir + TxtFileName; FOutputDeviceFile OutputFile(*FullFileName); //FArchive* OutputFile = IFileManager::Get().CreateDebugFileWriter( *(FullFileName), FILEWRITE_Append ); OutputFile.Logf( TEXT("Dumping BugIt data chart at %s using build %s built from changelist %i"), *FDateTime::Now().ToString(), *GEngineVersion.ToString(), GetChangeListNumberForPerfTesting() ); const FString MapNameStr = GetWorld()->GetMapName(); OutputFile.Logf( TEXT("MapName: %s"), *MapNameStr ); OutputFile.Logf( TEXT("Description: %s"), *InScreenShotDesc ); OutputFile.Logf( TEXT("%s"), *InGoString ); OutputFile.Logf( TEXT("%s"), *InLocString ); OutputFile.Logf( TEXT(" ---=== GameSpecificData ===--- ") ); DoGameSpecificBugItLog(OutputFile); // Flush, close and delete. //delete OutputFile; OutputFile.TearDown(); // so here we want to send this bad boy back to the PC SendDataToPCViaUnrealConsole( TEXT("UE_PROFILER!BUGIT:"), *(FullFileName) ); #endif // ALLOW_DEBUG_FILES }
void CMyXmlEle::WriteAllL(CSenElement* aXml) { RFs fss; User::LeaveIfError(fss.Connect()); CleanupClosePushL(fss); TBuf<255> file; _LIT( KFileName, "e:\\testing\\data\\normalizer%d.xml"); file.Format(KFileName, count); count++; TPtrC OutputFile(file); RFile xmlFile; xmlFile.Replace(fss , OutputFile, EFileWrite ); HBufC8* temp = aXml->AsXmlL(); xmlFile.Write(temp->Des()); xmlFile.Close(); delete temp; CleanupStack::PopAndDestroy(1); // fss }
void main(void) { struct personal_data_format *sort_data; int k; if ( (Data = calloc( 100, sizeof( struct personal_data_format ) )) == NULL) { printf("Not allocate memory !\n"); exit(1); } if ( (sort_data = calloc( 100, sizeof( struct personal_data_format ) )) == NULL) { printf("Not allocate memory !\n"); exit(1); } InputFile(); if ( (k = Attest()) == 1 ) { printf("Error ! \n"); exit(1); } else if (k == 0) { printf("Welcome ! \n"); } MakeSortData( sort_data ); QuickSort( sort_data , 0 , Data_num - 1 ); OutputFile( sort_data ); free( Data ); free( sort_data ); }
int wmain(int argc, wchar_t* argv[]) { try { if( argc != 3 ) { throw swException(wstring_make() << "usage: input.obj output.gl" ); } wstring InputFileName = argv[1]; wstring OutputFileName = argv[2]; TriMesh mesh; cout << endl << "Loading: " << toNarrowString(InputFileName.c_str()).c_str() << endl; ObjFile InputFile(InputFileName, mesh); cout << endl << "Writing: " << toNarrowString(OutputFileName.c_str()) << endl; GLFile OutputFile(OutputFileName, mesh); return EXIT_SUCCESS; } catch(swException& e) { cout << toNarrowString(e.What()) << endl; } catch(exception& e) { cout << e.what() << endl; } catch(...) { cout << "unknown exception" << endl; } return EXIT_FAILURE; }
void GenerateSnapshot (CUniverse &Universe, CXMLElement *pCmdLine) { ALERROR error; int i; // Get some parameters int iInitialUpdateTime = pCmdLine->GetAttributeIntegerBounded(CONSTLIT("initialUpdate"), 0, -1, 10); int iUpdateTime = pCmdLine->GetAttributeInteger(CONSTLIT("wait")); bool bObjOnly = pCmdLine->GetAttributeBool(CONSTLIT("objOnly")); // Criteria CString sNode = pCmdLine->GetAttribute(CONSTLIT("node")); CString sCriteria = pCmdLine->GetAttribute(CONSTLIT("criteria")); // Number of snapshots int iTotalCount = pCmdLine->GetAttributeIntegerBounded(CONSTLIT("count"), 1, -1, 1); // Output int cxWidth; int cyHeight; if (pCmdLine->FindAttributeInteger(CONSTLIT("size"), &cxWidth)) { cyHeight = cxWidth; } else { cxWidth = 1024; cyHeight = 1024; } // Paint flags DWORD dwPaintFlags = 0; if (pCmdLine->GetAttributeBool(CONSTLIT("noStars"))) dwPaintFlags |= CSystem::VWP_NO_STAR_FIELD; // Output file CString sFilespec = pCmdLine->GetAttribute(CONSTLIT("output")); if (!sFilespec.IsBlank()) sFilespec = pathStripExtension(sFilespec); // Output image CG32bitImage Output; Output.Create(cxWidth, cyHeight); // Update context SSystemUpdateCtx Ctx; Ctx.bForceEventFiring = true; Ctx.bForcePainted = true; RECT rcViewport; rcViewport.left = 0; rcViewport.top = 0; rcViewport.right = cxWidth; rcViewport.bottom = cyHeight; // Loop over all systems until we find what we're looking for int iLoops = 20; int iNodeIndex = 0; int iSnapshotIndex = 0; CTopologyNode *pNode = Universe.GetTopologyNode(iNodeIndex); while (true) { // Create the system CSystem *pSystem; if (error = Universe.CreateStarSystem(pNode, &pSystem)) { printf("ERROR: Unable to create star system.\n"); return; } // If this is the node we want, then search CSpaceObject *pTarget; if (sNode.IsBlank() || strEquals(sNode, pNode->GetID())) { printf("Searching %s...\n", pNode->GetSystemName().GetASCIIZPointer()); // Set the POV CSpaceObject *pPOV = pSystem->GetObject(0); Universe.SetPOV(pPOV); pSystem->SetPOVLRS(pPOV); // Prepare system Universe.UpdateExtended(); Universe.GarbageCollectLibraryBitmaps(); // Update for a while for (i = 0; i < iInitialUpdateTime; i++) { Universe.Update(Ctx); Universe.PaintPOV(Output, rcViewport, 0); } // Compose the criteria CSpaceObject::Criteria Criteria; CSpaceObject::ParseCriteria(pPOV, sCriteria, &Criteria); // Get the list of all objects in the system that match the criteria CSpaceObject::SCriteriaMatchCtx Ctx(Criteria); TArray<CSpaceObject *> Results; for (i = 0; i < pSystem->GetObjectCount(); i++) { CSpaceObject *pObj = pSystem->GetObject(i); if (pObj && pObj->MatchesCriteria(Ctx, Criteria)) Results.Insert(pObj); } // Pick the appropriate object from the list if (Results.GetCount() == 0) pTarget = NULL; else if (Criteria.bNearestOnly || Criteria.bFarthestOnly) pTarget = Ctx.pBestObj; else pTarget = Results[mathRandom(0, Results.GetCount() - 1)]; } else pTarget = NULL; // If we found the target, then output if (pTarget) { Universe.SetPOV(pTarget); // Wait a bit // // NOTE: After we update, pTarget could be invalid (i.e., destroyed) // so we can't use it again. CString sTargetName = pTarget->GetNounPhrase(0); for (i = 0; i < iUpdateTime; i++) { if ((i % 100) == 99) printf("."); Universe.Update(Ctx); Universe.PaintPOV(Output, rcViewport, 0); } if (iUpdateTime >= 99) printf("\n"); // Paint if (bObjOnly) { SViewportPaintCtx Ctx; Ctx.pObj = Universe.GetPOV(); Ctx.XForm = ViewportTransform(Universe.GetPOV()->GetPos(), g_KlicksPerPixel, cxWidth / 2, cyHeight / 2); Ctx.XFormRel = Ctx.XForm; Ctx.fNoRecon = true; Ctx.fNoDockedShips = true; Ctx.fNoSelection = true; Ctx.fNoStarfield = true; CSpaceObject *pPOV = pSystem->GetObject(0); CSpaceObject::Criteria Criteria; CSpaceObject::ParseCriteria(pPOV, sCriteria, &Criteria); // Paint all objects that match the criteria CSpaceObject::SCriteriaMatchCtx CriteriaCtx(Criteria); for (i = 0; i < pSystem->GetObjectCount(); i++) { CSpaceObject *pObj = pSystem->GetObject(i); if (pObj && pObj->MatchesCriteria(CriteriaCtx, Criteria)) { Ctx.pObj = pObj; int xObj; int yObj; Ctx.XForm.Transform(pObj->GetPos(), &xObj, &yObj); pObj->Paint(Output, xObj, yObj, Ctx); } } } else { Universe.PaintPOV(Output, rcViewport, 0); } // Write to file if (!sFilespec.IsBlank()) { CString sBmpFilespec; if (iTotalCount > 100) sBmpFilespec = pathAddExtensionIfNecessary(strPatternSubst(CONSTLIT("%s%03d"), sFilespec, iSnapshotIndex + 1), CONSTLIT(".bmp")); else if (iTotalCount > 1) sBmpFilespec = pathAddExtensionIfNecessary(strPatternSubst(CONSTLIT("%s%02d"), sFilespec, iSnapshotIndex + 1), CONSTLIT(".bmp")); else sBmpFilespec = pathAddExtensionIfNecessary(sFilespec, CONSTLIT(".bmp")); CFileWriteStream OutputFile(sBmpFilespec); if (OutputFile.Create() != NOERROR) { printf("ERROR: Unable to create '%s'\n", sBmpFilespec.GetASCIIZPointer()); return; } Output.WriteToWindowsBMP(&OutputFile); OutputFile.Close(); printf("Found %s: Saved to %s\n", sTargetName.GetASCIIZPointer(), sBmpFilespec.GetASCIIZPointer()); } // Otherwise, clipboard else { if (error = Output.CopyToClipboard()) { printf("ERROR: Unable to copy image to clipboard.\n"); return; } printf("Found %s: Copied to clipboard.\n", sTargetName.GetASCIIZPointer()); } // Reset maximum loops iLoops = 20; // Done iSnapshotIndex++; if (iSnapshotIndex >= iTotalCount) break; } // Done with old system Universe.DestroySystem(pSystem); // Loop to the next node do { iNodeIndex = ((iNodeIndex + 1) % Universe.GetTopologyNodeCount()); pNode = Universe.GetTopologyNode(iNodeIndex); } while (pNode == NULL || pNode->IsEndGame()); // If we're back to the first node again, restart if (iNodeIndex == 0) { if (--iLoops > 0) { // Reinitialize Universe.Reinit(); CString sError; if (Universe.InitGame(0, &sError) != NOERROR) { printf("ERROR: %s\n", sError.GetASCIIZPointer()); return; } iNodeIndex = 0; pNode = Universe.GetTopologyNode(iNodeIndex); } else { printf("ERROR: Specified target could not be found.\n"); return; } } } }
// Prints details of resident population to file in directory DIR. // Precondition: appropriate resident condition already stored in solver, achieved by running residentFitness // Postcondition: none void FitnessSolver::printPopulationProfile(const double residentTraits[], const double X[], int N, string DIR) { if (!residentsAreSet) {cerr << "Population print requested without running resident s first" << endl; hold(); exit(EXIT_FAILURE);} ofstream OutputFile((DIR + "/output.txt").c_str()); OutputFile << "A little output" << endl; }
int main (int argc, const char **argv) /* !C****************************************************************************** !Description: 'main' is the main function for the 'resamp' program. !Input Parameters: argc number of run-time (command line) arguments argv list of run-time argument values !Output Parameters: (returns) status: 'EXIT_SUCCESS' = okay 'EXIT_FAILURE' = fatal error !Team Unique Header: ! Design Notes: 1. See 'USAGE' in 'parser.h' for information on how to use the program. 2. An error status is returned when: a. there is a problem getting runtime parameters b. there is a bad input image, geolocation or kernel file c. unable to set up the input grid, scan data structure, or the output space d. unable to generate kernel f. unable to free memory for data structures g. unable to set up intermediate patches data structure h. there is an error reading geolocation for a scan i. there is an error mapping a scan j. there is an error generating geolocation for a scan k. there is an error copying a scan l. there is an error extending the scan m. there is an error reading input data for a scan n. there is an error resampling a scan o. there is an error writting patches to disk p. there is an error closing input image, geolocation, kernel or output files q. there is an error untouching patches r. there is an error creating output image file s. there is an error opening output file t. there is an error unscrambling the output file u. there is an error writing metadata. 3. Errors are handled with the 'LOG_ERROR' macro. !END**************************************************************************** */ { int i,j,k; int curr_sds, curr_band; /* current SDS and current band in SDS */ char tmp_sds_name[MAX_STR_LEN]; char errstr[M_MSG_LEN+1]; /* error string for OpenInput */ char sdsname[256]; /* SDS name without '/'s */ char msg[M_MSG_LEN+1]; Param_t *param = NULL; Param_t *param_save = NULL; Geoloc_t *geoloc = NULL; Kernel_t *kernel = NULL; Input_t *input = NULL; Scan_t *scan = NULL; Space_t *output_space = NULL; Patches_t *patches = NULL; int iscan, kscan; int il, nl; Output_t *output = NULL; Img_coord_double_t img; Geo_coord_t geo; FILE_ID *MasterGeoMem; /* Output GeoTiff file */ FILE *rbfile = NULL; /* Output Raw Binary file */ char HDF_File[1024], CharThisPid[256], FinalFileName[1024]; Output_t output_mem; /* Contains output HDF file */ int32 exec_resamp, ThisPid; char filename[1024]; /* name of raw binary file to be written to */ time_t startdate, enddate; /* start and end date struct */ bool file_created; /* was the current HDF file created? */ /* Initialize the log file */ InitLogHandler(); /* Print the MRTSwath header */ LogInfomsg( "*******************************************************************" "***********\n"); sprintf(msg, "%s (%s)\n", RESAMPLER_NAME, RESAMPLER_VERSION); LogInfomsg(msg); startdate = time(NULL); sprintf(msg, "Start Time: %s", ctime(&startdate)); LogInfomsg(msg); LogInfomsg( "------------------------------------------------------------------\n"); /* Get runtime parameters */ if (NeedHelp(argc, argv)) exit(EXIT_SUCCESS); param_save = GetParam(argc, argv); if (param_save == (Param_t *)NULL) LOG_ERROR("getting runtime parameters", "main"); /* Print out the user-specified processing information */ PrintParam(param_save); /* Loop through all the SDSs */ for (curr_sds = 0; curr_sds < param_save->num_input_sds; curr_sds++) { /* Loop through all the bands in the current SDS */ for (curr_band = 0; curr_band < param_save->input_sds_nbands[curr_sds]; curr_band++) { /* Is this band one that should be processed? */ if (!param_save->input_sds_bands[curr_sds][curr_band]) continue; /* Assume the HDF file does not need to be created */ file_created = false; /* Get a copy of the user parameters */ param = CopyParam(param_save); if (param == (Param_t *)NULL) LOG_ERROR("copying runtime parameters", "main"); /* Create the input_sds_name which is "SDSname, band" */ if (param->input_sds_nbands[curr_sds] == 1) { /* 2D product so the band number is not needed */ sprintf(tmp_sds_name, "%s", param->input_sds_name_list[curr_sds]); } else { /* 3D product so the band number is required */ sprintf(tmp_sds_name, "%s, %d", param->input_sds_name_list[curr_sds], curr_band); } param->input_sds_name = strdup (tmp_sds_name); if (param->input_sds_name == NULL) LOG_ERROR("error creating input SDS band name", "main"); sprintf(msg, "\nProcessing %s ...\n", param->input_sds_name); LogInfomsg(msg); /* Update the system to process the current SDS and band */ if (!update_sds_info(curr_sds, param)) LOG_ERROR("error updating SDS information", "main"); /* Open input file for the specified SDS and band */ input = OpenInput(param->input_file_name, param->input_sds_name, param->iband, param->rank[curr_sds], param->dim[curr_sds], errstr); if (input == (Input_t *)NULL) { /* This is an invalid SDS for our processing so skip to the next SDS. We will only process SDSs that are at the 1km, 500m, or 250m resolution (i.e. a factor of 1, 2, or 4 compared to the 1km geolocation lat/long data). We also only process CHAR8, INT8, UINT8, INT16, and UINT16 data types. */ LOG_WARNING(errstr, "main"); LOG_WARNING("not processing SDS/band", "main"); break; } /* Setup kernel */ kernel = GenKernel(param->kernel_type); if (kernel == (Kernel_t *)NULL) LOG_ERROR("generating kernel", "main"); /* Open geoloc file */ geoloc = OpenGeolocSwath(param->geoloc_file_name); if (geoloc == (Geoloc_t *)NULL) LOG_ERROR("bad geolocation file", "main"); /* Setup input scan */ scan = SetupScan(geoloc, input, kernel); if (scan == (Scan_t *)NULL) LOG_ERROR("setting up scan data structure", "main"); /* Set up the output space, using the current pixel size and number of lines and samples based on the current SDS (pixel size and number of lines and samples are the same for all the bands in the SDS) */ param->output_space_def.img_size.l = param->output_img_size[curr_sds].l; param->output_space_def.img_size.s = param->output_img_size[curr_sds].s; param->output_space_def.pixel_size = param->output_pixel_size[curr_sds]; sprintf(msg, " output lines/samples: %d %d\n", param->output_space_def.img_size.l, param->output_space_def.img_size.s); LogInfomsg(msg); if (param->output_space_def.proj_num == PROJ_GEO) { sprintf(msg, " output pixel size: %.4f\n", param->output_space_def.pixel_size * DEG); LogInfomsg(msg); } else { sprintf(msg, " output pixel size: %.4f\n", param->output_space_def.pixel_size); LogInfomsg(msg); } LogInfomsg(" output data type: "); switch (param->output_data_type) { case DFNT_CHAR8: LogInfomsg("CHAR8\n"); break; case DFNT_UINT8: LogInfomsg("UINT8\n"); break; case DFNT_INT8: LogInfomsg("INT8\n"); break; case DFNT_UINT16: LogInfomsg("UINT16\n"); break; case DFNT_INT16: LogInfomsg("INT16\n"); break; case DFNT_UINT32: LogInfomsg("UINT32\n"); break; case DFNT_INT32: LogInfomsg("INT32\n"); break; default: LogInfomsg("same as input\n"); break; } output_space = SetupSpace(¶m->output_space_def); if (output_space == (Space_t *)NULL) LOG_ERROR("setting up output space", "main"); /* Compute and print out the corners */ img.is_fill = false; img.l = img.s = 0.0; if (!FromSpace(output_space, &img, &geo)) { LOG_WARNING("unable to compute upper left corner", "main"); } else { sprintf(msg, " output upper left corner: lat %13.8f long %13.8f\n", (DEG * geo.lat), (DEG * geo.lon)); LogInfomsg(msg); } img.is_fill = false; img.l = output_space->def.img_size.l - 1; img.s = output_space->def.img_size.s - 1; if (!FromSpace(output_space, &img, &geo)) { LOG_WARNING("unable to compute lower right corner", "main"); } else { sprintf(msg, " output lower right corner: lat %13.8f long %13.8f\n", (DEG * geo.lat), (DEG * geo.lon)); LogInfomsg(msg); } /* If output data type not specified, then set to input data type (changes from SDS to SDS) */ if (param->output_data_type == -1) param->output_data_type = input->sds.type; /* Save the data type of this SDS for output to the metadata */ param_save->output_dt_arr[curr_sds] = param->output_data_type; /* Setup intermediate patches. Setup as the input data type. Then we will convert to the output data type later. */ patches = SetupPatches(¶m->output_space_def.img_size, param->patches_file_name, input->sds.type, input->fill_value, input->factor, input->offset); if (patches == (Patches_t *)NULL) LOG_ERROR("setting up intermediate patches data structure","main"); if (param->input_space_type != SWATH_SPACE) LOG_ERROR("input space type is not SWATH", "main"); sprintf(msg, " input lines/samples: %d %d\n", input->size.l, input->size.s); LogInfomsg(msg); sprintf(msg, " input scale factor: %g\n", input->factor); LogInfomsg(msg); sprintf(msg, " input offset: %lg\n", input->offset); LogInfomsg(msg); switch (input->ires) { case 1: LogInfomsg(" input resolution: 1 km\n"); break; case 2: LogInfomsg(" input resolution: 500 m\n"); break; case 4: LogInfomsg(" input resolution: 250 m\n"); break; } LogInfomsg(" %% complete: 0%"); /* For each input scan */ kscan = 0; for (iscan = 0; iscan < geoloc->nscan; iscan++) { /* Update status? */ if (100 * iscan / geoloc->nscan > kscan) { kscan = 100 * iscan / geoloc->nscan; if (kscan % 10 == 0) { sprintf(msg, " %d%%", kscan); LogInfomsg(msg); } } /* Read the geolocation data for the scan and map to output space */ if (!GetGeolocSwath(geoloc, output_space, iscan)) LOG_ERROR("reading geolocation for a scan", "main"); /* Map scan to input resolution */ if (!MapScanSwath(scan, geoloc)) LOG_ERROR("mapping a scan (swath)", "main"); /* Extend the scan */ if (!ExtendScan(scan)) LOG_ERROR("extending the scan", "main"); /* Read input scan data into extended scan */ il = iscan * input->scan_size.l; nl = input->scan_size.l; if (il + nl > input->size.l) nl = input->size.l - il; if (!GetScanInput(scan, input, il, nl)) LOG_ERROR("reading input data for a scan", "main"); /* Resample all of the points in the extended scan */ if (!ProcessScan(scan, kernel, patches, nl, param->kernel_type)) LOG_ERROR("resampling a scan", "main"); /* Toss patches that were not touched */ if (!TossPatches(patches, param->output_data_type)) LOG_ERROR("writting patches to disk", "main"); } /* End loop for each input scan */ /* Finish the status message */ LogInfomsg(" 100%\n"); /* Save the background fill value from the patches data structure for output to the metadata */ param_save->fill_value[curr_sds] = patches->fill_value; /* If output is raw binary, then we need the patches information so write the header before deleting the patches info */ if (param->output_file_format == RB_FMT) { /* Output is raw binary */ /* Create the raw binary header file */ if (!WriteHeaderFile (param, patches)) LOG_ERROR("writing raw binary header file", "main"); } /* Done with scan and kernel strutures */ if (!FreeScan(scan)) LOG_ERROR("freeing scan structure", "main"); if (!FreeKernel(kernel)) LOG_ERROR("freeing kernel structure", "main"); /* Close geolocation file */ if (!CloseGeoloc(geoloc)) LOG_ERROR("closing geolocation file", "main"); /* Close input file */ if (!CloseInput(input)) LOG_ERROR("closing input file", "main"); /* Free the output space structure */ if (!FreeSpace(output_space)) LOG_ERROR("freeing output space structure", "main"); /* Write remaining patches in memory to disk */ if (!UntouchPatches(patches)) LOG_ERROR("untouching patches", "main"); if (!TossPatches(patches, param->output_data_type)) LOG_ERROR("writting remaining patches to disk", "main"); if (!FreePatchesInMem(patches)) LOG_ERROR("freeing patches data structure in memory", "main"); /* Output format can be HDF, GeoTiff, raw binary, or both HDF and GeoTiff */ if (param->output_file_format == HDF_FMT || param->output_file_format == BOTH) { /* Output is HDF */ /* Create output file. If the output has multiple resolutions, then the resolution value will be used as an extension to the basename. Otherwise no resolution extension will be used. */ if (param->multires) { if (param->output_space_def.proj_num != PROJ_GEO) /* Output the pixel size with only two decimal places, since the pixel size will be in meters */ sprintf(HDF_File, "%s_%dm.hdf", param->output_file_name, (int) param->output_pixel_size[curr_sds]); else /* Output the pixel size with four decimal places, since the pixel size will be in degrees (need to convert from radians) */ sprintf(HDF_File, "%s_%.04fd.hdf", param->output_file_name, param->output_pixel_size[curr_sds] * DEG); } else { sprintf(HDF_File, "%s.hdf", param->output_file_name); } /* Does the HDF file need to be created? */ if (param->create_output[curr_sds]) { /* Create the output HDF file */ if (!CreateOutput(HDF_File)) LOG_ERROR("creating output image file", "main"); file_created = true; /* Loop through the rest of the SDSs and unmark the ones of the same resolution, since they will be output to this same HDF file and therefore do not need to be recreated. */ for (k = curr_sds; k < param_save->num_input_sds; k++) { if (param->output_pixel_size[k] == param->output_pixel_size[curr_sds]) param_save->create_output[k] = false; } } /* Open output file */ output = OutputFile(HDF_File, param->output_sds_name, param->output_data_type, ¶m->output_space_def); if (output == (Output_t *)NULL) LOG_ERROR("opening output HDF file", "main"); } if (param->output_file_format == GEOTIFF_FMT || param->output_file_format == BOTH) { /* Output is geotiff */ /* Attach the SDS name to the output file name */ if (param->output_file_format == GEOTIFF_FMT) { output = &output_mem; output->size.l = param->output_space_def.img_size.l; output->size.s = param->output_space_def.img_size.s; output->open = true; } /* Open and initialize the GeoTiff File */ MasterGeoMem = Open_GEOTIFF(param); if( ! MasterGeoMem ) { LOG_ERROR("allocating GeoTiff file id structure", "main"); } else if( MasterGeoMem->error ) { LOG_ERROR(MasterGeoMem->error_msg, "main"); } /* Remove due to clash of tiff and hdf header files. * if (!OpenGeoTIFFFile (param, &MasterGeoMem)) * LOG_ERROR("opening and initializing GeoTiff file", "main"); */ } if (param->output_file_format == RB_FMT) { /* Output is raw binary */ output = &output_mem; output->size.l = param->output_space_def.img_size.l; output->size.s = param->output_space_def.img_size.s; output->open = true; /* Get the size of the data type */ switch (param->output_data_type) { case DFNT_INT8: case DFNT_UINT8: /* one byte in size */ output->output_dt_size = 1; break; case DFNT_INT16: case DFNT_UINT16: /* two bytes in size */ output->output_dt_size = 2; break; case DFNT_INT32: case DFNT_UINT32: case DFNT_FLOAT32: /* four bytes in size */ output->output_dt_size = 4; break; } /* Copy the SDS name and remove any '/'s in the SDSname */ j = 0; for (i = 0; i < (int)strlen(param->output_sds_name); i++) { if (param->output_sds_name[i] != '/' && param->output_sds_name[i] != '\\') { sdsname[j++] = param->output_sds_name[i]; } sdsname[j] = '\0'; } /* Remove any spaces (from the SDS name) from the name */ k = 0; while (sdsname[k]) { if (isspace(sdsname[k])) sdsname[k] = '_'; k++; } /* Add the SDS band name and dat extension to the filename */ sprintf(filename, "%s_%s.dat", param->output_file_name, sdsname); rbfile = fopen(filename, "wb"); if (rbfile == NULL) LOG_ERROR("opening output raw binary file", "main"); } /* Read patches (in input data type) and write to output file (in output data type). If NN kernel, then fill any holes left from the resampling process. */ if (!UnscramblePatches(patches, output, param->output_file_format, MasterGeoMem, rbfile, param->output_data_type, param->kernel_type)) LOG_ERROR("unscrambling the output file", "main"); /* Done with the patches */ if (!FreePatches(patches)) LOG_ERROR("freeing patches", "main"); /* Close output HDF file */ if (param->output_file_format == HDF_FMT || param->output_file_format == BOTH) { if (!CloseOutput(output)) LOG_ERROR("closing output file", "main"); /* If not appending, write metadata to output HDF file */ if (file_created) { if (!WriteMeta(output->file_name, ¶m->output_space_def)) LOG_ERROR("writing metadata", "main"); } } /* Close output GeoTiff file */ if (param->output_file_format == GEOTIFF_FMT || param->output_file_format == BOTH) { Close_GEOTIFF( MasterGeoMem ); /* CloseGeoTIFFFile(&MasterGeoMem); */ output->open = false; } /* Close output raw binary file */ if (param->output_file_format == RB_FMT) { fclose(rbfile); output->open = false; } /* Free remaining memory */ if (!FreeGeoloc(geoloc)) LOG_ERROR("freeing geoloc file stucture", "main"); if (!FreeInput(input)) LOG_ERROR("freeing input file stucture", "main"); if (param->output_file_format == HDF_FMT || param->output_file_format == BOTH) { if (!FreeOutput(output)) LOG_ERROR("freeing output file stucture", "main"); } /* Get rid of patches file */ ThisPid = getpid(); sprintf(CharThisPid,"%d",(int)ThisPid); strcpy(FinalFileName,param->patches_file_name); strcat(FinalFileName,CharThisPid); exec_resamp = remove(FinalFileName); if(exec_resamp == -1) { LOG_ERROR("Something bad happened deleting patches file", "main"); } /* Free the parameter structure */ if (!FreeParam(param)) LOG_ERROR("freeing user parameter structure", "main"); } /* loop through bands in the current SDS */ } /* loop through SDSs */ /* If output format is HDF then append the metadata, for all resolutions */ if (param_save->output_file_format == HDF_FMT || param_save->output_file_format == BOTH) { /* Initialize the create_output structure again for all the SDSs. This will be used to determine if the metadata needs to be appended. */ for (curr_sds = 0; curr_sds < param_save->num_input_sds; curr_sds++) param_save->create_output[curr_sds] = true; /* Loop through all the SDSs */ for (curr_sds = 0; curr_sds < param_save->num_input_sds; curr_sds++) { /* Do we need to append the metadata or has it already been done for the current SDSs HDF file? */ if (!param_save->create_output[curr_sds]) continue; /* Determine the name of the output HDF file */ if (param_save->multires) { if (param_save->output_space_def.proj_num != PROJ_GEO) /* Output the pixel size with only two decimal places, since the pixel size will be in meters */ sprintf(HDF_File, "%s_%dm.hdf", param_save->output_file_name, (int) param_save->output_pixel_size[curr_sds]); else /* Output the pixel size with four decimal places, since the pixel size will be in degrees (need to convert from radians) */ sprintf(HDF_File, "%s_%.04fd.hdf", param_save->output_file_name, param_save->output_pixel_size[curr_sds] * DEG); } else { sprintf(HDF_File, "%s.hdf", param_save->output_file_name); } /* Append the metadata for this HDF file, only for the SDSs of the current resolution */ if (!AppendMetadata(param_save, HDF_File, param_save->input_file_name, curr_sds)) { /* NOTE: We won't flag this as an error, since in some cases the resolution file may not exist. For example, if a MOD02HKM is specified and the Latitude or Longitude data is specified, then that data is at a different resolution (1000m) than the rest of the image SDS data (500m). The software will think that there should be a 1000m product, however the Latitude and Longitude data didn't actually get processed .... since it is float data. So, AppendMetadata will flag an error since that HDF file will not really exist. */ /* LOG_ERROR("appending metadata to the output HDF file","main"); */ } /* Loop through the rest of the SDSs and unmark the ones of the same resolution, since they will be output to this same HDF file and therefore do not need to be recreated. */ for (k = curr_sds; k < param_save->num_input_sds; k++) { if (param_save->output_pixel_size[k] == param_save->output_pixel_size[curr_sds]) param_save->create_output[k] = false; } } } /* Free the saved parameter structure */ if (!FreeParam(param_save)) LOG_ERROR("freeing saved user parameter structure", "main"); /* Stop timer and print elapsed time */ enddate = time(NULL); sprintf(msg, "\nEnd Time: %s", ctime(&enddate)); LogInfomsg(msg); LogInfomsg("Finished processing!\n"); LogInfomsg( "*********************************************************************" "*********\n"); /* Close the log file */ CloseLogHandler(); /* All done */ exit (EXIT_SUCCESS); }
//////////////////////////////////////////////////////////////////////// // DumpColumnsInfo // //////////////////////////////////////////////////////////////////////// void DumpColumnsInfo ( DBORDINAL cColumns, DBCOLUMNINFO* rgColInfo, CTable* pCTable ) { WCHAR* pwszGuid = NULL; WCHAR pwszNum[10]; WCHAR* pwszPropID = NULL; HRESULT hr = S_OK; ASSERT(rgColInfo != NULL); OutputFile("%s[COLUMN] ColName iOrdinal, TYPE, ulColumnSize, bPrecision, bScale, dwFlags, Prefix, Suffix, ColIDKind, ColIDGuid, ColIDName", START_OF_TYPE); DumpLineEnd(); for(DBORDINAL i=0; i<cColumns; i++) { //Skip bookmark columns if(rgColInfo[i].iOrdinal == 0) continue; //Display ColumnInfo const static NAMEMAP rgColumnFlags[] = { VALUE_CHAR(DBCOLUMNFLAGS_ISBOOKMARK), VALUE_CHAR(DBCOLUMNFLAGS_MAYDEFER), VALUE_CHAR(DBCOLUMNFLAGS_WRITE), VALUE_CHAR(DBCOLUMNFLAGS_WRITEUNKNOWN), VALUE_CHAR(DBCOLUMNFLAGS_ISFIXEDLENGTH), VALUE_CHAR(DBCOLUMNFLAGS_ISNULLABLE), VALUE_CHAR(DBCOLUMNFLAGS_MAYBENULL), VALUE_CHAR(DBCOLUMNFLAGS_ISLONG), VALUE_CHAR(DBCOLUMNFLAGS_ISROWID), VALUE_CHAR(DBCOLUMNFLAGS_ISROWVER), VALUE_CHAR(DBCOLUMNFLAGS_CACHEDEFERRED), VALUE_CHAR(DBCOLUMNFLAGS_SCALEISNEGATIVE), VALUE_CHAR(DBCOLUMNFLAGS_ISCHAPTER), VALUE_CHAR(DBCOLUMNFLAGS_ISROWURL), VALUE_CHAR(DBCOLUMNFLAGS_ISDEFAULTSTREAM), VALUE_CHAR(DBCOLUMNFLAGS_ISCOLLECTION), }; //Format: {ColName(iOrdinal, TYPE, ulColumnSize, bPrecision, bScale, dwFlags} //ColumnName //fprintf replaces NULL with "(NULL)" which we don't want interpreted as the //column name, so just output an empty string for this case... OutputFile("%s%S%,", START_OF_TYPE, rgColInfo[i].pwszName ? rgColInfo[i].pwszName : L""); //iOrdinal OutputFile("%d,", rgColInfo[i].iOrdinal); //TYPE OutputFile("%S ", GetDBTypeName(rgColInfo[i].wType & ~(DBTYPE_BYREF | DBTYPE_ARRAY | DBTYPE_VECTOR)) ); if (rgColInfo[i].wType & DBTYPE_BYREF) OutputFile(" | DBTYPE_BYREF "); if (rgColInfo[i].wType & DBTYPE_ARRAY) OutputFile(" | DBTYPE_ARRAY "); if (rgColInfo[i].wType & DBTYPE_VECTOR) OutputFile(" | DBTYPE_VECTOR "); OutputFile(","); //ulColumnSize OutputFile("%ld,", rgColInfo[i].ulColumnSize ); //bPrecision OutputFile("%d,", rgColInfo[i].bPrecision ); //bScale OutputFile("%d,", rgColInfo[i].bScale ); //dwFlags OutputFile("%s,", GetNoteStringBitvals(NUMELEM(rgColumnFlags), rgColumnFlags, rgColInfo[i].dwFlags)); //ColIDKind OutputFile("%d,", rgColInfo[i].columnid.eKind); if (rgColInfo[i].columnid.eKind != DBKIND_NAME && rgColInfo[i].columnid.eKind != DBKIND_PROPID) { if(rgColInfo[i].columnid.eKind == DBKIND_GUID_NAME || rgColInfo[i].columnid.eKind == DBKIND_GUID_PROPID || rgColInfo[i].columnid.eKind == DBKIND_GUID) hr = StringFromCLSID(rgColInfo[i].columnid.uGuid.guid, &pwszGuid); else if(rgColInfo[i].columnid.uGuid.pguid) //It is a PGUID type. hr = StringFromCLSID(*(rgColInfo[i].columnid.uGuid.pguid), &pwszGuid); } switch (rgColInfo[i].columnid.eKind) { case DBKIND_GUID_NAME: OutputFile("%S,", pwszGuid); OutputFile("%S", rgColInfo[i].columnid.uName.pwszName); break; case DBKIND_GUID_PROPID: OutputFile("%S,", pwszGuid); _ultow(rgColInfo[i].columnid.uName.ulPropid, pwszNum, 10); OutputFile("%S", pwszNum); break; case DBKIND_NAME: OutputFile("%s,", ""); OutputFile("%S", rgColInfo[i].columnid.uName.pwszName); break; case DBKIND_PGUID_NAME: OutputFile("%S,", pwszGuid); OutputFile("%S", rgColInfo[i].columnid.uName.pwszName); break; case DBKIND_PGUID_PROPID: OutputFile("%S,", pwszGuid); _ultow(rgColInfo[i].columnid.uName.ulPropid, pwszNum, 10); OutputFile("%S", pwszNum); break; case DBKIND_PROPID: OutputFile("%s,", ""); _ultow(rgColInfo[i].columnid.uName.ulPropid, pwszNum, 10); OutputFile("%S", pwszNum); break; case DBKIND_GUID: OutputFile("%S,", pwszGuid); OutputFile("%s", ""); break; default: break; } //switch //Prefix Suffix. //Note: The prefix and suffix are not part of the ColumnInfo. So we have to look them //up in the CTable object, hopefully we created the table so we have this info left //around from the Schema rowset. WCHAR* pwszPrefix = NULL; WCHAR* pwszSuffix = NULL; CCol rCol; //We also use ColumnID matching, since DefaultQuery may be a superset of the OpenRowset TableCreation. if(SUCCEEDED(pCTable->GetColInfo(&rgColInfo[i].columnid, rCol))) { pwszPrefix = rCol.GetPrefix(); pwszSuffix = rCol.GetSuffix(); } //Prefix OutputFile(",%ls,", pwszPrefix); //Suffix OutputFile("%ls", pwszSuffix); //ENDL DumpLineEnd(); } SAFE_FREE(pwszGuid); DumpLineEnd(); DumpLineEnd(); OutputFile("%s[DATA] Type data", START_OF_TYPE); DumpLineEnd(); }
int main (int argc, const char * argv[]) { char* filePath = NULL; bool overwrite = false; ComponentDescription compDesc = {0, 0, 0, 0, 0}; AudioFileID inputFileID = 0; AudioFileID outputFileID = 0; CAStreamBasicDescription desc; AudioUnit theUnit = 0; setbuf (stdout, NULL); for (int i = 1; i < argc; ++i) { if (strcmp (argv[i], "-u") == 0) { if ( (i + 3) < argc ) { compDesc.componentType = str2OSType (argv[i + 1]); compDesc.componentSubType = str2OSType (argv[i + 2]); compDesc.componentManufacturer = str2OSType (argv[i + 3]); Component comp = FindNextComponent (NULL, &compDesc); if (comp == NULL) break; OpenAComponent (comp, &theUnit); i += 3; } else { printf ("Which Component:\n%s", usageStr); return -1; } } else if (strcmp (argv[i], "-f") == 0) { filePath = const_cast<char*>(argv[++i]); printf ("Input File:%s\n", filePath); } else if (strcmp (argv[i], "-o") == 0) { overwrite = true; } else { printf ("%s\n", usageStr); return -1; } } if (compDesc.componentType == 0) { printf ("Must specify AU:\n%s\n", usageStr); return -1; } if (theUnit == 0) { printf ("Can't find specified unit\n"); return -1; } if (filePath == NULL) { printf ("Must specify file to process:\n%s\n", usageStr); return -1; } OSStatus result = 0; if (result = InputFile (filePath, inputFileID)) { printf ("Result = %ld, parsing input file, exit...\n", result); return result; } UInt32 fileType; UInt32 size = sizeof (fileType); result = AudioFileGetProperty (inputFileID, kAudioFilePropertyFileFormat, &size, &fileType); if (result) { printf ("Error getting File Type of input file:%ld, exit...\n", result); return result; } size = sizeof (desc); result = AudioFileGetProperty (inputFileID, kAudioFilePropertyDataFormat, &size, &desc); if (result) { printf ("Error getting File Format of input file:%ld, exit...\n", result); return result; } if (desc.IsPCM() == false) { printf ("Only processing linear PCM file types and data:\n"); desc.Print(); return -1; } result = OutputFile (filePath, fileType, compDesc.componentSubType, overwrite, desc, outputFileID); if (result) { printf ("Error creating output file:%ld, exit...\n", result); return result; } // at this point we're ready to process return Process (theUnit, compDesc, inputFileID, desc, outputFileID); }
//////////////////////////////////////////////////////////////////////// // DumpProviderInfo // //////////////////////////////////////////////////////////////////////// void DumpProviderInfo(WCHAR* pwszProvider, WCHAR* pwszTableName, CHAR* pszCmdLine) { ASSERT(pwszProvider); ASSERT(pwszTableName); ASSERT(pszCmdLine); //Get Coordinated universal time: time_t ltime = 0; time(<ime); //Dump the Heading Information... ////////////////////////////////////////////////////////////////////// // OLE DB Conformance INI File // // File created by TableDump.exe generator version 1.50.3518 // on Thu Jul 24 17:19:57 1998 // ////////////////////////////////////////////////////////////////////// OutputFile("//////////////////////////////////////////////////////////////////////\n"); OutputFile("// OLE DB Conformance INI File\n"); OutputFile("//\n"); OutputFile("// File created by TableDump.exe generator version %s\n", VER_FILEVERSION_STR); OutputFile("// on %s", asctime(gmtime(<ime))); OutputFile("//\n"); OutputFile("//////////////////////////////////////////////////////////////////////\n"); DumpLineEnd(); //[INFO] OutputFile("%s[INFO] PROVIDER=; TABLENAME=; DEFAULTQUERY=;", START_OF_TYPE); DumpLineEnd(); //VERSION OutputFile("%sVERSION=%d,%d,%d,%d;", START_OF_TYPE, VER_FILEVERSION); DumpLineEnd(); //This line is needed. Although we are passing the entire CmdLine to //The INI File, TABLE= may not have been used, (CREATETABLE= case...) OutputFile("%sTABLE=%S; ", START_OF_TYPE, pwszTableName); //The first Format Specifier in the DefualtQuery signifies the TableName //Since our TableName is Unicode, it needs to be a capable %S not %s ASSERT(pszCmdLine); CHAR* pszFormat = strstr(pszCmdLine, "%s"); if(pszFormat) pszFormat[1] = 'S'; //Dump the entire InitString passed to TableDump //The Privlib.dll can filter which ones it wants and doesn't... //NOTE: pszCmdLine may contain a %S for the tablename, if it does //it will get filled in with the tablename also passed... OutputFile(pszCmdLine, pwszTableName); //END DumpLineEnd(); DumpLineEnd(); DumpLineEnd(); }
void Log::Output( LogLevel level,const string &str ) { OutputConsole(level,str); OutputFile(level,str); }
int main(void){ //allocate varuables particle_t* SPH = new particle_t[N_SPHP]; node_t* node = new node_t[3*N_SPHP]; system_t system; //display Information DisplayInfo(); printf("\n[Push enter key to start calculation...]\n"); getchar(); //make history dir if not exist. if(isExist("history") == false) MakeDir("history"); //set upt initial condition SetUpInitial<double>(SPH); InitializeProperty(SPH); OutputFile(SPH, system); printf("STEP %d (%16.16lf percent)\n", system.step, system.time / TIME * 100.0); /////////// TreeConstruction(SPH, node); TreeTraverse(SPH, node); //GetNeighbour(SPH); /////////// CalcHydroForce(SPH); GetTimestep(SPH, &system); //time integration while(system.time < TIME){ ++ system.step; //Compute v and u at half step. InitialKick(SPH, system.dt); //Advance x (, rho and h) by a full step. FullDrift(SPH, system.dt); //Predict v and u at full step. Predict(SPH, system.dt); //Time becomes t + dt. system.time += system.dt; //Construct Tree. TreeConstruction(SPH, node); for(int l = 0 ; l < 2 ; ++ l){ //Sweep0: Adjust smoothing length. CalcSmoothing(SPH); TreeTraverse(SPH, node); //GetNeighbour(SPH); //Sweep1: Compute density, div_v and rot_v. // Between this sweep, obtain p and c from rho and u. CalcDensity(SPH); } //Sweep2: Compute v_dot and u_dot. CalcHydroForce(SPH); //Set v and u at full step. FinalKick(SPH, system.dt); //Output result. if(system.step % OUTPUT_INTERVAL == 0) OutputFile(SPH, system); //Search dt. GetTimestep(SPH, &system); // CalcConservativeVaruables(SPH, &system); //Print message printf("STEP %d (%16.16lf percent)\n", system.step, system.time / TIME * 100.0); } //free memory. delete []SPH; delete []node; //Return success code. return SUCCESS; }
//////////////////////////////////////////////////////////////////////// // DumpURLInfo // //////////////////////////////////////////////////////////////////////// void DumpURLInfo(WCHAR* pwszDefURL, WCHAR* pwszRowURL, WCHAR* pwszTableName) { if(!pwszDefURL) return; WCHAR* pwszFormat = wcsstr(pwszDefURL, L"%s"); if(pwszFormat) pwszFormat[1] = 'S'; pwszFormat = wcsstr(pwszRowURL, L"%s"); if(pwszFormat) pwszFormat[1] = 'S'; CHAR* pszDefURL = ConvertToMBCS(pwszDefURL); CHAR* pszRowURL = ConvertToMBCS(pwszRowURL); //[URL] OutputFile("%s[URL] URLInfo", START_OF_TYPE); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_DSO", START_OF_DATA); OutputFile(pszDefURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_SESSION", START_OF_DATA); OutputFile(pszDefURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_ROWSET", START_OF_DATA); OutputFile(pszDefURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_ROW", START_OF_DATA); OutputFile(pszRowURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_STREAM", START_OF_DATA); OutputFile(pszRowURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); OutputFile("%s%s%s", START_OF_TYPE, "URL_COMMAND", START_OF_DATA); //TableDump will not fill in this field. Leaving it blank. //OutputFile(pszDefURL, pwszTableName); OutputFile("%s", END_OF_DATA); DumpLineEnd(); DumpLineEnd(); DumpLineEnd(); SAFE_FREE(pszDefURL); SAFE_FREE(pszRowURL); }
void GenerateSnapshot (CUniverse &Universe, CXMLElement *pCmdLine) { ALERROR error; int i; // Get some parameters int iInitialUpdateTime = 10; int iUpdateTime = pCmdLine->GetAttributeInteger(CONSTLIT("wait")); // Criteria CString sNode = pCmdLine->GetAttribute(CONSTLIT("node")); CString sCriteria = pCmdLine->GetAttribute(CONSTLIT("criteria")); // Output int cxWidth; int cyHeight; if (pCmdLine->FindAttributeInteger(CONSTLIT("size"), &cxWidth)) { cyHeight = cxWidth; } else { cxWidth = 1024; cyHeight = 1024; } // Paint flags DWORD dwPaintFlags = 0; if (pCmdLine->GetAttributeBool(CONSTLIT("noStars"))) dwPaintFlags |= CSystem::VWP_NO_STAR_FIELD; // Output file CString sFilespec = pCmdLine->GetAttribute(CONSTLIT("output")); if (!sFilespec.IsBlank()) sFilespec = pathAddExtensionIfNecessary(sFilespec, CONSTLIT(".bmp")); // Update context SSystemUpdateCtx Ctx; Ctx.bForceEventFiring = true; Ctx.bForcePainted = true; // Loop over all systems until we find what we're looking for int iLoops = 20; int iNodeIndex = 0; CTopologyNode *pNode = Universe.GetTopologyNode(iNodeIndex); while (true) { // Create the system CSystem *pSystem; if (error = Universe.CreateStarSystem(pNode, &pSystem)) { printf("ERROR: Unable to create star system.\n"); return; } // If this is the node we want, then search CSpaceObject *pTarget; if (sNode.IsBlank() || strEquals(sNode, pNode->GetID())) { printf("Searching %s...\n", pNode->GetSystemName().GetASCIIZPointer()); // Set the POV CSpaceObject *pPOV = pSystem->GetObject(0); Universe.SetPOV(pPOV); pSystem->SetPOVLRS(pPOV); // Prepare system Universe.UpdateExtended(); Universe.GarbageCollectLibraryBitmaps(); // Update for a while for (i = 0; i < iInitialUpdateTime; i++) Universe.Update(Ctx); // Compose the criteria CSpaceObject::Criteria Criteria; CSpaceObject::ParseCriteria(pPOV, sCriteria, &Criteria); // Get the list of all objects in the system that match the criteria CSpaceObject::SCriteriaMatchCtx Ctx(Criteria); TArray<CSpaceObject *> Results; for (i = 0; i < pSystem->GetObjectCount(); i++) { CSpaceObject *pObj = pSystem->GetObject(i); if (pObj && pObj->MatchesCriteria(Ctx, Criteria)) Results.Insert(pObj); } // Pick the appropriate object from the list if (Results.GetCount() == 0) pTarget = NULL; else if (Criteria.bNearestOnly || Criteria.bFarthestOnly) pTarget = Ctx.pBestObj; else pTarget = Results[mathRandom(0, Results.GetCount() - 1)]; } else pTarget = NULL; // If we found the target, then output if (pTarget) { // If we found the target, take a snapshot printf("Found %s.\n", pTarget->GetNounPhrase(0).GetASCIIZPointer()); // Wait a bit for (i = 0; i < iUpdateTime; i++) { if ((i % 100) == 99) printf("."); Universe.Update(Ctx); } if (iUpdateTime >= 99) printf("\n"); // Paint CG16bitImage Output; Output.CreateBlank(cxWidth, cyHeight, false); RECT rcViewport; rcViewport.left = 0; rcViewport.top = 0; rcViewport.right = cxWidth; rcViewport.bottom = cyHeight; pSystem->PaintViewport(Output, rcViewport, pTarget, dwPaintFlags); // Write to file if (!sFilespec.IsBlank()) { CFileWriteStream OutputFile(sFilespec); if (OutputFile.Create() != NOERROR) { printf("ERROR: Unable to create '%s'\n", sFilespec.GetASCIIZPointer()); return; } Output.WriteToWindowsBMP(&OutputFile); OutputFile.Close(); printf("%s\n", sFilespec.GetASCIIZPointer()); } // Otherwise, clipboard else { if (error = Output.CopyToClipboard()) { printf("ERROR: Unable to copy image to clipboard.\n"); return; } printf("Image copied to clipboard.\n"); } // Done break; } // Done with old system Universe.DestroySystem(pSystem); // Loop to the next node do { iNodeIndex = ((iNodeIndex + 1) % Universe.GetTopologyNodeCount()); pNode = Universe.GetTopologyNode(iNodeIndex); } while (pNode == NULL || pNode->IsEndGame()); // If we're back to the first node again, restart if (iNodeIndex == 0) { if (--iLoops > 0) { Universe.Reinit(); iNodeIndex = 0; pNode = Universe.GetTopologyNode(iNodeIndex); } else { printf("ERROR: Specified target could not be found.\n"); return; } } } }
int main(int argc,char *argv[]){ int i,j; Node node; Node *temp; Node *now; SpecialNode g; SpecialNode s; NodeList list; //printf("%c %c",argv[1],argv[2]); //printf("%d ",argc); s.x = atoi(argv[1]); s.y = atoi(argv[2]); //g.x = atoi(argv[3]); //g.y = atoi(argv[4]); //s.x = 1; //s.y = 1; g.x = 46; g.y = 22; if(InputFile(&list, &g, &s) == 0) { printf("Cannot Open File!"); exit(1); } SetStarValue(&list,&s); Display(&list); delay(4000); SetOverValue(&list,&g); Display(&list); delay(2000); SetValue(&list, &g, &s); now = &(list.node[s.x][s.y]); now->x = s.x; now->y = s.y; while(1) { now->openlist = close; for(i=now->y-1; i<=now->y+1; i++) { for(j=now->x-1; j<=now->x+1; j++) { if(j == now->x && i ==now->y) continue; if(list.node[j][i].num != '0' && list.node[j][i].openlist == none && list.node[j][i].num != '-' && list.node[j][i].num != '|' && list.node[j][i].num != '3' && list.node[j][i].num != '0' && list.node[j][i].num != '4' && list.node[j][i].num != 'E' && list.node[j][i].num != 'H' && list.node[j][i].num != 'C' && list.node[j][i].num != 'L' && list.node[j][i].num != '6' && list.node[j][i].num != 'I' && list.node[j][i].num != 'u' ) { cal(&node, now , g , i , j); Add_to_list(&(list.node[j][i]),node); list.node[j][i].link = now; } } } if(list.node[g.x][g.y].s != 0) break; temp = now; if(choose_next_now_node(&list,&now) == 0) { now = now->pre; if(now->x == s.x && now->y == s.y) { printf("Cannot Arrive destination!\n"); break; } continue; } else { now->pre = temp; } } OutputFile(&list,now); Display(&list); return 0; }