Ejemplo n.º 1
0
BOOL CBranch_patcherDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// Extra initialization here

	RECT cltRect;
	GetClientRect( &cltRect ),
	m_Display = new CRichEditCtrl();
	m_Display->Create( WS_CHILD|WS_VISIBLE|WS_BORDER|WS_HSCROLL|WS_VSCROLL|ES_AUTOHSCROLL|ES_AUTOVSCROLL|ES_MULTILINE,
					   CRect( 20, 180, cltRect.right-20, cltRect.bottom-20 ), this, 1 );

	// Initialize directories
	loadConfiguration();
	processCommandLine();
	displayTokens();

	EnteringTokens = false;
	m_SrcDirLabel = "Source Dir";
	m_TargetDirLabel = "Target Dir";
	UpdateData( false );
	((CButton*)GetDlgItem( IDC_DoPatch ))->EnableWindow( FALSE );

	return TRUE;  // return TRUE  unless you set the focus to a control
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
    int retval( EXIT_FAILURE );
    Environment.add( "WIPFC" );
    if( Environment.value( "WIPFC" ).empty() ) {
        printBanner();
        std::cout << "The 'WIPFC' environment variable needs to be set. ";
        std::cout << "It should contain the name of the directory containing .nls and entity.txt" << std::endl;
        return retval;
    }
    Environment.add( "IPFCARTWORK" );
    Environment.add( "IPFCIMBED" );
    Environment.add( "TMP" );
    Compiler c;
    try {
        processCommandLine(argc, argv, c);
        if( c.banner() ) {
            printBanner();
        }
        retval = c.compile();
    }
    catch( FatalError& e ) {
        c.printError( e.code );
    }
    catch( FatalIOError& e ) {
        c.printError( e.code, e.fname );
    }
    return retval;
}
Ejemplo n.º 3
0
int main(int argc, char** argv) {
  pthread_t * children;                   // dynamic array of child threads
  unsigned long id = 0;                   // loop control variable
  unsigned long numThreads = 0;           // desired # of threads
  unsigned long sumSquares = 0;
  unsigned long childsSquare = 0;
                                          // get desired # of threads
  numThreads = processCommandLine(argc, argv);
                                          // allocate array of handles
  children = malloc( numThreads * sizeof(pthread_t) );
                                          // FORK:
  for (id = 1; id < numThreads; id++) {
     pthread_create( &(children[id-1]),   // our handle for the child 
                      NULL,               // attributes of the child
                      child,              // the function it should run
                      (void*) id );       // args to that function
  }
  
  printf("The parent (main) thread computed %lu.\n", sumSquares);

  for (id = 1; id < numThreads; id++) {   // JOIN:
     pthread_join( children[id-1], (void**) &childsSquare );
     sumSquares += childsSquare;
  }

  printf("\nThe sum of the squares from 1 to %lu is %lu.\n\n",
          numThreads-1, sumSquares);
  
  free(children);                         // deallocate array

  return 0;
}
Ejemplo n.º 4
0
int main(int argc, char* argv[]){
  float vNumber=0.3;
  CommandLineArgs myArgs{};
  if(!processCommandLine(argc, argv, myArgs)){
    std::cout<<"ERROR processing command line"<<"\n";
    return 1;
    }
  if (myArgs.wantHelp){
    printHelp();
    return 0;
    }
  if (myArgs.wantVers){
    printVersion(vNumber);
    return 0;
    }

  //std::cout<<"Command line inputted \n iValue = "<<(myArgs.iValue=="")<<"\n";

 // The readStream functions handle the input of strings. It calls the transformChar function to ensure that all alphabet characters are capitalised and any other characters are ignored. 
  std::string bigString{""};
  if (myArgs.iValue == ""){
    bigString= read(std::cin);
    }
  else{
    std::ifstream in_file {myArgs.iValue};
    if (in_file.good()){
      bigString=read(in_file);
      }
    else {
      std::cout<<"Input file not OK to read \n";
      return 1;
      }
    }
  //std::cout<<"Cipher choice = "<<myArgs.cipherChoice<<"\n";
  std::string result; 
  
  
  
  auto myCipher = CipherFactory(myArgs.cipherChoice, myArgs.kValue);    
  
  if (myArgs.encOrDec) result = myCipher->encrypt(bigString);
  else if (myArgs.encOrDec == false) result = myCipher->decrypt(bigString);
  else std::cout<<"ERROR: Not sure whether to encrypt or decrypt \n";
  
  // And now to out put the results
  if (myArgs.oValue==""){
    std::cout<<"Result is here: "<<result<<"\n";
    outPut(std::cout, result);
    }
  else {
    std::ofstream out_file{myArgs.oValue};
    if (out_file.good()){
      outPut (out_file, result);
    }
    else {
      return 1;
    }
  }

}
Ejemplo n.º 5
0
int main(int argc, char* argv[]) {

	processCommandLine(argc, argv);
	//setParameters();

	load(input, pps);

	fvision::exitIf(pps.size() == 0, string("can not get point correspondences from the input file: ") + infilepath + " !");
	fvision::exitIf(pps.size() < 8, "at least 8 points should be input!");

	FundamentalMatrixCalculatorFactory::Configuration config;
	if (homographyBased) config.method = FundamentalMatrixCalculatorFactory::Configuration::HOMOGRAPHY_BASED;
	config.ransacDistanceThreshold = threshold;
	if (verbose) { cout<<"configuration: "<<endl<<config<<endl; }

	pfmc = FundamentalMatrixCalculatorFactory().create(config);

	CvMatWrapper fw = pfmc->compute(pps);
	const CvMat* F = fw.getMat();

	outputHelper.setDir(outputDir);
	outputHelper.setExtension("txt");

	if (verbose) { cout<<"F: "<<endl<<F<<endl; }

	if (f_filename != NULL) { outputHelper.save(f_filename, fw); }

	evaluateF(F, pps);

    return 0;
}
Ejemplo n.º 6
0
void IntlParametersBlock::processParametersBlock(ProcessString* processString, ClumpletWriter& pb)
{
	for (pb.rewind(); !pb.isEof(); pb.moveNext())
	{
		UCHAR tag = pb.getClumpTag();
		string s;

		switch (checkTag(tag))
		{
		case TAG_SKIP:
			break;

		case TAG_STRING:
			pb.getString(s);
			processString(s);
			pb.deleteClumplet();
			pb.insertString(tag, s);
			break;

		case TAG_COMMAND_LINE:
			pb.getString(s);
			processCommandLine(processString, s);
			pb.deleteClumplet();
			pb.insertString(tag, s);
			break;
		}
	}
}
Ejemplo n.º 7
0
  int main(int argc, char** argv){

    processCommandLine(argc, argv);
  
    // sturm test of Wilk -- slow (about 3-4 min)!
    testSturm(legendre4);

    SS = * new Sturm<NT> (legendre4);
    Interval v = SS.isolateRoot(3);
    std::cout << "3rd Root = " << v.first << ", " << v.second << std::endl; 
    v = SS.isolateRoot(1);
    std::cout << "1rd Root = " << v.first << ", " << v.second << std::endl; 
    v = SS.isolateRoot(5);
    std::cout << "5rd Root = " << v.first << ", " << v.second << std::endl; 

    v = SS.firstRootBelow(0);
    std::cout << "1st below 0 = " << v.first << ", " << v.second << std::endl; 
    v = SS.firstRootBelow(100);
    std::cout << "1st below 100 = "<< v.first << ", " << v.second << std::endl; 
    v = SS.firstRootAbove(0);
    std::cout << "1st above 0 = " << v.first << ", " << v.second << std::endl; 
    v = SS.firstRootAbove(-100);
    std::cout << "1st above -100 = "<<v.first << ", " << v.second << std::endl; 

    testSturm(wilk);

    return 0;
  }// main
Ejemplo n.º 8
0
/* main ()
**
** Scan the command line arguments, then enter into the command loop.
*/
int main (int argc, char ** argv) {
  checkHostCompatibility ();
  checkArithmetic ();
  processCommandLine (argc, argv);

  /* If the "write" option (-w) was given, write a file to the DISK. */
  if (commandOptionW) {
    writeCommand ();
  } else if (commandOptionI) {
    initializeCommand ();
  } else if (commandOptionL) {
    listCommand ();
  } else if (commandOptionC) {
    createCommand ();
  } else if (commandOptionR) {
    removeCommand ();
  } else if (commandOptionA) {
    addCommand ();
  } else if (commandOptionE) {
    extractCommand ();
  } else {
    fatalError ("No commands given; Use -h for help display");
    return -1;
  }

  return 0;
}
Ejemplo n.º 9
0
int main(int argc, char** argv) {
    pthread_t * children;                   // dynamic array of child threads
    unsigned long id = 0;                   // loop control variable
    unsigned long numThreads = 0;           // desired # of threads
    // get desired # of threads
    numThreads = processCommandLine(argc, argv);
    // allocate array of handles
    children = malloc( numThreads * sizeof(pthread_t) );
    // FORK:
    for (id = 1; id < numThreads; ++id) {
        pthread_create( &(children[id-1]),   // our handle for the child
                        NULL,               // attributes of the child
                        child,              // the function it should run
                        (void*) id );       // args to that function
    }

    do1000Transactions(0);

    for (id = 1; id < numThreads; ++id) {   // JOIN:
        pthread_join( children[id-1], NULL );
    }

    printf("\nThe final balance of the account using %lu threads is $%.2f.\n\n",
           numThreads, bankAccountBalance);

    free(children);                         // deallocate array
    cleanup();                              // deallocate mutex
    return 0;
}
Ejemplo n.º 10
0
int main(int argc, char** argv) {
  pthread_t * children;                   // dynamic array of child threads
  unsigned long id = 0;                   // loop control variable
  unsigned long numThreads = 0;           // desired # of threads
                                          // get desired # of threads
  numThreads = processCommandLine(argc, argv);
                                          // allocate array of handles
  children = malloc( numThreads * sizeof(pthread_t) );
                                          // FORK:
  for (id = 1; id < numThreads; id++) {
     pthread_create( &(children[id-1]),   // our handle for the child 
                      NULL,               // attributes of the child
                      childGreetings,     // the function it should run
                      (void*) id );       // args to that function
  }
  
  printf("Greetings from the parent, thread #0.\n");

  for (id = 1; id < numThreads; id++) {   // JOIN:
     pthread_join( children[id-1], NULL );
  }
  
  free(children);                         // deallocate array

  return 0;
}
Ejemplo n.º 11
0
void IntlParametersBlock::processParametersBlock(ProcessString* processString, ClumpletWriter& pb)
{
	const char* tagName = NULL;
	try
	{
		for (pb.rewind(); !pb.isEof(); )
		{
			UCHAR tag = pb.getClumpTag();
			string s;

			tagName = NULL;
			switch (checkTag(tag, &tagName))
			{
			case TAG_SKIP:
				pb.moveNext();
				break;

			case TAG_STRING:
				pb.getString(s);
				processString(s);
				pb.deleteClumplet();
				pb.insertString(tag, s);
				break;

			case TAG_COMMAND_LINE:
				pb.getString(s);
				processCommandLine(processString, s);
				pb.deleteClumplet();
				pb.insertString(tag, s);
				break;
			}
		}
	}
	catch (const Firebird::status_exception& st)
	{
		LocalStatus ls;
		CheckStatusWrapper l(&ls);
		st.stuffException(&l);
		if ((l.getState() & IStatus::STATE_ERRORS) && (l.getErrors()[1] == isc_bad_conn_str) && tagName)
		{
			Arg::Gds newErrors(isc_intl_char);
			newErrors << tagName;

			const ISC_STATUS* errors = l.getErrors();
			newErrors << Arg::StatusVector(errors + 2);		// skip isc_bad_conn_str

			l.setErrors(newErrors.value());
			status_exception::raise(&l);
		}

		// other case leave exception as is
		throw;
	}
}
Ejemplo n.º 12
0
/********
 * main()
 ********/
int main( int argc, char *argv[] )
{
	struct packet  p;
	char          *device;
	int			   sd;
	char 		   buffer[2000];
	int			   bytes_read = 0;
	
	
	/* comprobamos que el usuario es root */
	if( getuid() )
	{
	    printf( "You must be root to run this program\n" );
	    exit(1);	
	}
	
	/* procesamos la línea de comandos */
	processCommandLine( argc, argv, &device );
	
	/* inicializamos el gestor de conexiones */
	cntInitConnections();
	
	/* inicializamos el sniffer */
	sd = initSniffer( device );
	
	/* inicializamos la interfaz de usuario */
	if( uiInit() == -1 )
	{
		printf( "Error inicializando la interfaz de usuario\n" );
		exit(1);
	}
		
	/* bucle principal */
	for(;;)
	{
		/* actualizamos interfaz de usuario */
		if( uiUpdate() == FALSE )
			break;
		
		/* si ha llegado un paquete, lo procesamos en la interfaz de usuario, por ahora */
		if( bytes_read > 0 )
			uiProcessPacket( &p );
		/* refrescamos la interfaz de usuario */
		uiRefresh();
		
		/* leemos un paquete si hay */
		bytes_read = readPacket( sd, buffer, 2000, &p );
	}
	
	/* salimos de la aplicación */
	uiEnd();
	endSniffer( device, sd );
}
Ejemplo n.º 13
0
int main(int argc, char** argv)
{
  exitFunction = myExit; 

  NUM_BRANCHES = 1; // BAD 

  if(argc < 2) 
    {
      printUsage(std::cout);
      exitFunction(-1, false); 
    }

  auto files = std::vector<std::string>{};
  double burnin = 0; 
  auto id = std::string{};

  std::tie(id,files,burnin) = processCommandLine(argc, argv); 

  for(auto f : files)
    std::cout  << "file: " << f << std::endl; 

  for(auto file : files)
    {
      if(not std::ifstream(file))
	{
	  std::cerr << "Error: could not open file >" <<  file  << "<" << std::endl; 
	  exitFunction(-1, false); 
	}    
    }

  assert(files.size() >  0); 

  auto&& bipEx = BipartitionExtractor(files, false, true);

  nat numTree = bipEx.getNumTreesInFile( files.at(0) );
  
  // std::cout <<  "have "<< numTree << std::endl; 
  
  nat absBurnin = nat(double(numTree) * burnin); 

  bipEx.extractBips<true>(absBurnin);
  bipEx.printBipartitions(id);
  bipEx.printBipartitionStatistics(id); 
  bipEx.printFileNames(id);
  bipEx.printBranchLengths(id);

  return 0; 
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
  CommandLineInfo info;
  processCommandLine(argc,argv,info);
  
  std::string in{""};
  char in_char{'x'};

  if(info.input_file_name == "")
    {
      while(std::cin >> in_char) // Builds output from input
	{
	  in += transformChar(in_char);
	}
    }
  else
    {
Ejemplo n.º 15
0
Archivo: main.cpp Proyecto: alibaba/xoc
int main(int argcc, char * argvc[])
{
    UNUSED(argcc);
    UNUSED(argvc);

    CHAR * argv[] = {
        "d2d.exe",
        //"test.apk",
        "-o", "output.dex",
    };
    int argc = sizeof(argv)/sizeof(argv[0]);
#else
int main(int argc, char const* argv[])
{
#endif
    int locerrno = 0; //0 indicates no error.
    long filelen;
    if (!processCommandLine(argc, argv)) {
        locerrno = -1;
        goto FIN;
    }

    if (g_tfile != NULL && g_dump_dex_file_path) {
        fprintf(g_tfile, "\n==---- %s ----==\n", g_dex_file_path);
    }

    if (d2dEntry(g_source_file_handler, g_output_file_handler,
                 &filelen, false, g_dex_file_path) != 0) {
        locerrno = errno;
        LOGE("error: perform dexpro failed.\n");
    }

FIN:
    if (g_source_file_handler >= 0) {
        close(g_source_file_handler);
    }

    if (g_output_file_handler >= 0) {
        close(g_output_file_handler);
    }

    xoc::finidump();

    return locerrno; //success.
}
Ejemplo n.º 16
0
int main( int argc, char** argv )
{
	QApplication app( argc, argv );

	Config* config = new Config( &app );

	// If we can't process the command-line or set up the database
	// there's no point continuing
	if ( !processCommandLine() || !setupDatabase() )
		return 0;

	QDeclarativeView view;

	view.connect( view.engine(), SIGNAL(quit()), SLOT(close()) );
	view.setResizeMode( QDeclarativeView::SizeRootObjectToView );

	// Register custom types for access to certail enums from QML
	qmlRegisterType< SoundEngine >( "net.randalflagg.llamaui", 1, 0, "SoundEngine" );
	qmlRegisterType< KeyboardMap >( "net.randalflagg.llamaui", 1, 0, "KeyboardMap" );
	qmlRegisterType< SystemProcess >( "net.randalflagg.llamaui", 1, 0, "SystemProcess" );

	QDeclarativeContext* rootContext = view.rootContext();

	// Initalise the keyboard key/action mapper
	if ( !initKeyboardMap( rootContext ) )
		return 0;

	rootContext->setContextProperty( "config", config );
	initSoundEngine( rootContext );
	initGameMenu( rootContext );
	initEmulatorMenu( rootContext );
	initSystemMenu( rootContext );
	initGameLauncher( rootContext );

	// Create the interface
	QDir dir( Config::instance()->value( "paths", "qmlDir" ).toString() );
	view.setSource( QUrl::fromLocalFile( dir.absoluteFilePath( "main.qml" ) ) );
	view.showFullScreen();

	// Hide the mouse cursor
	app.setOverrideCursor( QCursor( Qt::BlankCursor ) );

	return app.exec();
}
int main(int argc, char** argv) {
    // Final sum
    unsigned long long finalSum;

    // Timing values
    clock_t startTime, stopTime;

    // Start the timer
    startTime = clock();

    // Get the maximum N
    unsigned long long maximum = processCommandLine(argc, argv);

    finalSum = sum_range(0, maximum); // Start from 0 and go to the maximum (from command line)

    stopTime = clock();

    printf("Final sum with 1 processor  in %f seconds is: %llu\n", \
            (double)(stopTime - startTime) / CLOCKS_PER_SEC, finalSum);

    return 0;
}
Ejemplo n.º 18
0
/* main()
**
** Read and print .o file.
*/
int main (int argc, char ** argv) {
    int i, lineNumber;
    int magic;
    int sawEntryLabel;
    processCommandLine (argc, argv);
    printf ("=====  HEADER INFO  =====\n\n");
    magic = readInteger ();
    if (magic == 0x424C5A6F) {
      printf ("magic number = BLZo (This is a '.o' file.)\n");
    } else if (magic == 0x424C5A78) {
      printf ("magic number = BLZx (This is an 'a.out' file.)\n");
    } else {
      fatalError ("Magic number is not 'BLZo' or 'BLZx'");
    }
    if (magic == 0x424C5A78) {   /* if we have an a.out file... */
      textSize = readInteger ();
      dataSize = readInteger ();
      bssSize = readInteger ();
      printf (".text size = %08x (%d)\n", textSize, textSize);
      printf (".data size = %08x (%d)\n", dataSize, dataSize);
      printf (".bss size =  %08x (%d)\n", bssSize, bssSize);
      textAddr = readInteger ();
      dataAddr = readInteger ();
      bssAddr = readInteger ();
      printf (".text load addr = %08x (%d)\n", textAddr, textAddr);
      printf (".data load addr = %08x (%d)\n", dataAddr, dataAddr);
      printf (".bss load addr =  %08x (%d)\n", bssAddr, bssAddr);
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
      printf ("\n=====  TEXT SEGMENT  =====\n\n");
      count = textSize;
      printSegment (textAddr);
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
      printf ("\n=====  DATA SEGMENT  =====\n\n");
      count = dataSize;
      printSegment (dataAddr);
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
      printf ("\n=====  LABEL INFORMATION  =====\n\n");
      printf ("Value   (in decimal)  Label\n");
      printf ("====================  ==================\n");
      while (1) {
        len = readInteger ();
        if (len <= 0) break;
        value = readInteger ();
        printf ("%08x%12d  ", value, value);
        for (; len>0; len--) {
          i = readByte ();
          printf ("%c", i);
        }
        printf ("\n");
      }
  
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
  
    } else {   /* if we have an .o file... */
      sawEntryLabel = readInteger ();
      if (sawEntryLabel == 1) {
        printf (".text contains _entry = TRUE\n");
      } else if (sawEntryLabel == 0) {
        printf (".text contains _entry = FALSE\n");
      } else {
        fatalError ("sawEntryLabel has invalid value");
      }
      textSize = readInteger ();
      dataSize = readInteger ();
      bssSize = readInteger ();
      printf (".text size = %08x (%d)\n", textSize, textSize);
      printf (".data size = %08x (%d)\n", dataSize, dataSize);
      printf (".bss size =  %08x (%d)\n", bssSize, bssSize);
      printf ("\n=====  TEXT SEGMENT  =====\n\n");
      count = textSize;
      printSegment (0);
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
      printf ("\n=====  DATA SEGMENT  =====\n\n");
      count = dataSize;
      printSegment (0);
  
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
  
      printf ("\n=====  SYMBOL TABLE  =====\n\n");
      printf ("Number  Value     Relative to   Symbol\n");
      printf ("======  ========  ===========   ======\n");
      while (1) {
        symbolNum = readInteger ();
        if (symbolNum == 0) break;
        value = readInteger ();
        relativeTo = readInteger ();
        len = readInteger ();
        printf ("%d\t%08x\t%d\t", symbolNum, value, relativeTo);
        for (; len>0; len--) {
          i = readByte ();
          printf ("%c", i);
        }
        printf ("\n");
      }
  
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
  
      printf ("\n=====  RELOCATION INFO  =====\n\n");
      printf ("Type    Locatn-to-modify New-val  Rel-to Src-Line\n");
      printf ("======= ================ ======== ====== ========\n");
      while (1) {
        i = readInteger ();
        if (i == 0) {
          break;
        } else if (i == 1) {
          printf ("8-bit\t");
        } else if (i == 2) {
          printf ("16-bit\t");
        } else if (i == 3) {
          printf ("24-bit\t");
        } else if (i == 4) {
          printf ("32-bit\t");
        } else if (i == 5) {
          printf ("set-hi\t");
        } else if (i == 6) {
          printf ("set-lo\t");
        } else if (i == 7) {
          printf ("ldaddr\t");
        } else {
          fatalError ("Invalid relocation record code");
        }
        value = readInteger ();
        printf ("%08x ", value);
        i = readInteger ();
        if (i == 1) {
          printf (".text\t");
        } else if (i == 2) {
          printf (".data\t");
        } else {
          printf ("*****\t");
        }
        value = readInteger ();
        printf (" %08x ", value);
        value = readInteger ();
        printf ("%4d   ", value);
        lineNumber = readInteger ();
        printf ("%6d  \n", lineNumber);
      }
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
  
      printf ("\n=====  ADDRESS LABELS  =====\n\n");
      printf ("Segment Offset    Label\n");
      printf ("======= ========  =====\n");
      while (1) {
        i = readInteger ();
        if (i == 0) break;
        if (i == 1) printf (".text\t");
        if (i == 2) printf (".data\t");
        if (i == 3) printf (".bss\t");
        value = readInteger ();
        len = readInteger ();
        printf ("%08x  ", value);
        for (; len>0; len--) {
          i = readByte ();
          printf ("%c", i);
        }
        printf ("\n");
      }
  
      magic = readInteger ();
      if (magic != 0x2a2a2a2a) {
        fatalError ("Invalid file format - missing \"****\" separator");
      }
    }

    return 0;
}
Ejemplo n.º 19
0
// -----------------------------------------------------------------------------
// Application initialisation
// -----------------------------------------------------------------------------
bool App::init(vector<std::string>& args, double ui_scale)
{
	// Get the id of the current thread (should be the main one)
	main_thread_id = std::this_thread::get_id();

	// Set locale to C so that the tokenizer will work properly
	// even in locales where the decimal separator is a comma.
	setlocale(LC_ALL, "C");

	// Init application directories
	if (!initDirectories())
		return false;

	// Init log
	Log::init();

	// Process the command line arguments
	auto paths_to_open = processCommandLine(args);

	// Init keybinds
	KeyBind::initBinds();

	// Load configuration file
	Log::info("Loading configuration");
	readConfigFile();

	// Check that SLADE.pk3 can be found
	Log::info("Loading resources");
	archive_manager.init();
	if (!archive_manager.resArchiveOK())
	{
		wxMessageBox(
			"Unable to find slade.pk3, make sure it exists in the same directory as the "
			"SLADE executable",
			"Error",
			wxICON_ERROR);
		return false;
	}

	// Init SActions
	SAction::initWxId(26000);
	SAction::initActions();

	// Init lua
	Lua::init();

	// Init UI
	UI::init(ui_scale);

	// Show splash screen
	UI::showSplash("Starting up...");

	// Init palettes
	if (!palette_manager.init())
	{
		Log::error("Failed to initialise palettes");
		return false;
	}

	// Init SImage formats
	SIFormat::initFormats();

	// Init brushes
	SBrush::initBrushes();

	// Load program icons
	Log::info("Loading icons");
	Icons::loadIcons();

	// Load program fonts
	Drawing::initFonts();

	// Load entry types
	Log::info("Loading entry types");
	EntryDataFormat::initBuiltinFormats();
	EntryType::loadEntryTypes();

	// Load text languages
	Log::info("Loading text languages");
	TextLanguage::loadLanguages();

	// Init text stylesets
	Log::info("Loading text style sets");
	StyleSet::loadResourceStyles();
	StyleSet::loadCustomStyles();

	// Init colour configuration
	Log::info("Loading colour configuration");
	ColourConfiguration::init();

	// Init nodebuilders
	NodeBuilders::init();

	// Init game executables
	Executables::init();

	// Init main editor
	MainEditor::init();

	// Init base resource
	Log::info("Loading base resource");
	archive_manager.initBaseResource();
	Log::info("Base resource loaded");

	// Init game configuration
	Log::info("Loading game configurations");
	Game::init();

	// Init script manager
	ScriptManager::init();

	// Show the main window
	MainEditor::windowWx()->Show(true);
	wxGetApp().SetTopWindow(MainEditor::windowWx());
	UI::showSplash("Starting up...", false, MainEditor::windowWx());

	// Open any archives from the command line
	for (auto& path : paths_to_open)
		archive_manager.openArchive(path);

	// Hide splash screen
	UI::hideSplash();

	init_ok = true;
	Log::info("SLADE Initialisation OK");

	// Show Setup Wizard if needed
	if (!setup_wizard_run)
	{
		SetupWizardDialog dlg(MainEditor::windowWx());
		dlg.ShowModal();
		setup_wizard_run = true;
		MainEditor::windowWx()->Update();
		MainEditor::windowWx()->Refresh();
	}

	return true;
}
Ejemplo n.º 20
0
int main(int argc, char **argv)
{
  exitFunction = myExit; 

  NUM_BRANCHES = 1;   // BAD

  if(argc < 2 ) 
    {
      printUsage(std::cout);
      exitFunction(-1, false); 
    }

  bool isMre = false;   
  auto threshold = double{0.}; 
 
  std::string id= {}; 
  double burnin = 0; 
  auto files = std::vector<std::string>{}; 

  std::tie(id, files, burnin, threshold, isMre) = processCommandLine(argc, argv);

  for(auto &file : files)
    {
      if(not std::ifstream(file))
	{
	  std::cerr << "Error: could not open file >" << file << "<" << std::endl; 
	  exitFunction(-1, false); 
	}    
    }

  assert(threshold > 1); 
  threshold /= 100.; 

  auto&& ct = ConsensusTree(files, burnin, threshold,isMre); 
  auto header = ct.getTreeHeader(); 
  auto result = ct.getConsensusTreeString(false);
  auto type = ct.getType();

  auto&& ss = std::stringstream{}; 
  ss << PROGRAM_NAME << "_" << type << "Nexus." << id; 

  auto &&ss2 = std::ostringstream{}; 
  ss2 << PROGRAM_NAME << "_" << type << "Newick." << id ; 

  if(std::ifstream(ss.str()))
    {
      std::cerr << std::endl << "File " << ss.str() << " already exists (probably \n"
		<< "left over from a previous run). Please choose a new run-id or remove\n"
		<< "previous output files." << std::endl; 
      exitFunction(-1, false); 
    }

  auto &&outfile = std::ofstream(ss.str()); 
  outfile << header  << result << std::endl; 
  outfile << "end;" << std::endl; 


  auto &&outfile2 = std::ofstream{ss2.str()}; 
  outfile2 << ct.getConsensusTreeString(true) << std::endl; 


  std::cout << "Printed consensus tree in nexus format to " << ss.str() << std::endl; 
  std::cout << "Printed consensus tree in newick format to " << ss2.str() << std::endl; 

  return 0; 
}
Ejemplo n.º 21
0
Archivo: main.c Proyecto: mitp0sh/bin2h
int
main
(
    int         argc,
    const char* argv[]
)
{
    /* local function variables */
    FILE*        fp = NULL;
    long        len = 0;
    char* file_buff = NULL;
    int      status = EXIT_SUCCESS;
    FILE*    fp_out = NULL;
    unsigned int  i = 0;
    /* ------------------------- */
    
    if(argc == 1)
    {
        printHeader();
        printUsage(argv[0]);
        return status;
    }
    
    /* process commandline arguments */
    processCommandLine(argc, argv);
    
    if((fp = fopen(binary_file, "rb")) == NULL)
    {
        printf("öaa");
        printHeader();
        printUnableToReadBinary();
        status = EXIT_FAILURE;
        goto bail;
    }
    
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    
    /* allocate memory for binary file */
    if((file_buff = (char *)malloc((size_t)len)) == NULL)
    {
        printHeader();
        printUnableToAllocateMemory();
        status = EXIT_FAILURE;
        goto bail_1;
    }
    
    /* read binary */
    if(fread(file_buff, 1, len, fp) != len)
    {
        printHeader();
        printUnableToReadBinary();
        status = EXIT_FAILURE;
        goto bail_2;
    }
    
    printf("\n");
    printf("  [OK] - %s - binary successfully read.\n", binary_file);
        
    /* create/open output file */
    fp_out = fopen(header_file, "w+b");
    if(fp_out == NULL)
    {
        printHeader();
        printUnableToCreateHeaderFile();
        status = EXIT_FAILURE;
        goto bail_2;
    }
    
    printf("  [OK] - %s - header file ready for processing.\n", header_file);
    
    fprintf(fp_out, "#ifndef BLOBHEADER_H\n");
    fprintf(fp_out, "    #define BLOBHEADER_H\n");
    fprintf(fp_out, "\n");
    fprintf(fp_out, "static const char %s[] = \n", blob_name);
    fprintf(fp_out, "{\n");
    
    /* process all bytes */
    for(i = 1; i < len + 1; i++)
    {
        if((i - 1) % 8 == 0)
        {
            fprintf(fp_out, "    ");
        }
        
        fprintf(fp_out, "(char)0x%02x", file_buff[i - 1] & 0xFF);
    
        if(i < len)
        {
            fprintf(fp_out, ", ");
        }
        else
        {
            fprintf(fp_out, "\n");
        }
        
        if(i % 8 == 0)
        {
            fprintf(fp_out, "\n");
        }
    }
    
    fprintf(fp_out, "};\n");
    fprintf(fp_out, "\n");
    fprintf(fp_out, "#endif");
    fprintf(fp_out, "\n");
    fclose(fp_out);
    
    printf("  [OK] - successfully finished!\n");
    printf("\n");
    
    /* everything went fine */
bail_2:
    free(file_buff);
bail_1:
    fclose(fp);
bail:
    fflush(stdout);
    return EXIT_SUCCESS;
}
Ejemplo n.º 22
0
int
main(int         in_argc,
     const char* in_argv[])
{
   MPMGlobalState::initGlobalState();

   if (processCommandLine(in_argc, in_argv) == false) {
      cout << "MPMerger v" << sg_pProgramVersion << '\n'
           << " MultiPalette Merger\n"
           << " @ Dynamix 1998, Original author Dave Moore\n\n";
      usage();
      return EXIT_FAILURE;
   }

   MPMGlobalState* pGlobalState = MPMGlobalState::getGlobalState();

   // Set up the options for this run...
   //
   MPMOptions  instOptions;           // Options for this run
   MPMFileList procFileList;          // List of files to process
   if (instOptions.attachResponseFile(pGlobalState->getResponseFileName()) == false) {
      cerr << "Unable to open response file: "
           << pGlobalState->getResponseFileName() << '\n'
           << " - ABORTING - \n";
      return EXIT_FAILURE;
   }
   if (instOptions.validateOptions() == false) {
      cerr << "Invalid options detected, exiting...\n\n";
      exit(1);
   }
   
   instOptions.processResponseFile(procFileList);
   AssertFatal(procFileList.getNumFiles() <= MAX_MULTI_PALETTES, "Too many palettes, exiting...");

   // Whether we are choosing colors or rendering, we need the unquantized palettes,
   //  so load them into memory...
   //
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pRawPalette == NULL, "Huh?");
      AssertFatal(rFileEntry.pFileName   != NULL, "Huh?");

      rFileEntry.pRawPalette = GFXPalette::load(rFileEntry.pFileName);

      if (rFileEntry.pRawPalette == NULL) {
         cerr << "main(): Unable to load file: " << rFileEntry.pFileName << '\n';
         exit(1);
      }
   }

   // We will need an authoritative final palette either way as well...
   //
   GFXPalette* pFinalMasterPalette = new GFXPalette;
   memset(pFinalMasterPalette->palette[0].color, 0, sizeof(PALETTEENTRY) * 256);
   if (instOptions.hasBasePalette() == true) {
      const char* pPaletteName = instOptions.getBasePalName();
      AssertFatal(pPaletteName != NULL, "No base palette name?  Here?");

      Bool palLoadSuccess = pFinalMasterPalette->read(pPaletteName);
      if (palLoadSuccess == false) {
         cerr << "Unable to load base palette: " << pPaletteName << ". Exiting...\n";
         exit(1);
      }
   }

   // We are always choosing colors for the master palette, so create a Popularity Table,
   //  and register our colors...
   //
   MPMPopularityTable popTable(instOptions);
   popTable.prepFixedColors(instOptions, pFinalMasterPalette);
   bool haveSomeRealColors = false;
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pRawPalette != NULL, "Huh?");

      if (rFileEntry.pRawPalette->palette[0].paletteType == GFXPalette::ColorQuantPaletteType) {
         printf(".");
         popTable.registerRGBColors(rFileEntry.pRawPalette, rFileEntry.fileWeight);
         haveSomeRealColors = true;
      } else
         printf("*");
   }

   // If we have NO files, we're just copying from the base palette to the new palette...
   if (procFileList.getNumFiles() == 0) {
      
   } else {
      AssertFatal(haveSomeRealColors == true, "Must have a least _one_ non-alpha palette...");
      
      // Quantize out the master palette..
      popTable.quantizeColors(instOptions, pFinalMasterPalette);
   }

   // Insert the mandatory entries into the master palette.  These are:
   //  palette[0].type  = HazeShadePaletteType
   //  palette[0].index = DWORD(-1)
   //           color[0]: (0, 0, 0)
   //         color[255]: (1, 1, 1)
   //         color[254]: instOptions.hazeColor
   //          hazeColor: 254
   //       correct bitvector entries.  renderStart-Last + 0, 254, 254
   //
   PALETTEENTRY hazeColor;
   PALETTEENTRY black, white;
   black.peRed = black.peGreen = black.peBlue = black.peFlags = 0;
   white.peRed = white.peGreen = white.peBlue = 255;
   white.peFlags = 0;
   hazeColor.peRed   = UInt8((instOptions.getHazeColor().red   * 255.0f) + 0.5f);
   hazeColor.peGreen = UInt8((instOptions.getHazeColor().green * 255.0f) + 0.5f);
   hazeColor.peBlue  = UInt8((instOptions.getHazeColor().blue  * 255.0f) + 0.5f);
   hazeColor.peFlags = 0;
   pFinalMasterPalette->palette[0].color[0]     = black;
   pFinalMasterPalette->palette[0].color[255]   = white;
   pFinalMasterPalette->palette[0].color[254]   = hazeColor;
   pFinalMasterPalette->palette[0].paletteIndex = DWORD(-1);
   pFinalMasterPalette->palette[0].paletteType  = GFXPalette::ShadeHazePaletteType;
   pFinalMasterPalette->hazeColor = 254;

   UInt32 renderFirst, renderLast;
   instOptions.getMasterRenderRange(renderFirst, renderLast);
   pFinalMasterPalette->allowedColorMatches.zero();
   for (UInt32 i = renderFirst; i <= renderLast; i++)
      pFinalMasterPalette->allowedColorMatches.set(i);
   pFinalMasterPalette->allowedColorMatches.set(0);
//   pFinalMasterPalette->allowedColorMatches.set(255);
   pFinalMasterPalette->allowedColorMatches.set(254);

   // Insert the shadow palette...
   //
   pFinalMasterPalette->palette[1].paletteIndex = -2;
   pFinalMasterPalette->palette[1].paletteType  = GFXPalette::TranslucentPaletteType;
   for (int i = 0; i < 256; i++) {
      pFinalMasterPalette->palette[1].color[i].peRed   = 0;
      pFinalMasterPalette->palette[1].color[i].peGreen = 0;
      pFinalMasterPalette->palette[1].color[i].peBlue  = 0;
      pFinalMasterPalette->palette[1].color[i].peFlags = i;
   } 
   pFinalMasterPalette->numPalettes++;

   // Ok, now we need to map the multipalettes into the master palette...
   //
   MPMMerger mpmMerger(instOptions);
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      mpmMerger.insertPalette(pFinalMasterPalette, rFileEntry.pRawPalette);
   }

   // And create the remap tables if necessary...
   //
   mpmMerger.createRemapTables(pFinalMasterPalette);

   // And we are DONE!  Write out the master palette to the specified name...
   //
   // First make sure that in no palettes any color other than 0 is fully black
   //
   for (int i = 0; i < pFinalMasterPalette->numPalettes; i++) {
      GFXPalette::MultiPalette& rMPalette = pFinalMasterPalette->palette[i];

      for (int j = 1; j < 256; j++) {
         PALETTEENTRY& rPEntry = rMPalette.color[j];
         if (rPEntry.peRed   == 0 &&
             rPEntry.peGreen == 0 &&
             rPEntry.peBlue  == 0)
            rPEntry.peBlue = 1;
      }
   }

   AssertFatal(instOptions.getOutputPalName() != NULL, "Error, no output name!");
   pFinalMasterPalette->write(instOptions.getOutputPalName());

   //-------------------------------------- Clean-up
   delete pFinalMasterPalette;
   MPMGlobalState::shutdownGlobalState();
   return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
int _tmain(int argc, _TCHAR* argv[])
{
	FILE* f;
	KTX_error_code ret;
	KTX_texture_info tinfo;
	KTX_image_info* infiles;
	struct commandOptions options;
	unsigned int imageSize;
	int exitCode = 0, face, i;
	unsigned int levelWidth, levelHeight;
	FileResult readResult;
	boolean useStdin = false;
	unsigned char* kvData = NULL;
	unsigned int kvDataLen = 0;

	processCommandLine(argc, argv, options);

	infiles = new KTX_image_info[options.numInputFiles];

	if (options.cubemap)
		tinfo.numberOfFaces = 6;
	else
		tinfo.numberOfFaces = 1;

	// TO DO: handle array textures
	tinfo.numberOfArrayElements = 0;

	// TO DO: handle 3D textures. Concatenate the files here or in WriteKTXF?

	if (!options.lower_left_maps_to_s0t0) {
		// Non-standard orientation. Add metadata.
		KTX_hash_table ht = ktxHashTable_Create();
		char orientation[10];

		assert(strlen(KTX_ORIENTATION2_FMT) < sizeof(orientation));
		_snprintf(orientation, sizeof(orientation), KTX_ORIENTATION2_FMT, 'r', 'd');
		ktxHashTable_AddKVPair(ht, KTX_ORIENTATION_KEY, strlen(orientation) + 1,
							   orientation);
		if (KTX_SUCCESS != ktxHashTable_Serialize(ht, &kvDataLen, &kvData)) {
			fprintf(stderr, "%s: Out of memory\n", options.appName);
			exit(2);
		}
		ktxHashTable_Destroy(ht);
	}

	for (i = 0; i < options.numInputFiles; i++) {
		_TCHAR* infile;

		if (options.useStdin) {
			infile = 0;
			f = stdin;
			if (WIN32) {
				/* Set "stdin" to have binary mode */
				(void)_setmode( _fileno( stdin ), _O_BINARY );
			}
		} else {
			infile = argv[options.firstInfileIndex + i];
			f = fopen(infile,"rb");
		}

		if (f) {
			unsigned int w, h, components, componentSize;
			unsigned char* srcImg;

			readResult = readNPBM(f, w, h, components, componentSize, imageSize, srcImg);
			if (SUCCESS == readResult) {

				/* Sanity check. */
				assert(w * h * componentSize * components == imageSize);

#if IMAGE_DEBUG
				dumpImage(infile, w, h, components, componentSize, options.luminance, srcImg);
#endif

				if (h > 1 && options.lower_left_maps_to_s0t0)
					yflip(srcImg, imageSize, w, h, components*componentSize);

				infiles[i].size = imageSize;
				infiles[i].data = srcImg;

				if (i == 0) {
					if (componentSize == 1) {
						tinfo.glType = GL_UNSIGNED_BYTE;
						tinfo.glTypeSize = 1;
					} else {
						tinfo.glType = GL_UNSIGNED_SHORT;
						tinfo.glTypeSize = 2;
					}
					switch (components) {
					  case 1:
						if (options.luminance) {
							tinfo.glFormat = tinfo.glBaseInternalFormat = GL_LUMINANCE;
							if (options.sized)
								tinfo.glInternalFormat = componentSize == 1 ? GL_LUMINANCE8 : GL_LUMINANCE16;
							else
								tinfo.glInternalFormat = GL_LUMINANCE;
						} else if (options.alpha) {
							tinfo.glFormat = tinfo.glBaseInternalFormat = GL_ALPHA;
							if (options.sized)
								tinfo.glInternalFormat = componentSize == 1 ? GL_ALPHA8 : GL_ALPHA16;
							else
								tinfo.glInternalFormat = GL_ALPHA;
						} else {
							tinfo.glFormat = tinfo.glBaseInternalFormat = GL_RED;
							if (options.sized)
								tinfo.glInternalFormat = componentSize == 1 ? GL_R8 : GL_R16;
							else
								tinfo.glInternalFormat = GL_RED;
						}
						break;

					  case 2:
						if (options.luminance) {
							tinfo.glFormat = tinfo.glBaseInternalFormat = GL_LUMINANCE_ALPHA;
							if (options.sized)
								tinfo.glInternalFormat = componentSize == 1 ? GL_LUMINANCE8_ALPHA8 : GL_LUMINANCE16_ALPHA16;
							else
								tinfo.glInternalFormat = GL_LUMINANCE_ALPHA;
						} else {
							tinfo.glFormat = tinfo.glBaseInternalFormat = GL_RG;
							if (options.sized)
								tinfo.glInternalFormat = componentSize == 1 ? GL_RG8 : GL_RG16;
							else
								tinfo.glInternalFormat = GL_RG;
						}
						break;

					  case 3:
						tinfo.glFormat = tinfo.glBaseInternalFormat = GL_RGB;
						if (options.sized)
							tinfo.glInternalFormat = componentSize == 1 ? GL_RGB8 : GL_RGB16;
						else
							tinfo.glInternalFormat = GL_RGB;
						break;

					  case 4:
						tinfo.glFormat = tinfo.glBaseInternalFormat = GL_RGBA;
						if (options.sized)
							tinfo.glInternalFormat = componentSize == 1 ? GL_RGBA8 : GL_RGBA16;
						else
							tinfo.glInternalFormat = GL_RGBA;
						break;
						break;

					  default:
					    /* If we get here there's a bug in readPAM */
					    assert(0);
					}
					tinfo.pixelWidth = levelWidth = w;
					tinfo.pixelHeight = levelHeight = h;
					tinfo.pixelDepth = 0;
					if (h == 1 && kvData != NULL) {
						/* 1D. Don't need orientation metadata */
						delete(kvData);
						kvData = NULL;
						kvDataLen = 0;
					}
					face = tinfo.numberOfFaces;
					if (options.automipmap)
						tinfo.numberOfMipmapLevels = 0;
					else if (options.mipmap) {
						// Calculate number of miplevels
						GLuint max_dim = w > h ? w : h;
						GLint levels = log2(max_dim) + 1;
						// Check we have enough.
						if (levels * face > options.numInputFiles) {
							fprintf(stderr, "%s: not enough input files for %d mipmap levels and faces\n",
								    options.appName, levels);
							exitCode = 1;
							goto cleanup2;
						}
						tinfo.numberOfMipmapLevels = levels;
					} else
						tinfo.numberOfMipmapLevels = 1;
				} else {
					if (options.mipmap) {
						if (face == 0) {
							levelWidth >>= 1;
							levelHeight >>= 1;
							if (w != levelWidth || h != levelHeight) {
								fprintf(stderr, "%s: \"%s\" has incorrect width or height for current mipmap level\n",
									    options.appName, infile);
								exitCode = 1;
								goto cleanup2;
							}
							face = options.cubemap ? 6 : 1;
						}
					}
				}
				face--;
				if (options.cubemap && w != h && w != levelWidth) {
						fprintf(stderr, "%s: \"%s,\" intended for a cubemap face, is not square or has incorrect\n"
							            "size for current mipmap level\n",
							    options.appName, infile);
						exitCode = 1;
						goto cleanup2;
				}
			} else {
Ejemplo n.º 24
0
int
main(int argc, const char* argv[])
{
   PNGlobalState::initGlobalState();

   if (processCommandLine(argc, argv) == false) {
      cout << "PicaNew v" << sg_pProgramVersion << '\n'
           << " Based on Pica by Joel Franklin which was\n"
           << " Based on DynaColor by Rhett Anderson\n"
           << " Glorious Thanks and Praise to the PNG and ZLib Folks...\n"
           << " @ Dynamix 1998, Original author Dave Moore\n\n";
      usage();
      return EXIT_FAILURE;
   }

   PNGlobalState* pGlobalState = PNGlobalState::getGlobalState();

   PNOptions  instOptions;           // Options for this run
   PNFileList procFileList;          // List of files to process

   if (instOptions.attachResponseFile(pGlobalState->getResponseFileName()) == false) {
      cerr << "Unable to open response file: "
           << pGlobalState->getResponseFileName() << '\n'
           << " - ABORTING - \n";
      return EXIT_FAILURE;
   }

   if (instOptions.validateOptions() == false) {
      cerr << "Invalid options detected, exiting...\n\n";
      exit(1);
   }

   instOptions.processResponseFile(procFileList);

   // Whether we are choosing colors or rendering, we need the unquantized images,
   //  so load them into memory...
   //
   PNUQImageFactory& rUQFactory = PNUQImageFactory::getInstance();
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      PNFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pUQImage  == NULL, "Huh?");
      AssertFatal(rFileEntry.pFileName != NULL, "Huh?");

      rFileEntry.pUQImage = rUQFactory.createUQImage(rFileEntry.pFileName);

      if (rFileEntry.pUQImage == NULL) {
         cerr << "main(): Unable to load file: " << rFileEntry.pFileName << '\n';
         exit(1);
      }
   }

   // We will need an authoritative final palette either way as well...
   //
   GFXPalette* pAuthPalette = new GFXPalette;
   memset(pAuthPalette->palette[0].color, 0, sizeof(PALETTEENTRY) * 256);
   if (instOptions.hasBasePalette() == true) {
      const char* pPaletteName = instOptions.getBasePalName();
      AssertFatal(pPaletteName != NULL, "No base palette name?  Here?");

      if (strstr(pPaletteName, ".tap") == NULL &&
          strstr(pPaletteName, ".TAP") == NULL) {
         Bool palLoadSuccess = pAuthPalette->read(pPaletteName);
         if (palLoadSuccess == false) {
            cerr << "Unable to load base palette: " << pPaletteName << ". Exiting...\n";
            exit(1);
         }
      } else {
         FILE *fp;
         if((fp = fopen(pPaletteName, "rb")) == NULL) {
             cerr << "ERROR - Cannot read Palette from : " << pPaletteName << "\n";
             exit(0);
         }

         for (int i = 0; i < 256; i++) {
            int red, green, blue, alpha;
            fscanf(fp, "%d %d %d %d", &red,
                                      &green,
                                      &blue,
                                      &alpha);
            pAuthPalette->palette[0].color[i].peRed   = UInt8(red);
            pAuthPalette->palette[0].color[i].peGreen = UInt8(green);
            pAuthPalette->palette[0].color[i].peBlue  = UInt8(blue);
            pAuthPalette->palette[0].color[i].peFlags = UInt8(alpha);
         }
         fclose(fp);
      }
   }
   // Always, always, always, the first color must be all 0
   //
   memset(&(pAuthPalette->palette[0].color[0]), 0, sizeof(PALETTEENTRY));


   // If we are choosing colors, set up the popularity table, and go to it...
   //
   if (instOptions.areChoosingColors() == true && procFileList.getNumFiles() != 0) {
      PNPopularityTable popularityTable(instOptions);

      // Files must register their colors with the popularity table..
      //
      PseudoTrace& tracer = PseudoTrace::getTracerObject();
      tracer.pushVerbosityLevel(1);
      tracer << "Scanning:  ";
      
      for (int i = 0; i < procFileList.getNumFiles(); i++) {
         PNFileEntry& rFileEntry = procFileList.getFile(i);
         AssertFatal(rFileEntry.pUQImage != NULL, "Huh?");

         rFileEntry.pUQImage->registerColors(popularityTable,
                                             rFileEntry.fileWeight);
         tracer << '.';
         tracer.flush();
      }
      tracer << " done\n";
      tracer.popVerbosityLevel();

      // Set up any fixed colors that may be required...
      //
      popularityTable.prepFixedColors(instOptions, pAuthPalette);

      // And quantize away!
      //
      popularityTable.quantizeColors(instOptions, pAuthPalette);
   }

   // If we are rendering the bitmaps, set up a color matching ditherer, and
   //  render away!
   //
   if (instOptions.areRenderingBitmaps() == true && procFileList.getNumFiles() != 0) {
      PNQuantizedRenderer pnRenderer(instOptions, pAuthPalette);

      PseudoTrace& tracer = PseudoTrace::getTracerObject();
      tracer.pushVerbosityLevel(1);
      tracer << "Rendering: ";
      
      for (int i = 0; i < procFileList.getNumFiles(); i++) {
         PNFileEntry& rFileEntry = procFileList.getFile(i);
         AssertFatal(rFileEntry.pUQImage != NULL, "Huh?");

         pnRenderer.renderUQImage(rFileEntry.pUQImage);

         if (instOptions.getExtrudingMipLevels() == false)
            tracer << '.';
         else
            tracer << '*';
         tracer.flush();
      }
      tracer << " done\n";
      tracer.popVerbosityLevel();

      // Store off the computed weights into the Palette...
      //
      const UInt32* pChosenFreqs = pnRenderer.getChosenFreqs();
      if (pAuthPalette->hasQuantizationInfo() == false)
         pAuthPalette->initQuantizationInfo();

      for (int i = 0; i < 256; i++)
         pAuthPalette->m_pColorWeights[i] += float(pChosenFreqs[i]);

      UInt32 renderStart, renderEnd;
      instOptions.getRenderRange(renderStart, renderEnd);
      pAuthPalette->m_usedRangeStart = renderStart;
      pAuthPalette->m_usedRangeEnd   = renderEnd;
   }

   // Write out the palette, and we're finished!
   //
   if (instOptions.getStripQuantizationInfo() == true)
      pAuthPalette->stripQuantizationInfo();

   if (instOptions.areChoosingColors() == true) {
      // First copy in the unique paletteKey, which we stuff into index 0
      //
      pAuthPalette->palette[0].paletteIndex = instOptions.getPaletteKey();

      // Now, technically, we're lying a bit about which type of palette this is,
      //  but the mpMerger tool will fix this up for us...
      //
      if (instOptions.getColorSpace() == PNOptions::ColorSpaceAlpha) {
         pAuthPalette->palette[0].paletteType = GFXPalette::AlphaQuantPaletteType;
      } else if (instOptions.getColorSpace() == PNOptions::ColorSpaceAdditive) {
         pAuthPalette->palette[0].paletteType = GFXPalette::AdditiveQuantPaletteType;
      } else if (instOptions.getColorSpace() == PNOptions::ColorSpaceSubtractive) {
         pAuthPalette->palette[0].paletteType = GFXPalette::SubtractiveQuantPaletteType;
      } else {
         pAuthPalette->palette[0].paletteType = GFXPalette::ColorQuantPaletteType;
      }

      if (instOptions.isStandAlonePalette() == true) {
         pAuthPalette->palette[0].paletteType = GFXPalette::NoRemapPaletteType;
      }

      for (int i = 1; i < 256; i++) {
         PALETTEENTRY& rPEntry = pAuthPalette->palette[0].color[i];
         if (rPEntry.peRed   == 0 &&
             rPEntry.peGreen == 0 &&
             rPEntry.peBlue  == 0)
            rPEntry.peBlue = 1;
      }

      // Write out our auth palette to the specified output name...
      //
      const char* pPaletteName = instOptions.getOutputPalName();
      pAuthPalette->write(pPaletteName);
   } else if (instOptions.areRenderingBitmaps() == true) {
      // Just write the palette back out to the base palette...
      //
      AssertFatal(instOptions.hasBasePalette() == true,
                  "If we aren't choosing colors, we must have a base palette...");
      pAuthPalette->write(instOptions.getBasePalName());
   } else {
      // Write out our auth palette to the specified output name...
      //
      pAuthPalette->palette[0].paletteIndex = instOptions.getPaletteKey();
      const char* pPaletteName = instOptions.getOutputPalName();
      if (pPaletteName != NULL)
         pAuthPalette->write(pPaletteName);
   }

   // Cleanup
   delete pAuthPalette;
   instOptions.unattachResponseFile();
   PNGlobalState::shutdownGlobalState();
   return EXIT_SUCCESS;
}
Ejemplo n.º 25
0
/**
 * XdmfExodusConverter is a command line utility for converting
 * between Xdmf and Exodus files. If given an Xdmf file, the tool
 * converts the file to Exodus and if given a path to an Exodus file,
 * the tool converts the file to Xdmf.
 *
 * Usage:
 *     XdmfExodusConverter <path-of-file-to-convert> 
 *                         (Optional: <path-to-output-file>)
 *
 */
int main(int argc, char* argv[])
{

  std::string inputFileName = "";
  std::string outputFileName = "";

  processCommandLine(inputFileName,
                     outputFileName,
                     argc,
                     argv);

  FILE * refFile = fopen(inputFileName.c_str(), "r");
  if (refFile) {
    // Success
    fclose(refFile);
  }
  else {
    std::cout << "Cannot open file: " << argv[1] << std::endl;
    return 1;
  }

  std::string meshName;
  if(outputFileName.compare("") == 0) {
    meshName = inputFileName;
  }
  else {
    meshName = outputFileName;
  }

  if(meshName.find_last_of("/\\") != std::string::npos) {
    meshName = meshName.substr(meshName.find_last_of("/\\") + 1,
                               meshName.length());
  }

  if (meshName.rfind(".") != std::string::npos) {
    meshName = meshName.substr(0, meshName.rfind("."));
  }

  int CPU_word_size = sizeof(double);
  int IO_word_size = 0; // Get from file
  float version;
  const int exodusHandle = 
    ex_open(argv[1], EX_READ, &CPU_word_size, &IO_word_size, &version);
  if(exodusHandle < 0) {
    // Xdmf to Exodus
    shared_ptr<XdmfReader> reader = XdmfReader::New();
    shared_ptr<XdmfDomain> domain = 
      shared_dynamic_cast<XdmfDomain>(reader->read(inputFileName));
    std::stringstream exodusFileName;
    exodusFileName << meshName << ".exo";
    shared_ptr<XdmfExodusWriter> writer = XdmfExodusWriter::New();
    if(domain->getNumberUnstructuredGrids() == 1) {
      const shared_ptr<XdmfUnstructuredGrid> grid = 
        domain->getUnstructuredGrid(0);
      writer->write(exodusFileName.str(),
                    grid);
      std::cout << "Wrote: " << exodusFileName.str() << std::endl;
    }
    else if(domain->getNumberGridCollections() == 1) {
      const shared_ptr<XdmfGridCollection> grid = 
        domain->getGridCollection(0);
      writer->write(exodusFileName.str(),
                    grid);
      std::cout << "Wrote: " << exodusFileName.str() << std::endl;
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Cannot find grid in Xdmf file to convert to "
                         "exodus.");
    }
  }
  else {
    // Exodus to Xdmf
    std::stringstream heavyFileName;
    heavyFileName << meshName << ".h5";
    shared_ptr<XdmfHDF5Writer> heavyDataWriter =
      XdmfHDF5Writer::New(heavyFileName.str());
    heavyDataWriter->setReleaseData(true);
    shared_ptr<XdmfExodusReader> exodusReader = XdmfExodusReader::New();
    shared_ptr<XdmfUnstructuredGrid> readGrid = 
      exodusReader->read(inputFileName,
                         heavyDataWriter);
    shared_ptr<XdmfDomain> newDomain = XdmfDomain::New();
    newDomain->insert(readGrid);
    std::stringstream xmlFileName;
    xmlFileName << meshName << ".xmf";
    shared_ptr<XdmfWriter> writer = XdmfWriter::New(xmlFileName.str(),
                                                    heavyDataWriter);
    newDomain->accept(writer);
    std::cout << "Wrote: " << xmlFileName.str() << std::endl;
  }

}
Ejemplo n.º 26
0
int main(int argc, char* argv[])
{
   //testCipher();
   CommandLineArguments args{false, false, false, "", "", "", ""};
   int retCode = processCommandLine(argc, argv, args);
   
   if(retCode != 0)
   {
	   return retCode;
   }
   
   // Use standard input by default
   std::ifstream inputStream{};
   if(!args.inputFilename.empty())
   {  // Try to use the input file
      inputStream.open(args.inputFilename);
      if(!inputStream.good())
      {
         std::cout << "Error: Could not open " << args.inputFilename << std::endl;
         return 1;
      }
   }

   std::ofstream outputStream{};
   if(!args.outputFilename.empty())
   {  // Try to use the output file
      outputStream.open(args.outputFilename);
      if(!outputStream.good())
      {
         std::cout << "Error: Could not open " << args.outputFilename << std::endl;
         return 1;
      }
   }
     
   std::string text = processInput(
      args.inputFilename.empty() ? std::cin : inputStream);

   std::string input{};
   for(char c : text)
   {
	   input.append(transformChar(c));
   }

   std::unique_ptr<Cipher> cipher;
   if(args.cipher == "caesar")
   {
      cipher = cipherFactory(CipherTypes::CAESAR);
   }
   else if(args.cipher == "playfair")
   {
      cipher = cipherFactory(CipherTypes::PLAYFAIR);
   }
   else if(args.cipher == "vigenere")
   {
      cipher = cipherFactory(CipherTypes::VIGENERE);
   }
   
   (*cipher).setKey(args.key);
   if(args.encrypt)
   {
      std::string ciphertext = (*cipher).encode(input);
      processOutput(
         args.outputFilename.empty() ? std::cout : outputStream,
         ciphertext);
   }
   else
   {
      std::string plaintext = (*cipher).decode(input);
      processOutput(
         args.outputFilename.empty() ? std::cout : outputStream,
         plaintext);      
   }
  
   return 0;
}
Ejemplo n.º 27
0
Archivo: main.cpp Proyecto: KDE/zanshin
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    App::initializeDependencies();

    auto aboutData = App::getAboutData();
    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);

    KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("zanshin-migratorrc"));
    KConfigGroup group = config->group("Migrations");
    if (!group.readEntry("Migrated021Projects", false)) {
        std::cerr << "Migrating data from zanshin 0.2, please wait..." << std::endl;
        QProcess proc;
        proc.start(QStringLiteral("zanshin-migrator"));
        proc.waitForFinished(-1);
        if (proc.exitStatus() == QProcess::CrashExit) {
            std::cerr << "Migrator crashed!" << std::endl;
        } else if (proc.exitCode() == 0) {
            std::cerr << "Migration done" << std::endl;
        } else {
            std::cerr << "Migration error, code" << proc.exitCode() << std::endl;
        }
    }

    auto widget = new QWidget;
    auto components = new Widgets::ApplicationComponents(widget);
    components->setModel(Presentation::ApplicationModel::Ptr::create());

    auto layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(components->pageView());
    widget->setLayout(layout);

    auto sourcesDock = new QDockWidget(QObject::tr("Sources"));
    sourcesDock->setObjectName(QStringLiteral("sourcesDock"));
    sourcesDock->setWidget(components->availableSourcesView());

    auto pagesDock = new QDockWidget(QObject::tr("Pages"));
    pagesDock->setObjectName(QStringLiteral("pagesDock"));
    pagesDock->setWidget(components->availablePagesView());

    auto editorDock = new QDockWidget(QObject::tr("Editor"));
    editorDock->setObjectName(QStringLiteral("editorDock"));
    editorDock->setWidget(components->editorView());

    auto window = new KXmlGuiWindow;
    window->setCentralWidget(widget);

    window->addDockWidget(Qt::RightDockWidgetArea, editorDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, pagesDock);
    window->addDockWidget(Qt::LeftDockWidgetArea, sourcesDock);

    auto actions = components->globalActions();
    actions.insert(QStringLiteral("dock_sources"), sourcesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_pages"), pagesDock->toggleViewAction());
    actions.insert(QStringLiteral("dock_editor"), editorDock->toggleViewAction());

    auto ac = window->actionCollection();
    ac->addAction(KStandardAction::Quit, window, SLOT(close()));
    for (auto it = actions.constBegin(); it != actions.constEnd(); ++it) {
        auto shortcut = it.value()->shortcut();
        if (!shortcut.isEmpty()) {
            ac->setDefaultShortcut(it.value(), shortcut);
        }
        ac->addAction(it.key(), it.value());
    }

    window->setupGUI(QSize(1024, 600),
                     KXmlGuiWindow::ToolBar
                   | KXmlGuiWindow::Keys
                   | KXmlGuiWindow::Save
                   | KXmlGuiWindow::Create);
    window->show();

    return app.exec();
}