Exemple #1
0
void handle_base_flags(int flag_char, /* IN */
                       const char *flag_arg, /* IN */
                       print_usage_f *print_usage, /* IN */
                       const char *appl, /* IN */
                       const char **default_outfilep) /* IN */
{
    switch(flag_char)
    {
    case 'o':
        *default_outfilep = flag_arg;
        break;
    case 'q':
        LOG_SET_LEVEL(LOG_BRIEF);
        break;
    case 'v':
        print_license();
        exit(0);
    default:
        if (flagflag != '?')
        {
            LOG(LOG_ERROR,
                ("error, invalid option \"-%c\"", flagflag));
            if (flagarg != NULL)
            {
                LOG(LOG_ERROR, (" with argument \"%s\"", flagarg));
            }
            LOG(LOG_ERROR, ("\n"));
        }
        print_usage(appl, LOG_BRIEF, *default_outfilep);
        exit(0);
    }
}
Exemple #2
0
void surfit_init_variables(Tcl_Interp * iinterp) {

	// 2d
	init_interp(iinterp);
	print_license();
	log_open();

	//init_all();
};
Exemple #3
0
int main(int argc, char *argv[])
{
	int retval;
	struct uuid_result result;
	struct Options opt;

	progname = argv[0];

	retval = parse_options(&opt, argc, argv);
	if (retval != EXIT_SUCCESS) {
		fprintf(stderr, "%s: Option error\n", progname);
		return EXIT_FAILURE;
	}

	msg(3, "Using verbose level %d", verbose_level(0));

	if (opt.help)
		return usage(EXIT_SUCCESS);
	if (opt.self_test)
		return run_self_tests();
	if (opt.version)
		return print_version();
	if (opt.license)
		return print_license();

#ifdef TEST_FUNC
	/*
	 * Send non-option command line arguments to various functions for 
	 * testing. This doesn't break anything, as the program only checks for 
	 * options. Non-option arguments are ignored.
	 */
	if (optind < argc) {
		int i;

		for (i = optind; i < argc; i++) {
			char *a = argv[i];
			char buf[1000];

			msg(3, "Checking arg %d \"%s\"", i, a);
			memset(buf, 0, 1000);
			strncpy(buf, a, 999);
			printf("squeeze_chars(\"%s\", \",\") = \"%s\"\n",
			       a, squeeze_chars(buf, "e"));
		}
		return EXIT_SUCCESS;
	}
#endif

	result = create_and_log_uuids(&opt);
	if (!result.success)
		retval = EXIT_FAILURE;

	msg(3, "Returning from main() with value %d", retval);
	return retval;
}
Exemple #4
0
int main(int argc, char **argv) {
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=5) {
    printf("Usage: %s zeta l Nf method\n",argv[0]);
    printf("zeta is the STO exponent to fit\n");
    printf("l is angular momentum to use\n");
    printf("Nf is number of exponents to use\n");
    printf("method is 0 for even-tempered, 1 for well-tempered and 2 for full optimization, or 3 for midpoint quadrature.\n");
    return 1;
  }

  // Read parameteres
  double zeta=atof(argv[1]);
  double am=atoi(argv[2]);
  int Nf=atoi(argv[3]);
  int method=atoi(argv[4]);

  // Do the optimization
  std::vector<contr_t> contr;

  if(method>=0 && method<=2)
    contr=slater_fit(zeta,am,Nf,true,method);
  else if(method==3)
    contr=slater_fit_midpoint(zeta,am,Nf);
  else throw std::runtime_error("Unknown method.\n");

  // Print them out
  printf("\nExponential contraction\nc_i\t\tz_i\t\tlg z_i\n");
  for(size_t i=0;i<contr.size();i++)
    printf("% e\t%e\t% e\n",contr[i].c,contr[i].z,log10(contr[i].z));

  // Form basis set
  ElementBasisSet elbas("El");
  FunctionShell sh(am,contr);
  elbas.add_function(sh);

  // Save the basis set
  BasisSetLibrary baslib;
  baslib.add_element(elbas);
  baslib.save_gaussian94("slater-contr.gbs");

  // also in decontracted form
  baslib.decontract();
  baslib.save_gaussian94("slater-uncontr.gbs");

  return 0;
}
int main(int argc, char* argv[])
{
  if (argc < 6)
  {
    print_usage(argv[0]);
    return -1;
  }

  std::ofstream out ("ServiceDescription.h", std::ofstream::binary);

  std::ifstream version(argv[1], std::ios_base::in);
  std::ifstream license(argv[2], std::ios_base::in);
  std::ifstream methods(argv[3], std::ios_base::in);
  std::ifstream types(argv[4], std::ios_base::in);
  std::ifstream notifications(argv[5], std::ios_base::in);

  if (!(version && license && methods && types && notifications))
  {
    std::cout << "Failed to find one or more of version.txt, license.txt, methods.json, types.json or notifications.json" << std::endl;
    return -1;
  }

  out << "#pragma once" << std::endl;

  print_license(license, out);

  out << std::endl;

  out << "namespace JSONRPC" << std::endl;
  out << "{" << std::endl;
  out << "  const char* const JSONRPC_SERVICE_ID          = \"http://xbmc.org/jsonrpc/ServiceDescription.json\";" << std::endl;
  out << "  const char* const JSONRPC_SERVICE_VERSION     = \""; print_version(version, out); out << "\";" << std::endl;
  out << "  const char* const JSONRPC_SERVICE_DESCRIPTION = \"JSON-RPC API of XBMC\";" << std::endl;
  out << std::endl;

  out << "  const char* const JSONRPC_SERVICE_TYPES[] = {";
  print_json(types, out);
  out << "  };" << std::endl;
  out << std::endl;

  out << "  const char* const JSONRPC_SERVICE_METHODS[] = {";
  print_json(methods, out);
  out << "  };" << std::endl;
  out << std::endl;

  out << "  const char* const JSONRPC_SERVICE_NOTIFICATIONS[] = {";
  print_json(notifications, out);
  out << "  };" << std::endl;

  out << "}" << std::endl;

  return 0;
}
Exemple #6
0
void handle_license_and_version_args(int argc, char *argv[],
                                     const char *program_name)
{
  if(_checkForOption("--license", argc, argv) ||
     _checkForOption("-l", argc, argv)        ||
     _checkForOption("-license", argc, argv))
  {
    print_license(ASF_BSD_ID);
  }
  if(_checkForOption("--version", argc, argv) ||
     _checkForOption("-v", argc, argv)        ||
     _checkForOption("-version", argc, argv))
  {
    print_version(program_name);
  }
}
Exemple #7
0
int main( int argc, char **argv )
{
	/** init
	*/
	int ret = 0;
	
	
	/** example
	*/
	print_license();
	printf( "\n\n" );
	
	printf( "Printing all thread ids...\n\n" );
	ret = traverse_threads( callback_print_thread_id, NULL, NULL, 0, 0, NULL );
	printf( "\ntraverse_threads() returned: %hs\n", traverse_threads_retcode_to_cstr( ret ) );
	
	return ( ( ret == TRAVERSE_SUCCESS ) ? 0 : 1 );
}
Exemple #8
0
void print_license_info()
{
    license_struct lstr;
    int license_valid;
    fputs("License information:\n", stderr);
    init_openssl();
    load_license(&lstr);
    print_license(&lstr);
    license_valid = verify_license(&lstr);
    free_license(&lstr);
    free_openssl();

    if (!license_valid) {
      exit(EXIT_FAILURE);
    }

    fputs("The license key is valid.\n", stderr);
}
int main( int argc, char **argv )
{
	int cmd = -1;
	HWND hwnd = NULL;
	
	
	print_license();
	printf( "\n" );
	
	if( argc < 2 )
		show_usage_and_exit();
	
	cmd = find_command( argv[ 1 ] );
	if( cmd == -1 )
		show_usage_and_exit();
	
	hwnd = FindWindowEx( NULL, NULL, "gdkWindowToplevel", "Workrave" );
	if( !hwnd )
	{
		printf( "Error: Workrave window not found!\n" );
		return 1;
	}
	
	printf( "Sending Workrave command %s...\n", command[ cmd ] );
	fflush( stdout );
	
	SetLastError( 0 );
	if( SendMessageTimeout( hwnd, WM_USER, cmd, 0, SMTO_BLOCK, 15000, NULL ) )
	{
		printf( "Command sent.\n" );
		return 0;
	}
	
	if( GetLastError() == ERROR_TIMEOUT )
		printf( "Error: SendMessageTimeout() timed out!\n" );
	else
		printf( "Error: SendMessageTimeout() failed!\n" );
	
	return 1;
}
int main(int argc, char *argv[])
{

	if (argc<2 || strlen(argv[1])!=1) {
		return print_usage();
	}

	switch (argv[1][0]) {
	case 'l':
		return print_license();
	case 'x':
		return extract_nb0_file(argc, argv);
	case 'c':
		return create_nb0_file(argc, argv);
	case 'w':
		return write_nb0_file(argc, argv);
	case 't':
		return test_nb0_file(argc, argv);
	default:
		return print_usage();

	}
}
Exemple #11
0
int Ganash::Application::on_command_line(const Glib::RefPtr<Gio::ApplicationCommandLine>&command_line)
{
  g_print("on_command_line\n");

  // @see example http://git.gnome.org/browse/glibmm/tree/examples/options/main.cc?h=glibmm-2-24
  // @see console|graphic http://stackoverflow.com/questions/13852421/gtkmm-3-parse-command-line-with-gtkapplication

  bool          entry_version = FALSE;
  bool          entry_license = FALSE;
  bool          entry_mode    = FALSE;


  Glib::OptionContext context("[FICHIER|URI...]");

  Glib::OptionEntry option_version;
  option_version.set_short_name('v');
  option_version.set_long_name("version");
  option_version.set_description("Affiche l'information de version et quitte");

  Glib::OptionEntry option_license;
  option_license.set_short_name('l');
  option_license.set_long_name("license");
  option_license.set_description("Affiche l'information de licence et quitte");

  Glib::OptionEntry option_mode;
  option_mode.set_short_name('c');
  option_mode.set_long_name("console");
  option_mode.set_description("Lance l'application en mode console interactif");

  Glib::OptionGroup group_application("options", "Options de l'application :", "Affiche les options de l'application");
  group_application.add_entry(option_version, entry_version);
  group_application.add_entry(option_license, entry_license);
  group_application.add_entry(option_mode,    entry_mode);
  context.add_group(group_application);

  int argc;
  char **argv = command_line->get_arguments(argc);
  loc_argc = argc;
  loc_argv = argv;

  try
  {
    context.parse(argc, argv);
    if(entry_version)
      {
        print_version();
        // Ganash::ApplicationCommand::print_version();
      }
    else if(entry_license)
      {
        print_license();
        // Ganash::ApplicationCommand::print_license();
      }
    if(entry_mode)
      {
        g_print("console activate\n");
      }
    else
      {
        activate();
      }
  }
  catch(const Glib::Error& ex)
  {
    g_print("%s\n", ex.what().c_str() );
  }


  return 0;
}
Exemple #12
0
int main(int argc, char **argv) {
#ifdef _OPENMP
  printf("ERKALE - Completeness optimization from Hel. OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - Completeness optimization from Hel. Serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=7 && argc!=8) {
    printf("Usage:   %s am n min max Nf/tol nfull (coulomb)\n",argv[0]);
    printf("am:      angular momentum of shell to optimize for.\n");
    printf("n:       moment to optimize for.\n");
    printf("         1 for maximal area, 2 for minimal rms deviation from unity.\n");
    printf("min:     profile lower limit, in log10.\n");
    printf("Nf:      amount of functions to place on shell.\n");
    printf("tol:     wanted tolerance.\n");
    printf("nfull:   number of outermost functions to fully optimize.\n");
    printf("coulomb: use Coulomb metric?\n");
    return 1;
  }

  // Get parameters
  int am=atoi(argv[1]);
  int n=atoi(argv[2]);
  double min=atof(argv[3]);
  int nf=atoi(argv[4]);
  double tol=atof(argv[5]);
  int nfull=atoi(argv[6]);

  bool coulomb=false;
  if(argc==8)
    coulomb=atoi(argv[7]);
  // The Coulomb metric is equivalent to the normal metric with am-1
  if(coulomb)
    am--;

  Timer t;

  // Form optimized set of primitives
  double w;
  arma::vec exps=move_exps(maxwidth_exps(am,tol,nf,w,n,nfull),min);

  // Return the original value if Coulomb metric was used
  if(coulomb)
    am++;

  // Create a basis set out of it. Print exponents in descending order
  ElementBasisSet el("El");
  for(size_t i=exps.size()-1;i<exps.size();i--) {
    // Create shell of functions
    FunctionShell tmp(am);
    tmp.add_exponent(1.0,exps[i]);
    // and add it to the basis set
    el.add_function(tmp);
  }

  BasisSetLibrary baslib;
  baslib.add_element(el);
  baslib.save_gaussian94("optimized.gbs");

  printf("Optimization performed in %s.\n",t.elapsed().c_str());
  printf("Completeness-optimized basis set saved to optimized.gbs.\n\n");

  printf("Width of profile is %.10e.\n",w);

  return 0;
}
Exemple #13
0
int main(int argc, char **argv) {

#ifdef _OPENMP
  printf("ERKALE - EMD from Hel, OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - EMD from Hel, serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=1 && argc!=2) {
    printf("Usage: $ %s (runfile)\n",argv[0]);
    return 0;
  }

  Timer t;

  // Parse settings
  Settings set;
  set.add_string("LoadChk","Checkpoint file to load density from","erkale.chk");
  set.add_bool("DoEMD", "Perform calculation of isotropic EMD (moments of EMD, Compton profile)", true);
  set.add_double("EMDTol", "Tolerance for the numerical integration of the radial EMD",1e-8);
  set.add_string("EMDlm", "Which projection of the radial EMD to compute","");
  set.add_bool("EMDAdapt", "Use adaptive grid to compute EMD?", true);
  set.add_string("EMDCube", "Calculate EMD on a cube? e.g. -10:.3:10 -5:.2:4 -2:.1:3", "");
  set.add_string("EMDOrbitals", "Compute EMD of given orbitals, e.g. 1,2,4:6","");
  set.add_string("Similarity", "Compute similarity measure to checkpoint","");
  set.add_string("SimilarityGrid", "Grid to use for computing similarity integrals","500 77");
  set.add_bool("SimilarityLM", "Seminumerical computation of similarity integrals?", false);
  set.add_int("SimilarityLmax", "Maximum angular momentum for seminumerical computation", 6);

  if(argc==2)
    set.parse(argv[1]);
  else
    printf("Using default settings.\n");
  set.print();

  // Get the tolerance
  double tol=set.get_double("EMDTol");

  // Load checkpoint
  Checkpoint chkpt(set.get_string("LoadChk"),false);

  // Load basis set
  BasisSet basis;
  chkpt.read(basis);

  // Load density matrix
  arma::cx_mat P;
  arma::mat Pr, Pi;
  chkpt.read("P",Pr);
  if(chkpt.exist("P_im")) {
    chkpt.read("P_im",Pi);
    P=Pr*COMPLEX1 + Pi*COMPLEXI;
  } else
    P=Pr*COMPLEX1;
  
  // The projection to calculate
  int l=0, m=0;
  std::string lmstr=set.get_string("EMDlm");
  if(lmstr.size()) {
    // Get l and m values
    std::vector<std::string> lmval=splitline(lmstr);
    if(lmval.size()!=2)
      throw std::runtime_error("Invalid specification of l and m values.\n");
    l=readint(lmval[0]);
    m=readint(lmval[1]);
  }
  bool adaptive=set.get_bool("EMDAdapt");

  // Compute orbital EMDs?
  if(set.get_string("EMDOrbitals")!="") {
    // Get orbitals
    std::vector<std::string> orbs=splitline(set.get_string("EMDOrbitals"));

    // Polarized calculation?
    bool restr;
    chkpt.read("Restricted",restr);
    if(restr!= (orbs.size()==1))
      throw std::runtime_error("Invalid occupancies for spin alpha and beta!\n");

    if(l!=0)
      printf("\nComputing the (%i %+i) projection of the orbital EMD.\n",l,m);

    for(size_t ispin=0;ispin<orbs.size();ispin++) {
      // Indices of orbitals to include.
      std::vector<size_t> idx=parse_range(orbs[ispin]);
      // Change into C++ indexing
      for(size_t i=0;i<idx.size();i++)
	idx[i]--;

      // Read orbitals
      arma::mat C;
      if(restr)
	chkpt.read("C",C);
      else {
	if(ispin==0)
	  chkpt.read("Ca",C);
	else
	  chkpt.read("Cb",C);
      }

      for(size_t i=0;i<idx.size();i++) {
	// Names of output files
	char emdname[80];
	char momname[80];
	char Jname[80];
	char Jintname[80];

	char suffix[80];
	if(l==0)
	  sprintf(suffix,".txt");
	else
	  sprintf(suffix,"_%i_%i.txt",l,m);

	if(restr) {
	  sprintf(emdname,"emd-%i%s",(int) idx[i]+1,suffix);
	  sprintf(momname,"moments-%i%s",(int) idx[i]+1,suffix);
	  sprintf(Jname,"compton-%i%s",(int) idx[i]+1,suffix);
	  sprintf(Jintname,"compton-interp-%i%s",(int) idx[i]+1,suffix);
	} else {
	  if(ispin==0) {
	    sprintf(emdname,"emd-a-%i%s",(int) idx[i]+1,suffix);
	    sprintf(momname,"moments-a-%i%s",(int) idx[i]+1,suffix);
	    sprintf(Jname,"compton-a-%i%s",(int) idx[i]+1,suffix);
	    sprintf(Jintname,"compton-interp-a-%i%s",(int) idx[i]+1,suffix);
	  } else {
	    sprintf(emdname,"emd-b-%i%s",(int) idx[i]+1,suffix);
	    sprintf(momname,"moments-b-%i%s",(int) idx[i]+1,suffix);
	    sprintf(Jname,"compton-b-%i%s",(int) idx[i]+1,suffix);
	    sprintf(Jintname,"compton-interp-b-%i%s",(int) idx[i]+1,suffix);
	  }
	}

	// Generate dummy density matrix
	arma::cx_mat Pdum=C.col(idx[i])*arma::trans(C.col(idx[i]))*COMPLEX1;

	Timer temd;

	GaussianEMDEvaluator *poseval=new GaussianEMDEvaluator(basis,Pdum,l,std::abs(m));
	GaussianEMDEvaluator *negeval;
	if(m!=0)
	  negeval=new GaussianEMDEvaluator(basis,Pdum,l,-std::abs(m));
	else
	  negeval=NULL;

	EMD emd(poseval, negeval, 1, l, m);
	if(adaptive) {
	  emd.initial_fill();
	  if(l==0 && m==0) emd.find_electrons();
	  emd.optimize_moments(true,tol);
	} else
	  emd.fixed_fill();

	emd.save(emdname);
	emd.moments(momname);
	if(l==0 && m==0) {
	  emd.compton_profile(Jname);
	  emd.compton_profile_interp(Jintname);
	}

	delete poseval;
	if(m!=0) delete negeval;
      }
    }
  }

  if(set.get_bool("DoEMD")) {
    t.print_time();

    printf("\nCalculating EMD properties.\n");
    printf("Please read and cite the reference:\n%s\n%s\n%s\n",	\
	   "J. Lehtola, M. Hakala, J. Vaara and K. Hämäläinen",		\
	   "Calculation of isotropic Compton profiles with Gaussian basis sets", \
	   "Phys. Chem. Chem. Phys. 13 (2011), pp. 5630 - 5641.");

    if(l!=0)
      printf("\nComputing the (%i %+i) projection of the EMD.\n",l,m);
    else
      printf("\nComputing the isotropic projection of the EMD.\n");

    // Amount of electrons is
    int Nel;
    chkpt.read("Nel",Nel);

    // Construct EMD evaluators
    Timer temd;
    GaussianEMDEvaluator *poseval=new GaussianEMDEvaluator(basis,P,l,std::abs(m));
    GaussianEMDEvaluator *negeval;
    if(m!=0)
      negeval=new GaussianEMDEvaluator(basis,P,l,-std::abs(m));
    else
      negeval=NULL;

    temd.set();
    EMD emd(poseval, negeval, Nel, l, m);
    if(adaptive) {
      emd.initial_fill();
      if(l==0 && m==0) emd.find_electrons();
      emd.optimize_moments(true,tol);
    } else
      emd.fixed_fill();

    if(l==0 && m==0) {
      emd.save("emd.txt");
      emd.moments("moments.txt");
      emd.compton_profile("compton.txt");
      emd.compton_profile_interp("compton-interp.txt");
    } else {
      char fname[80];
      sprintf(fname,"emd_%i_%i.txt",l,m);
      emd.save(fname);

      sprintf(fname,"moments_%i_%i.txt",l,m);
      emd.moments(fname);
    }

    if(l==0 && m==0)
      printf("Calculating isotropic EMD properties took %s.\n",temd.elapsed().c_str());
    else
      printf("Calculating projected EMD properties took %s.\n",temd.elapsed().c_str());

    delete poseval;
    if(m!=0) delete negeval;
  }

  // Do EMD on a cube?
  if(stricmp(set.get_string("EMDCube"),"")!=0) {
    t.print_time();
    Timer temd;

    // Form grid in p space.
    std::vector<double> px, py, pz;
    parse_cube(set.get_string("EMDCube"),px,py,pz);

    // Calculate EMD on cube
    emd_cube(basis,P,px,py,pz);

    printf("Calculating EMD on a cube took %s.\n",temd.elapsed().c_str());
  }

  // Compute similarity?
  if(stricmp(set.get_string("Similarity"),"")!=0) {

    // Load checkpoint
    Checkpoint simchk(set.get_string("Similarity"),false);

    // Get grid size
    std::vector<std::string> gridsize=splitline(set.get_string("SimilarityGrid"));
    if(gridsize.size()!=2) {
      throw std::runtime_error("Invalid grid size!\n");
    }
    int nrad=readint(gridsize[0]);
    int lmax=readint(gridsize[1]);
    int radlmax=set.get_int("SimilarityLmax");

    // Load basis set
    BasisSet simbas;
    simchk.read(simbas);

    // Load density matrix
    arma::mat simPr, simPi;
    arma::cx_mat simP;
    simchk.read("P",simPr);
    if(simchk.exist("P_im")) {
      simchk.read("P_im",simPi);
      simP=simPr*COMPLEX1 + simPi*COMPLEXI;
    } else
      simP=simPr*COMPLEX1;
    
    // Compute momentum density overlap
    arma::cube ovl;
    if(set.get_bool("SimilarityLM"))
      ovl=emd_overlap_semi(basis,P,simbas,simP,nrad,radlmax);
    else
      ovl=emd_overlap(basis,P,simbas,simP,nrad,lmax);

    // Amount of electrons
    int Nela, Nelb;
    chkpt.read("Nel", Nela);
    simchk.read("Nel", Nelb);

    // Shape function overlap
    arma::cube sh=emd_similarity(ovl,Nela,Nelb);
    sh.slice(0).save("similarity.dat",arma::raw_ascii);
    sh.slice(1).save("similarity_avg.dat",arma::raw_ascii);

    for(int s=0;s<2;s++) {
      if(s) {
	printf("%2s\t%9s\t%9s\t%9s\t%9s\t%9s\t%9s\t%9s\n","k","S0(AA)","S0(BB)","S0(AB)","I0(AA)","I0(BB)","I0(AB)","D0(AB)");
	for(int k=-1;k<3;k++)
	  // Vandenbussche don't include p^2 in the spherical average
	  printf("%2i\t%e\t%e\t%e\t%e\t%e\t%e\t%e\n", k+1, sh(k+1,0,s), sh(k+1,1,s), sh(k+1,2,s), sh(k+1,3,s), sh(k+1,4,s), sh(k+1,5,s), sh(k+1,6,s));
      } else {
	printf("%2s\t%9s\t%9s\t%9s\t%9s\t%9s\t%9s\t%9s\n","k","S(AA)","S(BB)","S(AB)","I(AA)","I(BB)","I(AB)","D(AB)");
	for(int k=-1;k<3;k++)
	  printf("%2i\t%e\t%e\t%e\t%e\t%e\t%e\t%e\n", k, sh(k+1,0,s), sh(k+1,1,s), sh(k+1,2,s), sh(k+1,3,s), sh(k+1,4,s), sh(k+1,5,s), sh(k+1,6,s));
      }
      printf("\n");
    }
  }

  return 0;
}
Exemple #14
0
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
    init_log();
    
    try {
        fnd::vector<fnd::const_cstring> opt_paths;
        unsigned opt_type_mask = regular_f;
        size_t opt_max_depth = math::maximum<size_t>();
        bool opt_canonical = false;
        bool opt_newline = false;
        fnd::const_cstring opt_interpolate;
        fnd::const_cstring opt_rx;
        regex::regex_option_type opt_rx_type = regex::ecma;
        bool opt_rx_search = true;
        int quit = -1;
        
        auto opts_ctx = fnd::opts::context(
            [&] (fnd::const_cstring id, fnd::const_cstring val,
                const size_t i)
            {
                gl->error("Unknown parameter: '-", id, "'.");
                quit = EXIT_FAILURE;
            },
            [&] (fnd::const_cstring val, const size_t i) {
                if(i > 0)
                    opt_paths.push_back(val);
                return true;
            },
            
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    print_help(argv[0]);
                    quit = EXIT_SUCCESS;
                    return false;
                },
                "help", "h"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    print_license();
                    quit = EXIT_SUCCESS;
                    return false;
                },
                "license"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    print_version();
                    quit = EXIT_SUCCESS;
                    return false;
                },
                "version"),
                
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    if(1 != i)
                        gl->warning("'-", id,
                            "' should be the first argument!");
                    gl->threshold(fnd::qlog::level::debug);
                    return true;
                },
                "verbose", "v"),
            
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(val.empty())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Missing value. '-", id, "=?'.");
                        return false;
                    }
                    
                    unsigned mask = 0;
                    for(const char c : val)
                    {
                        switch(c)
                        {
                        case 'f':
                            mask |= regular_f;
                            break;
                        case 's':
                            mask |= symlink_f;
                            break;
                        case 'd':
                            mask |= directory_f;
                            break;
                        case 'b':
                            mask |= block_f;
                            break;
                        case 'i':
                            mask |= fifo_f;
                            break;
                        case 'k':
                            mask |= socket_f;
                            break;
                        case 'c':
                            mask |= character_device_f;
                            break;
                        case 'a':
                            mask = all_f;
                        default:
                            quit = EXIT_FAILURE;
                            gl->error("Invalid value. '-", id, "=#ERROR'");
                            return false;
                        }
                    }
                    
                    opt_type_mask = mask;
                    
                    return true;
                },
                "type", "t"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(val.empty())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Missing value. '-", id, "=?'.");
                        return false;
                    }
                    auto r = fmt::to_integer<size_t>(
                        val, 10, fnd::nothrow_tag());
                    if(!r.valid())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Expected a positive number. ",
                            "--", id, "=#ERROR");
                        return false;
                    }
                    opt_max_depth = r.get();
                    return true;
                },
                "depth", "d"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    opt_canonical = true;
                    return true;
                },
                "canonical", "c"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    opt_newline = true;
                    return true;
                },
                "newline", "n"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(val.empty())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Missing value. '-", id, "=?'.");
                        return false;
                    }
                    opt_interpolate = val;
                    return true;
                },
                "interpolate", "i"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(val.empty())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Missing value. '-", id, "=?'.");
                        return false;
                    }
                    opt_rx = val;
                    return true;
                },
                "regex", "r"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(val.empty())
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Missing value. '-", id, "=?'.");
                        return false;
                    }
                    
                    if(val == "grep")
                        opt_rx_type = regex::grep;
                    else if(val == "egrep")
                        opt_rx_type = regex::egrep;
                    else if(val == "ecma")
                        opt_rx_type = regex::ecma;
                    else if(val == "posix")
                        opt_rx_type = regex::basic_posix;
                    else if(val == "eposix")
                        opt_rx_type = regex::extended_posix;
                    else
                    {
                        quit = EXIT_FAILURE;
                        gl->error("Invalid value. '-", id, "=#ERROR'");
                        return false;
                    }
                    
                    return true;
                },
                "regex-type", "rt"),
            fnd::opts::argument(
                [&] (fnd::const_cstring id, fnd::const_cstring val, size_t i) {
                    if(!val.empty())
                        gl->warning("Value ignored. '-", id, "' is a flag.");
                    opt_rx_search = false;
                    return true;
                },
                "regex-match", "rm"));
        
        fnd::opts::parse_command_line(opts_ctx, argc, argv);
        
        if(quit != -1)
            return quit;
        
        regex::default_regex *rx = nullptr;
        n_scope_exit(&) {
            if(rx)
                delete rx;
        };
        if(!opt_rx.empty() && opt_rx != ".*")
        {
            try {
                rx = new regex::default_regex(
                    opt_rx, regex::optimize | opt_rx_type);
            } catch(const regex::regex_error &e) {
                gl->error("Compiling a regular expression failed.");
                gl->debug(fnd::diagnostic_information(e));
                return EXIT_FAILURE;
            }
        }
        
        auto f = [&](fs::path p, size_t level) -> bool
        {   
            const fs::file_status stat = fs::status(p);
 
            switch(fs::type(stat))
            {
            case fs::file_type::regular:
                if((opt_type_mask & regular_f) == 0u)
                    return true;
                break;
            case fs::file_type::symlink:
                if((opt_type_mask & symlink_f) == 0u)
                    return true;
                break;
            case fs::file_type::directory:
                if((opt_type_mask & directory_f) == 0u)
                    return true;
                break;
            case fs::file_type::block:
                if((opt_type_mask & block_f) == 0u)
                    return true;
                break;
            case fs::file_type::fifo:
                if((opt_type_mask & fifo_f) == 0u)
                    return true;
                break;
            case fs::file_type::socket:
                if((opt_type_mask & socket_f) == 0u)
                    return true;
                break;
            case fs::file_type::character_device:
                if((opt_type_mask & character_device_f) == 0u)
                    return true;
                break;
            default:
                n_throw(logic_error);
            }
            
            if(rx)
            {
                if(opt_rx_search) {
                    if(!regex::search(p.str(), *rx))
                        return true;
                } else {
                    if(!regex::match(p.str(), *rx))
                        return true;
                }
            }
            
            if(opt_interpolate.empty())
            {
                fmt::fwrite(io::cout, p);
            }
            else
            {
                try {
                    fmt::interp(
                        io::cout,
                        opt_interpolate,
                        p,
                        fs::to_cstr(fs::type(stat)),
                        fs::size(stat),
                        fs::last_access(stat),
                        fs::last_modification(stat),
                        fs::last_status_change(stat),
                        fs::pretty_permissions(stat),
                        level);
                } catch(...) {
                    n_throw(runtime_error)
                    << fnd::ei_msg_c("String interpolation failed.")
                    << fnd::ei_exc(fnd::current_exception())
                    << fs::ei_path(p);
                }
            }
            
            if(opt_newline)
                io::put(io::cout, '\n');
            else
                io::put(io::cout, ' ');
            
            return true;
        };
        
        if(opt_paths.empty())
            opt_paths.emplace_back(".");
        
        for(fnd::const_cstring x : opt_paths)
        {
            const fs::path path = opt_canonical
                ? fs::canonical(x)
                : x;
            fs::recursive_scan(path, opt_max_depth, f);
        }
    }
    catch(const fnd::exception &e)
    {
        const fs::ei_path *p = fnd::get_error_info<fs::ei_path>(e);
        
        gl->fatal("Internal Error");
        
        if(p)
            gl->fatal("Path: ", p->value());
        
        gl->debug(fnd::diagnostic_information(e));
        
        return EXIT_FAILURE;
    }
    catch(...)
    {
        gl->fatal("Internal Error");
        gl->debug(fnd::diagnostic_information(fnd::current_exception()));
        
        return EXIT_FAILURE;
    }
    
    return EXIT_SUCCESS;
}
Exemple #15
0
int main(int argc, char* argv[]) {
	string homedir;
	for (int i = 1; i < argc; i++) {
		if (cmdcmp(argv[i], "-h") == 0) {
			print_usage();
			exit(EXIT_SUCCESS);
		} else if (cmdcmp(argv[i], "-i") == 0) {
			print_license();
			exit(EXIT_SUCCESS);
		} else if (cmdcmp(argv[i], "-homedir") == 0 && i + 1 < argc) {
			homedir = argv[++i];
		} else {
			fprintf(stderr, "Illegal argument \"%s\"\n", argv[i]);
			print_usage();
			exit(EXIT_FAILURE);
		}
	}

	if (!settings_.init(homedir)) {
		fprintf(stderr, "The homedir[%s] is not exist\n", homedir.c_str());
		return -1;
	}
	string reason = settings_.load_conf();
	if (reason != "") {
		fprintf(stderr, "Failed to load configuration file, %s\n", reason.c_str());
		return -1;
	}
	log_init("xixibase_%N.log", 20 * 1024 * 1024);
	set_log_level(settings_.log_level);

	LOG_INFO(VERSION" start.");

	printf_system_info();

	settings_.print();

	try {
#if defined(_WIN32)
		SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
		signal(SIGINT, sigproc);
		signal(SIGHUP, sigproc);
		signal(SIGQUIT, sigproc);
		signal(SIGTERM, sigproc);
		signal(SIGPIPE, sigpipeproc);
#endif

		svr_ = new Server(settings_.pool_size, settings_.num_threads);

		if (svr_->start()) {
			svr_->run();
		}

		LOG_INFO("destory instance");
		delete svr_;
		svr_ = NULL;
	} catch (std::exception& e) {
		LOG_FATAL("Exception: " << e.what());
	}
	LOG_INFO(VERSION" stop.");

	return 0;
}
Exemple #16
0
static int gaa_try(int gaa_num, int gaa_index, gaainfo *gaaval, char *opt_list)
{
    int OK = 0;
    int gaa_last_non_option;
	struct GAAOPTION_port GAATMP_port;
	struct GAAOPTION_opaque_prf_input GAATMP_opaque_prf_input;
	struct GAAOPTION_pskkey GAATMP_pskkey;
	struct GAAOPTION_pskusername GAATMP_pskusername;
	struct GAAOPTION_srppasswd GAATMP_srppasswd;
	struct GAAOPTION_srpusername GAATMP_srpusername;
	struct GAAOPTION_x509certfile GAATMP_x509certfile;
	struct GAAOPTION_x509keyfile GAATMP_x509keyfile;
	struct GAAOPTION_pgpcertfile GAATMP_pgpcertfile;
	struct GAAOPTION_pgpkeyring GAATMP_pgpkeyring;
	struct GAAOPTION_pgpkeyfile GAATMP_pgpkeyfile;
	struct GAAOPTION_x509crlfile GAATMP_x509crlfile;
	struct GAAOPTION_x509cafile GAATMP_x509cafile;
	struct GAAOPTION_priority GAATMP_priority;
	struct GAAOPTION_ctypes GAATMP_ctypes;
	struct GAAOPTION_kx GAATMP_kx;
	struct GAAOPTION_macs GAATMP_macs;
	struct GAAOPTION_comp GAATMP_comp;
	struct GAAOPTION_protocols GAATMP_protocols;
	struct GAAOPTION_ciphers GAATMP_ciphers;
	struct GAAOPTION_recordsize GAATMP_recordsize;
	struct GAAOPTION_debug GAATMP_debug;

#line 393 "gaa.skel"
#ifdef GAA_REST_EXISTS
    struct GAAREST GAAREST_tmp;
#endif

    opt_list[gaa_num] = 1;
    
    for(gaa_last_non_option = gaa_index;
        (gaa_last_non_option != GAAargc) && (gaa_is_an_argument(GAAargv[gaa_last_non_option]) == GAA_NOT_AN_OPTION);
        gaa_last_non_option++);

    if(gaa_num == GAA_REST)
    {
        gaa_index = 1;
        gaa_last_non_option = GAAargc;
    }
    
    switch(gaa_num)
    {
	case GAAOPTID_copyright:
	OK = 0;
#line 117 "cli.gaa"
{ print_license(); exit(0); ;};

		return GAA_OK;
		break;
	case GAAOPTID_version:
	OK = 0;
#line 116 "cli.gaa"
{ cli_version(); exit(0); ;};

		return GAA_OK;
		break;
	case GAAOPTID_help:
	OK = 0;
#line 114 "cli.gaa"
{ gaa_help(); exit(0); ;};

		return GAA_OK;
		break;
	case GAAOPTID_list:
	OK = 0;
#line 113 "cli.gaa"
{ print_list(gaaval->verbose); exit(0); ;};

		return GAA_OK;
		break;
	case GAAOPTID_insecure:
	OK = 0;
#line 111 "cli.gaa"
{ gaaval->insecure = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_port:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_port.arg1, gaa_getstr, GAATMP_port.size1);
		gaa_index++;
#line 108 "cli.gaa"
{ gaaval->port = GAATMP_port.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_opaque_prf_input:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_opaque_prf_input.arg1, gaa_getstr, GAATMP_opaque_prf_input.size1);
		gaa_index++;
#line 105 "cli.gaa"
{ gaaval->opaque_prf_input = GAATMP_opaque_prf_input.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_pskkey:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_pskkey.arg1, gaa_getstr, GAATMP_pskkey.size1);
		gaa_index++;
#line 102 "cli.gaa"
{ gaaval->psk_key = GAATMP_pskkey.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_pskusername:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_pskusername.arg1, gaa_getstr, GAATMP_pskusername.size1);
		gaa_index++;
#line 99 "cli.gaa"
{ gaaval->psk_username = GAATMP_pskusername.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_srppasswd:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_srppasswd.arg1, gaa_getstr, GAATMP_srppasswd.size1);
		gaa_index++;
#line 96 "cli.gaa"
{ gaaval->srp_passwd = GAATMP_srppasswd.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_srpusername:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_srpusername.arg1, gaa_getstr, GAATMP_srpusername.size1);
		gaa_index++;
#line 93 "cli.gaa"
{ gaaval->srp_username = GAATMP_srpusername.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_x509certfile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_x509certfile.arg1, gaa_getstr, GAATMP_x509certfile.size1);
		gaa_index++;
#line 90 "cli.gaa"
{ gaaval->x509_certfile = GAATMP_x509certfile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_x509keyfile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_x509keyfile.arg1, gaa_getstr, GAATMP_x509keyfile.size1);
		gaa_index++;
#line 87 "cli.gaa"
{ gaaval->x509_keyfile = GAATMP_x509keyfile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_pgpcertfile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_pgpcertfile.arg1, gaa_getstr, GAATMP_pgpcertfile.size1);
		gaa_index++;
#line 84 "cli.gaa"
{ gaaval->pgp_certfile = GAATMP_pgpcertfile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_pgpkeyring:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_pgpkeyring.arg1, gaa_getstr, GAATMP_pgpkeyring.size1);
		gaa_index++;
#line 81 "cli.gaa"
{ gaaval->pgp_keyring = GAATMP_pgpkeyring.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_pgpkeyfile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_pgpkeyfile.arg1, gaa_getstr, GAATMP_pgpkeyfile.size1);
		gaa_index++;
#line 78 "cli.gaa"
{ gaaval->pgp_keyfile = GAATMP_pgpkeyfile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_x509crlfile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_x509crlfile.arg1, gaa_getstr, GAATMP_x509crlfile.size1);
		gaa_index++;
#line 75 "cli.gaa"
{ gaaval->x509_crlfile = GAATMP_x509crlfile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_x509cafile:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_x509cafile.arg1, gaa_getstr, GAATMP_x509cafile.size1);
		gaa_index++;
#line 72 "cli.gaa"
{ gaaval->x509_cafile = GAATMP_x509cafile.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_priority:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_priority.arg1, gaa_getstr, GAATMP_priority.size1);
		gaa_index++;
#line 69 "cli.gaa"
{ gaaval->priorities = GAATMP_priority.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_ctypes:
	OK = 0;
		GAA_LIST_FILL(GAATMP_ctypes.arg1, gaa_getstr, char*, GAATMP_ctypes.size1);
#line 66 "cli.gaa"
{ gaaval->ctype = GAATMP_ctypes.arg1; gaaval->nctype = GAATMP_ctypes.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_kx:
	OK = 0;
		GAA_LIST_FILL(GAATMP_kx.arg1, gaa_getstr, char*, GAATMP_kx.size1);
#line 62 "cli.gaa"
{ gaaval->kx = GAATMP_kx.arg1; gaaval->nkx = GAATMP_kx.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_macs:
	OK = 0;
		GAA_LIST_FILL(GAATMP_macs.arg1, gaa_getstr, char*, GAATMP_macs.size1);
#line 58 "cli.gaa"
{ gaaval->macs = GAATMP_macs.arg1; gaaval->nmacs = GAATMP_macs.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_comp:
	OK = 0;
		GAA_LIST_FILL(GAATMP_comp.arg1, gaa_getstr, char*, GAATMP_comp.size1);
#line 54 "cli.gaa"
{ gaaval->comp = GAATMP_comp.arg1; gaaval->ncomp = GAATMP_comp.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_protocols:
	OK = 0;
		GAA_LIST_FILL(GAATMP_protocols.arg1, gaa_getstr, char*, GAATMP_protocols.size1);
#line 50 "cli.gaa"
{ gaaval->proto = GAATMP_protocols.arg1; gaaval->nproto = GAATMP_protocols.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_ciphers:
	OK = 0;
		GAA_LIST_FILL(GAATMP_ciphers.arg1, gaa_getstr, char*, GAATMP_ciphers.size1);
#line 46 "cli.gaa"
{ gaaval->ciphers = GAATMP_ciphers.arg1; gaaval->nciphers = GAATMP_ciphers.size1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_verbose:
	OK = 0;
#line 42 "cli.gaa"
{ gaaval->verbose = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_recordsize:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_recordsize.arg1, gaa_getint, GAATMP_recordsize.size1);
		gaa_index++;
#line 39 "cli.gaa"
{ gaaval->record_size = GAATMP_recordsize.arg1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_print_cert:
	OK = 0;
#line 36 "cli.gaa"
{ gaaval->print_cert = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_disable_extensions:
	OK = 0;
#line 33 "cli.gaa"
{ gaaval->disable_extensions = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_fingerprint:
	OK = 0;
#line 30 "cli.gaa"
{ gaaval->fingerprint = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_x509fmtder:
	OK = 0;
#line 27 "cli.gaa"
{ gaaval->fmtder = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_crlf:
	OK = 0;
#line 24 "cli.gaa"
{ gaaval->crlf = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_starttls:
	OK = 0;
#line 21 "cli.gaa"
{ gaaval->starttls = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_resume:
	OK = 0;
#line 18 "cli.gaa"
{ gaaval->resume = 1 ;};

		return GAA_OK;
		break;
	case GAAOPTID_debug:
	OK = 0;
		GAA_TESTMOREARGS;
		GAA_FILL(GAATMP_debug.arg1, gaa_getint, GAATMP_debug.size1);
		gaa_index++;
#line 15 "cli.gaa"
{ gaaval->debug = GAATMP_debug.arg1 ;};

		return GAA_OK;
		break;
	case GAA_REST:
		GAA_TESTMOREARGS;
		GAA_FILL(GAAREST_tmp.arg1, gaa_getstr, GAAREST_tmp.size1);
		gaa_index++;
#line 120 "cli.gaa"
{ gaaval->rest_args = GAAREST_tmp.arg1; ;};

		return GAA_OK;
		break;

#line 413 "gaa.skel"
    default: break;
    }
    return GAA_ERROR_UNKNOWN;
}
Exemple #17
0
int main(int argc, char **argv)
{
	video_playback_setup *settings;
	 
    	sigset_t allsignals;
    	struct sigaction action;
	struct timespec req;
	int i;
	fflush(stdout);

	vj_mem_init();

	vevo_strict_init();
	
	info = veejay_malloc();
	if (!info) {
		vj_mem_threaded_stop();
		return 1;
	}
	
   	settings = (video_playback_setup *) info->settings;

	if(!check_command_line_options(argc, argv))
	{
		veejay_free(info);
		return 0;
    	}

	
   	if(info->dump)
 	{
		veejay_set_colors(0);
		vj_event_init(NULL);
		vj_effect_initialize(720,576,0);
		vj_osc_allocate(VJ_PORT+2);	
		vj_event_dump();
		vj_effect_dump();
			fprintf(stdout, "Environment variables:\n\tSDL_VIDEO_HWACCEL\t\tSet to 1 to use SDL video hardware accel (default=on)\n\tVEEJAY_PERFORMANCE\t\tSet to \"quality\" or \"fastest\" (default is fastest)\n\tVEEJAY_AUTO_SCALE_PIXELS\tSet to 1 to convert between CCIR 601 and JPEG automatically (default=dont care)\n\tVEEJAY_INTERPOLATE_CHROMA\tSet to 1 if you wish to interpolate every chroma sample when scaling (default=0)\n\tVEEJAY_CAPTURE_DRIVER\t\tSet to \"unicap\" or \"v4lutils\" (default=v4lutils)\n\tVEEJAY_SDL_KEY_REPEAT_INTERVAL\tinterval of key pressed to repeat while pressed down.\n\tVEEJAY_PLAYBACK_CACHE\t\tSample cache size in MB - by default, veejay takes 30 percent of total RAM\n\tVEEJAY_SDL_KEY_REPEAT_DELAY\tDelay key repeat in ms\n\tVEEJAY_FULLSCREEN\t\tStart in fullscreen (1) or windowed (0) mode\n\tVEEJAY_SCREEN_GEOMETRY\t\tSpecifiy a geometry for veejay to position the video window.\n\tVEEJAY_SCREEN_SIZE\t\tSize of video window, defaults to full screen size.\n\tVEEJAY_RUN_MODE\t\t\tRun in \"classic\" (352x288 Dummy) or default (720x576). \n");
			fprintf(stdout, "\n\n\tExample for bash:\n\t\t\t$ export VEEJAY_AUTO_SCALE_PIXEL=1\n");


		veejay_free(info);
		return 0;
	}

	if( vj_el_get_mem_size() == 0 )
		prepare_cache_line( max_mem_, n_slots_ );

	veejay_check_homedir( info );

	sigsegfault_handler();

    	sigemptyset(&(settings->signal_set));
	sigaddset(&(settings->signal_set), SIGINT);
	sigaddset(&(settings->signal_set), SIGPIPE);
	sigaddset(&(settings->signal_set), SIGILL);
//	sigaddset(&(settings->signal_set), SIGSEGV);
	sigaddset(&(settings->signal_set), SIGFPE );
	sigaddset(&(settings->signal_set), SIGTERM );
	sigaddset(&(settings->signal_set), SIGABRT);
	sigaddset(&(settings->signal_set), SIGPWR );
	sigaddset(&(settings->signal_set), SIGQUIT );

	sigfillset( &allsignals );
	action.sa_handler = donothing;
	action.sa_mask = allsignals;
	action.sa_flags = SA_SIGINFO | SA_ONESHOT ; //SA_RESTART | SA_RESETHAND;

	signal( SIGPIPE, SIG_IGN );

	for( i = 1; i < NSIG; i ++ )
		if( sigismember( &(settings->signal_set), i ))
			sigaction( i, &action, 0 );
	
	char *mem_func = get_memcpy_descr();
	if(mem_func)
	{
		veejay_msg(VEEJAY_MSG_INFO, "Using SIMD %s", mem_func);
		free(mem_func);
	}
	info->use_keyb = use_keyb;
	info->use_mouse = use_mouse;
	info->show_cursor = show_cursor;


	if(veejay_init(
		info,
		default_geometry_x,
		default_geometry_y,
		NULL,
		live,
	    ta	)< 0)
	{	
		veejay_msg(VEEJAY_MSG_ERROR, "Cannot start veejay");
		return 0;
	}

	if(auto_loop)
		veejay_auto_loop(info);


	print_license();

	veejay_init_msg_ring();  // rest of logging to screen

    	if(!veejay_main(info))
	{
	    veejay_msg(VEEJAY_MSG_ERROR, "Cannot start main playback cycle");
		veejay_free(info);
		return 1;
	}

	
	veejay_msg(VEEJAY_MSG_DEBUG, "Started playback");

	int current_state = LAVPLAY_STATE_PLAYING;

	req.tv_sec = 0;
	req.tv_nsec = 4000 * 1000; 

	while( 1 ) { //@ until your PC stops working
		
		clock_nanosleep( CLOCK_REALTIME, 0, &req, NULL );

		current_state = veejay_get_state(info);
		
		if( current_state == LAVPLAY_STATE_STOP )
			break;
	}

	veejay_busy(info);			
	veejay_free(info);
	veejay_destroy_msg_ring();

	veejay_msg(VEEJAY_MSG_INFO, "Thank you for using Veejay");

	return 0;
}
Exemple #18
0
void parse_worker_command_line( int argc, char **argv, char **env,
		int *daemon_mode, char **worker_socket, char **worker_user,
		char **worker_group) {
	int c = 0;
	int display_usage = FALSE;
	int display_license = FALSE;

#ifdef HAVE_GETOPT_H
	int option_index = 0;
	static struct option long_options[] = {
		{ "help", no_argument, 0, 'h'},
		{ "version", no_argument, 0, 'V'},
		{ "license", no_argument, 0, 'V'},
		{ "daemon", no_argument, 0, 'd'},
		{ "worker", required_argument, 0, 'W'},
		{ "user", required_argument, 0, 'u'},
		{ "group", required_argument, 0, 'g'},
		{ 0, 0, 0, 0}
	};
#define getopt( argc, argv, o) getopt_long( argc, argv, o, long_options, &option_index)
#endif

	/* get all command line arguments */
	while( 1) {
		c = getopt( argc, argv, "+:hVdW:u:g:");

		if( -1 == c || EOF == c) break;

		switch( c) {

			case '?': /* usage */
			case 'h':
				display_usage = TRUE;
				break;

			case 'V': /* version */
				display_license = TRUE;
				break;

			case 'd': /* daemon mode */
				*daemon_mode = TRUE;
				break;

			case 'W':
				*worker_socket = optarg;
				break;

			case 'u':
				*worker_user = optarg;
				break;

			case 'g':
				*worker_group = optarg;
				break;

			case ':':
				printf( "Missing argument for command line option '%c'.\n\n",
						optopt);
				print_usage( argv[ 0]);
				exit( 1);
				break;

			default:
				printf( "Unknown command line option '%c'.\n\n", c);
				print_usage( argv[ 0]);
				exit( 1);
				break;
		}
	}

	if( TRUE == display_license) {
		print_version();
		print_license();
		exit( 0);
	}

	if( TRUE == display_usage) {
		print_usage( argv[ 0]);
		exit( 0);
	}

}
Exemple #19
0
int main(int argc, char **argv)
{
	g_BufferedMemorySize = 100;

	string compressorName;
	string commandLineOptions;

	std::vector<string> fuseOptions;
	fuseOptions.push_back(argv[0]);

	po::options_description desc("Usage: " PACKAGE "_offline [options] path\n"
	                                "\nPath may be directory or file.\n"
	                                "\nNo options mean decompression mode.\n\n"
	                                "Allowed options");
	desc.add_options()
		("options,o", po::value<string>(&commandLineOptions),
				"fc_c:arg  - compression method (lzo/bzip2/zlib/lzma)\n"
				"            (default: gz)\n"
				"fc_b:arg  - size of blocks in kilobytes\n"
				"            (default: 100)\n"
				"fc_d      - run in debug mode\n"
				"fc_ma:arg - files with passed mime types to be\n"
				"            always not compressed\n"
				"fc_mr:arg - files with passed mime types to be\n"
				"            always compressed\n"
				"\nOther options are passed directly to fuse library. See fuse documentation for full list of supported options.\n")
		("dir_lower", po::value<string>(&g_dirLower), "path")
		("help,h", "print this help")
		("version,v", "print version")
		("quiet,q", "quiet mode")
	;

	po::positional_options_description pdesc;
	pdesc.add("dir_lower", 1);

	po::variables_map vm;
	try {
		po::store(po::command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);
	} catch (...) {
		print_help(desc);
		exit(EXIT_FAILURE);
	}
	po::notify(vm);

	if (vm.count("help"))
	{
		print_help(desc);
		exit(EXIT_SUCCESS);
	}
	if (vm.count("version"))
	{
		print_license();
		exit(EXIT_SUCCESS);
	}
	if (vm.count("quiet"))
	{
		g_QuietMode = true;
	}

	g_RLog = new rlog::RLog("FuseCompress_offline", g_QuietMode ? LOG_NOTICE : LOG_INFO, true);

	if (vm.count("options"))
	{
		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> sep(",");
		tokenizer tokens(commandLineOptions, sep);

		for (tokenizer::iterator tok_it = tokens.begin(); tok_it != tokens.end(); ++tok_it)
		{
			if ((*tok_it).find_first_of("fc_", 0, 3) == 0)
			{
				typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
				boost::char_separator<char> sep(":");
				tokenizer tokens(*tok_it, sep);

				tokenizer::iterator key = tokens.begin();
				tokenizer::iterator value = key; ++value;

				if (*key == "fc_c")
				{
					if (value == tokens.end())
					{
						rError("Compression type not set!");
						exit(EXIT_FAILURE);
					}
					compressorName = *value;
				}
				if (*key == "fc_b")
				{
					if (value == tokens.end())
					{
						rError("Block size not set!");
						exit(EXIT_FAILURE);
					}
					g_BufferedMemorySize = boost::lexical_cast<unsigned int>(*value);
				}
				if (*key == "fc_d")
				{
					g_DebugMode = true;
					g_RLog->setLevel(LOG_DEBUG);
				}
				if (*key == "fc_ma")
				{
					if (value == tokens.end())
					{
						rError("Mime type(s) not set!");
						exit(EXIT_FAILURE);
					}
					g_CompressedMagic.Add(*value);
				}
				if (*key == "fc_mr")
				{
					if (value == tokens.end())
					{
						rError("Mime type(s) not set!");
						exit(EXIT_FAILURE);
					}
					g_CompressedMagic.Remove(*value);
				}
			}
			else
			{
				fuseOptions.push_back("-o");
				fuseOptions.push_back(*tok_it);
			}
		}
	}
	if (!vm.count("dir_lower"))
	{
		print_help(desc);
		exit(EXIT_FAILURE);
	}

	g_BufferedMemorySize *= 1024;

	if (compressorName != "")
	{
		g_RawOutput = false;

		if (g_CompressionType.parseType(compressorName) == false)
		{
			rError("Compressor %s not found!", compressorName.c_str());
			exit(EXIT_FAILURE);
		}
	}

	fs::path pathLower(g_dirLower
#if BOOST_VERSION <= 104600
            , fs::native
#endif
            );

	if (!pathLower.is_complete())
	{
		char cwd[PATH_MAX];

		// Transform relative path to absolute path.

		if (getcwd(cwd, sizeof(cwd)) == NULL)
		{
			rError("Cannot determine current working directory!");
			exit(EXIT_FAILURE);
		}

        pathLower = fs::path(cwd
#if BOOST_VERSION <= 104600
                , fs::native
#endif
                ) / pathLower;
	}

	// Set signal handler to catch SIGINT (CTRL+C).

	struct sigaction setup_kill;
	memset(&setup_kill, 0, sizeof(setup_kill));
	setup_kill.sa_handler = catch_kill;
	sigaction(SIGINT, &setup_kill, NULL);

	// Iterate over directory structure and execute compress
	// for every files there.

	if (nftw(const_cast<char *>(pathLower.string().c_str()), compress, 100, FTW_PHYS | FTW_CHDIR))
		exit(EXIT_FAILURE);

	exit(EXIT_SUCCESS);
}
Exemple #20
0
int main(int argc, char *argv[])
{
	int c;
	int daemonize = 0;
	int port = SIGMA_DUT_PORT;
	char *local_cmd = NULL;
#ifdef __QNXNTO__
	char *env_str = NULL;
	char buf[20];
	char *sigma_ctrl_sock = NULL; /* env used for QNX */
#endif /* __QNXNTO__ */

	memset(&sigma_dut, 0, sizeof(sigma_dut));
	sigma_dut.debug_level = DUT_MSG_INFO;
	sigma_dut.default_timeout = 120;
	sigma_dut.dialog_token = 0;
	set_defaults(&sigma_dut);

	for (;;) {
		c = getopt(argc, argv,
			   "ab:Bc:C:dDE:e:fhH:i:Ik:l:L:m:M:np:qr:R:s:S:tT:uv:VWw:");
		if (c < 0)
			break;
		switch (c) {
		case 'a':
			sigma_dut.ap_anqpserver = 1;
			break;
		case 'b':
			sigma_dut.bridge = optarg;
			break;
		case 'B':
			daemonize++;
			break;
		case 'C':
			sigma_cert_path = optarg;
			break;
		case 'd':
			if (sigma_dut.debug_level > 0)
				sigma_dut.debug_level--;
			break;
#ifdef __QNXNTO__
		case 'E':
			sigma_ctrl_sock = optarg;
			break;
#endif /* __QNXNTO__ */
		case 'D':
			sigma_dut.stdout_debug = 1;
			break;
		case 'e':
			sigma_dut.hostapd_entropy_log = optarg;
			break;
		case 'f':
			/* Disable writing stats */
			sigma_dut.write_stats = 0;
			break;
		case 'H':
			sigma_dut.hostapd_debug_log = optarg;
			break;
		case 'I':
			print_license();
			exit(0);
			break;
		case 'l':
			local_cmd = optarg;
			break;
		case 'L':
			sigma_dut.summary_log = optarg;
			break;
		case 'p':
			port = atoi(optarg);
			break;
		case 'q':
			sigma_dut.debug_level++;
			break;
		case 'r':
			if (strcmp(optarg, "HT40") == 0) {
				sigma_dut.default_ap_chwidth = AP_40;
			} else {
				printf("Unsupported -r value\n");
				exit(1);
			}
			break;
		case 'R': {
			static int num_radio = 0;
			static char **radio_ptr = sigma_radio_ifname;

			num_radio++;
			if (num_radio > MAX_RADIO) {
				printf("Multiple radio support limit (%d) exceeded\n",
				       MAX_RADIO);
				exit(1);
			}
			*radio_ptr++ = optarg;
			break;
		}
		case 's':
			sigma_dut.sniffer_ifname = optarg;
			break;
		case 't':
			sigma_dut.no_timestamps = 1;
			break;
		case 'T':
			sigma_dut.throughput_pktsize = atoi(optarg);
			if (sigma_dut.throughput_pktsize <= 0) {
				printf("Invalid -T value\n");
				exit(0);
			}
			break;
		case 'm':
			sigma_dut.set_macaddr = optarg;
			break;
		case 'M':
			sigma_main_ifname = optarg;
			break;
		case 'n':
			sigma_dut.no_ip_addr_set = 1;
			break;
		case 'S':
			sigma_station_ifname = optarg;
			break;
		case 'w':
			sigma_hapd_ctrl = optarg;
			sigma_wpas_ctrl = optarg;
			break;
		case 'i':
			ap_inet_addr = optarg;
			break;
		case 'k':
			ap_inet_mask = optarg;
			break;
		case 'c':
			printf("%s", optarg);
			if (set_wifi_chip(optarg) < 0)
				sigma_dut_print(&sigma_dut, DUT_MSG_ERROR,
						"WRONG CHIP TYPE: SAP will "
						"not load");
			break;
		case 'v':
			sigma_dut.version = optarg;
			break;
		case 'V':
			printf("sigma_dut " SIGMA_DUT_VER "\n");
			exit(0);
			break;
		case 'W':
			sigma_dut_print(&sigma_dut, DUT_MSG_INFO,
					"Running WMM-AC test suite");
			sigma_wmm_ac = 1;
			break;
		case 'u':
		       sigma_dut_print(&sigma_dut, DUT_MSG_INFO,
				       "Use iface down/up in reset cmd");
		       sigma_dut.iface_down_on_reset = 1;
		       break;
		case 'h':
		default:
			printf("usage: sigma_dut [-aBdfqDIntuVW] [-p<port>] "
			       "[-s<sniffer>] [-m<set_maccaddr.sh>] \\\n"
				"       [-M<main ifname>] [-R<radio ifname>] "
			       "[-S<station ifname>] \\\n"
			       "       [-T<throughput pktsize>] \\\n"
			       "       [-w<wpa_supplicant/hostapd ctrl_iface "
			       "dir>] \\\n"
			       "       [-H <hostapd log file>] \\\n"
			       "       [-C <certificate path>] \\\n"
			       "       [-v <version string>] \\\n"
			       "       [-L <summary log>] \\\n"
			       "       [-c <wifi chip type: WCN or ATHEROS or "
			       "AR6003 or MAC80211 or QNXNTO or OPENWRT>] "
			       "\\\n"
			       "       [-i <IP address of the AP>] \\\n"
			       "       [-k <subnet mask for the AP>] \\\n"
			       "       [-e <hostapd entropy file>] \\\n"
			       "       [-r <HT40>]\n");
			printf("local command: sigma_dut [-p<port>] "
			       "<-l<cmd>>\n");
			exit(0);
			break;
		}
	}

	if (local_cmd)
		return run_local_cmd(port, local_cmd);

	if (wifi_chip_type == DRIVER_QNXNTO &&
	    (sigma_main_ifname == NULL || sigma_station_ifname == NULL)) {
		sigma_dut_print(&sigma_dut, DUT_MSG_ERROR,
				"Interface should be provided for QNX driver check option M and S");
	}

	sigma_dut_register_cmds();

#ifdef __QNXNTO__
	/* Try to open socket in other env dev */
	if (sigma_ctrl_sock) {
		env_str = getenv("SOCK");
		if (env_str) {
			sigma_dut_print(&sigma_dut, DUT_MSG_INFO,
					"SOCK=%s", env_str);
		}
		snprintf(buf, sizeof(buf), "SOCK=%s", sigma_ctrl_sock);
		if (putenv(buf) != 0) {
			sigma_dut_print(&sigma_dut, DUT_MSG_ERROR,
					"putenv() failed setting SOCK");
			return EXIT_FAILURE;
		}
	}
#endif /* __QNXNTO__ */

	if (open_socket(&sigma_dut, port) < 0)
		return -1;

#ifdef __QNXNTO__
	/* restore back the SOCK */
	if (sigma_ctrl_sock) {
		if (env_str) {
			snprintf(buf, sizeof(buf), "SOCK=%s", env_str);
			if (putenv(buf) != 0) {
				sigma_dut_print(&sigma_dut, DUT_MSG_ERROR,
						"putenv() failed setting SOCK");
				return EXIT_FAILURE;
			}
		} else {
			/* unset the env for sock */
			unsetenv("SOCK");
		}
	}
#endif /* __QNXNTO__ */

	if (daemonize) {
		if (daemon(0, 0) < 0) {
			perror("daemon");
			exit(-1);
		}
	} else {
#ifdef __linux__
		setlinebuf(stdout);
#endif /* __linux__ */
	}

	run_loop(&sigma_dut);

#ifdef CONFIG_SNIFFER
	sniffer_close(&sigma_dut);
#endif /* CONFIG_SNIFFER */

	close_socket(&sigma_dut);
	sigma_dut_unreg_cmds(&sigma_dut);

	return 0;
}
Exemple #21
0
int main(int argc, char **argv) {

#ifdef _OPENMP
  printf("ERKALE - Geometry optimization from Hel, OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - Geometry optimization from Hel, serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=2) {
    printf("Usage: $ %s runfile\n",argv[0]);
    return 0;
  }

  // Initialize libint
  init_libint_base();
  // Initialize libderiv
  init_libderiv_base();

  Timer tprog;
  tprog.print_time();

  // Parse settings
  Settings set;
  set.add_scf_settings();
  set.add_string("SaveChk","File to use as checkpoint","erkale.chk");
  set.add_string("LoadChk","File to load old results from","");
  set.add_bool("ForcePol","Force polarized calculation",false);
  set.add_bool("FreezeCore","Freeze the atomic cores?",false);
  set.add_string("Optimizer","Optimizer to use: CGFR, CGPR, BFGS, BFGS2 (default), SD","BFGS2");
  set.add_int("MaxSteps","Maximum amount of geometry steps",256);
  set.add_string("Criterion","Convergence criterion to use: LOOSE, NORMAL, TIGHT, VERYTIGHT","NORMAL");
  set.add_string("OptMovie","xyz movie to store progress in","optimize.xyz");
  set.add_string("Result","File to save optimized geometry in","optimized.xyz");
  set.set_string("Logfile","erkale_geom.log");
  set.parse(std::string(argv[1]),true);
  set.print();

  bool verbose=set.get_bool("Verbose");
  int maxiter=set.get_int("MaxSteps");
  std::string optmovie=set.get_string("OptMovie");
  std::string result=set.get_string("Result");

  // Interpret optimizer
  enum minimizer alg;
  std::string method=set.get_string("Optimizer");
  if(stricmp(method,"CGFR")==0)
    alg=gCGFR;
  else if(stricmp(method,"CGPR")==0)
    alg=gCGPR;
  else if(stricmp(method,"BFGS")==0)
    alg=gBFGS;
  else if(stricmp(method,"BFGS2")==0)
    alg=gBFGS2;
  else if(stricmp(method,"SD")==0)
    alg=gSD;
  else {
    ERROR_INFO();
    throw std::runtime_error("Unknown optimization method.\n");
  }

  // Interpret optimizer
  enum convergence crit;
  method=set.get_string("Criterion");
  if(stricmp(method,"LOOSE")==0)
    crit=LOOSE;
  else if(stricmp(method,"NORMAL")==0)
    crit=NORMAL;
  else if(stricmp(method,"TIGHT")==0)
    crit=TIGHT;
  else if(stricmp(method,"VERYTIGHT")==0)
    crit=VERYTIGHT;
  else {
    ERROR_INFO();
    throw std::runtime_error("Unknown optimization method.\n");
  }

  // Redirect output?
  std::string logfile=set.get_string("Logfile");
  if(stricmp(logfile,"stdout")!=0) {
    // Redirect stdout to file
    FILE *outstream=freopen(logfile.c_str(),"w",stdout);
    if(outstream==NULL) {
      ERROR_INFO();
      throw std::runtime_error("Unable to redirect output!\n");
    } else
      fprintf(stderr,"\n");
  }

  // Read in atoms.
  std::string atomfile=set.get_string("System");
  const std::vector<atom_t> origgeom=load_xyz(atomfile);
  std::vector<atom_t> atoms(origgeom);

  // Are any atoms fixed?
  std::vector<size_t> dofidx;
  for(size_t i=0;i<atoms.size();i++) {
    bool fixed=false;

    if(atoms[i].el.size()>3)
      if(stricmp(atoms[i].el.substr(atoms[i].el.size()-3),"-Fx")==0) {
	fixed=true;
	atoms[i].el=atoms[i].el.substr(0,atoms[i].el.size()-3);
      }

    // Add to degrees of freedom
    if(!fixed)
      dofidx.push_back(i);
  }

  // Read in basis set
  BasisSetLibrary baslib;
  std::string basfile=set.get_string("Basis");
  baslib.load_gaussian94(basfile);
  printf("\n");

  // Save to output
  save_xyz(atoms,"Initial configuration",optmovie,false);

  // Minimizer options
  opthelper_t pars;
  pars.atoms=atoms;
  pars.baslib=baslib;
  pars.set=set;
  pars.dofidx=dofidx;

  /* Starting point */
  gsl_vector *x = gsl_vector_alloc (3*dofidx.size());
  for(size_t i=0;i<dofidx.size();i++) {
    gsl_vector_set(x,3*i,atoms[dofidx[i]].x);
    gsl_vector_set(x,3*i+1,atoms[dofidx[i]].y);
    gsl_vector_set(x,3*i+2,atoms[dofidx[i]].z);
  }

  // GSL status
  int status;

  const gsl_multimin_fdfminimizer_type *T;
  gsl_multimin_fdfminimizer *s;

  gsl_multimin_function_fdf minimizer;

  minimizer.n = x->size;
  minimizer.f = calc_E;
  minimizer.df = calc_f;
  minimizer.fdf = calc_Ef;
  minimizer.params = (void *) &pars;

  if(alg==gCGFR) {
    T = gsl_multimin_fdfminimizer_conjugate_fr;
    if(verbose) printf("Using Fletcher-Reeves conjugate gradients.\n");
  } else if(alg==gCGPR) {
    T = gsl_multimin_fdfminimizer_conjugate_pr;
    if(verbose) printf("Using Polak-Ribière conjugate gradients.\n");
  } else if(alg==gBFGS) {
    T = gsl_multimin_fdfminimizer_vector_bfgs;
    if(verbose) printf("Using the BFGS minimizer.\n");
  } else if(alg==gBFGS2) {
    T = gsl_multimin_fdfminimizer_vector_bfgs2;
    if(verbose) printf("Using the BFGS2 minimizer.\n");
  } else if(alg==gSD) {
    T = gsl_multimin_fdfminimizer_steepest_descent;
    if(verbose) printf("Using the steepest descent minimizer.\n");
  } else {
    ERROR_INFO();
    throw std::runtime_error("Unsupported minimizer\n");
  }

  // Run an initial calculation
  double oldE=calc_E(x,minimizer.params);

  // Turn off verbose setting
  pars.set.set_bool("Verbose",false);
  // and load from old checkpoint
  pars.set.set_string("LoadChk",pars.set.get_string("SaveChk"));

  // Initialize minimizer
  s = gsl_multimin_fdfminimizer_alloc (T, minimizer.n);

  // Use initial step length of 0.02 bohr, and a line search accuracy
  // 1e-1 (recommended in the GSL manual for BFGS)
  gsl_multimin_fdfminimizer_set (s, &minimizer, x, 0.02, 1e-1);

  // Store old force
  arma::mat oldf=interpret_force(s->gradient);

  fprintf(stderr,"Geometry optimizer initialized in %s.\n",tprog.elapsed().c_str());
  fprintf(stderr,"Entering minimization loop with %s optimizer.\n",set.get_string("Optimizer").c_str());

  fprintf(stderr,"%4s %16s %10s %10s %9s %9s %9s %9s %s\n","iter","E","dE","dE/dEproj","disp max","disp rms","f max","f rms", "titer");

  std::vector<atom_t> oldgeom(atoms);

  bool convd=false;
  int iter;

  for(iter=1;iter<=maxiter;iter++) {
    printf("\nGeometry iteration %i\n",(int) iter);
    fflush(stdout);

    Timer titer;

    status = gsl_multimin_fdfminimizer_iterate (s);

    if (status) {
      fprintf(stderr,"GSL encountered error: \"%s\".\n",gsl_strerror(status));
      break;
    }

    // New geometry is
    std::vector<atom_t> geom=get_atoms(s->x,pars);

    // Calculate displacements
    double dmax, drms;
    get_displacement(geom, oldgeom, dmax, drms);

    // Calculate projected change of energy
    double dEproj=calculate_projection(geom,oldgeom,oldf,pars.dofidx);
    // Actual change of energy is
    double dE=s->f - oldE;

    // Switch geometries
    oldgeom=geom;
    // Save old force

    // Get forces
    double fmax, frms;
    get_forces(s->gradient, fmax, frms);

    // Save geometry step
    char comment[80];
    sprintf(comment,"Step %i",(int) iter);
    save_xyz(get_atoms(s->x,pars),comment,optmovie,true);

    // Check convergence
    bool fmaxconv=false, frmsconv=false;
    bool dmaxconv=false, drmsconv=false;

    switch(crit) {

    case(LOOSE):
      if(fmax < 2.5e-3)
	fmaxconv=true;
      if(frms < 1.7e-3)
	frmsconv=true;
      if(dmax < 1.0e-2)
	dmaxconv=true;
      if(drms < 6.7e-3)
	drmsconv=true;
      break;

    case(NORMAL):
      if(fmax < 4.5e-4)
	fmaxconv=true;
      if(frms < 3.0e-4)
	frmsconv=true;
      if(dmax < 1.8e-3)
	dmaxconv=true;
      if(drms < 1.2e-3)
	drmsconv=true;
      break;

    case(TIGHT):
      if(fmax < 1.5e-5)
	fmaxconv=true;
      if(frms < 1.0e-5)
	frmsconv=true;
      if(dmax < 6.0e-5)
	dmaxconv=true;
      if(drms < 4.0e-5)
	drmsconv=true;
      break;

    case(VERYTIGHT):
      if(fmax < 2.0e-6)
	fmaxconv=true;
      if(frms < 1.0e-6)
	frmsconv=true;
      if(dmax < 6.0e-6)
	dmaxconv=true;
      if(drms < 4.0e-6)
	drmsconv=true;
      break;

    default:
      ERROR_INFO();
      throw std::runtime_error("Not implemented!\n");
    }

    // Converged?
    const static char cconv[]=" *";

    double dEfrac;
    if(dEproj!=0.0)
      dEfrac=dE/dEproj;
    else
      dEfrac=0.0;

    fprintf(stderr,"%4d % 16.8f % .3e % .3e %.3e%c %.3e%c %.3e%c %.3e%c %s\n", (int) iter, s->f, dE, dEfrac, dmax, cconv[dmaxconv], drms, cconv[drmsconv], fmax, cconv[fmaxconv], frms, cconv[frmsconv], titer.elapsed().c_str());
    fflush(stderr);

    convd=dmaxconv && drmsconv && fmaxconv && frmsconv;

    if(convd) {
      fprintf(stderr,"Converged.\n");
      break;
    }

    // Store old energy
    oldE=s->f;
    // Store old force
    oldf=interpret_force(s->gradient);
  }

  if(convd)
    save_xyz(get_atoms(s->x,pars),"Optimized geometry",result);

  gsl_multimin_fdfminimizer_free (s);

  gsl_vector_free (x);

  if(iter==maxiter && !convd) {
    printf("Geometry convergence was not achieved!\n");
  }


  printf("Running program took %s.\n",tprog.elapsed().c_str());

  return 0;
}
Exemple #22
0
int main(int argc, char **argv) {
  printf("ERKALE - Basis set tools from Hel.\n");
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc<3) {
    printf("Usage: %s input.gbs command\n\n",argv[0]);
    help();
    return 0;
  }

  // Get filename
  std::string filein(argv[1]);
  // Load input
  BasisSetLibrary bas;
  bas.load_gaussian94(filein);

  // Get command
  std::string cmd(argv[2]);
  // and determine what to do.
  if(stricmp(cmd,"cholesky")==0) {
    // Print completeness profile.

    if(argc!=7) {
      printf("\nUsage: %s input.gbs cholesky thr maxam ovlthr output.gbs\n",argv[0]);
      return 1;
    }

    double thr(atof(argv[3]));
    int maxam(atoi(argv[4]));
    double ovlthr(atof(argv[5]));
    std::string outfile(argv[6]);

    if(maxam>=LIBINT_MAX_AM) {
      printf("Setting maxam = %i because limitations in used version of LIBINT.\n",LIBINT_MAX_AM-1);
      maxam=LIBINT_MAX_AM-1;
    }
			       
    init_libint_base();
    BasisSetLibrary ret=bas.cholesky_set(thr,maxam,ovlthr);
    ret.save_gaussian94(outfile);
    
  } else if(stricmp(cmd,"completeness")==0) {
    // Print completeness profile.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs completeness element output.dat (coulomb)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);
    bool coulomb=false;
    if(argc==6)
      coulomb=atoi(argv[5]);

    // Get wanted element from basis
    ElementBasisSet elbas=bas.get_element(el);

    // Compute completeness profile
    compprof_t prof=compute_completeness(elbas,-10.0,10.0,2001,coulomb);

    // Print profile in output file
    FILE *out=fopen(fileout.c_str(),"w");
    for(size_t i=0;i<prof.lga.size();i++) {
      // Value of scanning exponent
      fprintf(out,"%13e",prof.lga[i]);
      // Print completeness of shells
      for(size_t j=0;j<prof.shells.size();j++)
	fprintf(out,"\t%13e",prof.shells[j].Y[i]);
      fprintf(out,"\n");
    }
    fclose(out);

  } else if(stricmp(cmd,"composition")==0) {
    // Determine composition of basis set.

    if(argc!=3 && argc!=4) {
      printf("\nUsage: %s input.gbs composition (El)\n",argv[0]);
      return 1;
    }

    // Elemental basis sets
    std::vector<ElementBasisSet> elbases;

    if(argc==4)
      elbases.push_back(bas.get_element(argv[3]));
    else
      elbases=bas.get_elements();

    printf("\n");
    printf("el at#  [npr|nbf] [primitive|contracted(?)]\n");
    printf("-------------------------------------------\n");

    // Loop over elements
    for(size_t iel=0;iel<elbases.size();iel++) {
      // Get the basis set
      ElementBasisSet elbas=elbases[iel];

      // Decontracted basis
      ElementBasisSet eldec(elbas);
      eldec.decontract();

      // Get the shells
      std::vector<FunctionShell> sh=elbas.get_shells();
      std::vector<FunctionShell> decsh=eldec.get_shells();

      // Count the shells
      arma::imat Nsh(max_am,2);
      Nsh.zeros();
      for(size_t ish=0;ish<decsh.size();ish++)
	Nsh(decsh[ish].get_am(),0)++;
      for(size_t ish=0;ish<sh.size();ish++)
	Nsh(sh[ish].get_am(),1)++;

      // Determine if basis set is contracted and the amount of
      // functions
      bool contr=false;
      size_t nbf=0;
      size_t nprim=0;
      for(int am=0;am<max_am;am++) {
	// Number of primitives
	nprim+=Nsh(am,0)*(2*am+1);
	// Number of contracted functions
	nbf+=Nsh(am,1)*(2*am+1);
      }
      if(nbf!=nprim)
	contr=true;

      // Print composition
      printf("%-2s %3i ",elbas.get_symbol().c_str(),(int) elbas.get_number());
      if(contr) {
	// Print amount of functions
	char cmp[20];
	sprintf(cmp,"[%i|%i]",(int) nprim,(int) nbf);
	printf("%10s [",cmp);

	// Print primitives
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	// Print contractions
	printf("|");
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)!=Nsh(am,1))
	    printf("%i%c",Nsh(am,1),tolower(shell_types[am]));
	printf("]\n");
      } else {
	printf("%10i  ",(int) nbf);
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	printf("\n");
      }
    }
  } else if(stricmp(cmd,"daug")==0 || stricmp(cmd,"taug")==0) {
    // Augment basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs %s output.gbs\n",argv[0],tolower(cmd).c_str());
      return 1;
    }

    int naug;
    if(stricmp(cmd,"daug")==0)
      naug=1;
    else
      naug=2;

    std::string fileout(argv[3]);
    bas.augment(naug);
    bas.save_gaussian94(fileout);
  } else if(stricmp(cmd,"decontract")==0) {
  // Decontract basis set.

    if(argc!=4) {
      printf("\nUsage: %s input.gbs decontract output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout(argv[3]);
    bas.decontract();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"densityfit")==0) {
  // Generate density fitted set

    if(argc!=6) {
      printf("\nUsage: %s input.gbs densityfit lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.density_fitting(lval,fsam));
    dfit.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dump")==0) {
    // Dump wanted element.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dump element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dumpdec")==0) {
    // Dump wanted element in decontracted form.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dumpdec element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    bas.decontract();
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"genbas")==0) {
    // Generate basis set for xyz file

    if(argc!=5) {
      printf("\nUsage: %s input.gbs genbas system.xyz output.gbs\n",argv[0]);
      return 1;
    }

    // Load atoms from xyz file
    std::vector<atom_t> atoms=load_xyz(argv[3]);
    // Output file
    std::string fileout(argv[4]);
    // Save output
    BasisSetLibrary elbas;

    // Collect elements
    std::vector<ElementBasisSet> els=bas.get_elements();
    // Loop over atoms in system
    for(size_t iat=0;iat<atoms.size();iat++) {
      bool found=false;

      // First, check if there is a special basis for the atom.
      for(size_t iel=0;iel<els.size();iel++)
	if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && atoms[iat].num == els[iel].get_number()) {
	  // Yes, add it.
	  elbas.add_element(els[iel]);
	  found=true;
	  break;
	}

      // Otherwise, check if a general basis is already in the basis
      if(!found) {
	std::vector<ElementBasisSet> added=elbas.get_elements();
	for(size_t j=0;j<added.size();j++)
	  if(added[j].get_number()==0 && stricmp(atoms[iat].el,added[j].get_symbol())==0)
	    found=true;
      }

      // If general basis not found, add it.
      if(!found) {
	for(size_t iel=0;iel<els.size();iel++)
	  if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && els[iel].get_number()==0) {
	    // Yes, add it.
	    elbas.add_element(els[iel]);
	    found=true;
	    break;
	  }
      }

      if(!found) {
	std::ostringstream oss;
	oss << "Basis set for element " << atoms[iat].el << " does not exist in " << filein << "!\n";
	throw std::runtime_error(oss.str());
      }
    }
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"merge")==0) {
    // Merge functions with too big overlap

    if(argc!=5) {
      printf("\nUsage: %s input.gbs merge cutoff output.gbs\n",argv[0]);
      return 1;
    }

    // Cutoff value
    double cutoff=atof(argv[3]);
    bas.merge(cutoff);
    bas.save_gaussian94(argv[4]);

  } else if(stricmp(cmd,"norm")==0) {
    // Normalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs norm output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.normalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"orth")==0) {
    // Orthogonalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs orth output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.orthonormalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"overlap")==0) {
    // Primitive overlap

    if(argc!=4) {
      printf("\nUsage: %s input.gbs overlap element\n",argv[0]);
      return 1;
    }

    // Get element basis set
    ElementBasisSet elbas=bas.get_element(argv[3]);
    elbas.decontract();

    // Loop over angular momentum
    for(int am=0;am<=elbas.get_max_am();am++) {
      // Get primitives
      arma::vec exps;
      arma::mat contr;
      elbas.get_primitives(exps,contr,am);

      // Compute overlap matrix
      arma::mat S=overlap(exps,exps,am);

      // Print out overlap
      printf("*** %c shell ***\n",shell_types[am]);
      exps.t().print("Exponents");
      printf("\n");

      S.print("Overlap");
      printf("\n");
    }

  } else if(stricmp(cmd,"Porth")==0) {
    // P-orthogonalize basis

    if(argc!=6) {
      printf("\nUsage: %s input.gbs Porth cutoff Cortho output.gbs\n",argv[0]);
      return 1;
    }

    double cutoff=atof(argv[3]);
    double Cortho=atof(argv[4]);
    std::string fileout=argv[5];
    bas.P_orthogonalize(cutoff,Cortho);
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"prodset")==0) {
    // Generate product set
    
    if(argc!=6) {
      printf("\nUsage: %s input.gbs prodset lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.product_set(lval,fsam));
    dfit.save_gaussian94(fileout);
    
  } else if(stricmp(cmd,"save")==0) {
    // Save basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs save output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"savecfour")==0) {
    // Save basis in CFOUR format

    if(argc!=5) {
      printf("\nUsage: %s input.gbs savecfour name basis.cfour\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    std::string name=argv[4];
    bas.save_cfour(name,fileout);

  } else if(stricmp(cmd,"savedalton")==0) {
    // Save basis in Dalton format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savedalton output.dal\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_dalton(fileout);

  } else if(stricmp(cmd,"savemolpro")==0) {
    // Save basis in Molpro format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savemolpro output.mol\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_molpro(fileout);

  } else if(stricmp(cmd,"sort")==0) {
    // Sort basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs sort output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.sort();
    bas.save_gaussian94(fileout);
  } else {
    printf("\nInvalid command.\n");

    help();
  }

  return 0;
}
Exemple #23
0
void process_arguments( int argc, char *argv[] )
{
   int c, errflg = 0;
   int infoflag = 0;
   int size;
   int expected_args;
   int num;

#ifdef STRICTZ
   /* Initialize the STRICTZ variables. */

   strictz_report_mode = STRICTZ_DEFAULT_REPORT_MODE;

   for ( num = 0; num < STRICTZ_NUM_ERRORS; num++ )
   {
      strictz_error_count[num] = 0;
   }
#endif /* STRICTZ */

   /* Parse the options */

   monochrome = 0;
   hist_buf_size = 1024;
   bigscreen = 0;

#ifdef STRICTZ                  
#if defined OS2 || defined __MSDOS__ 
#define GETOPT_SET "gbomvzhy?l:c:k:r:t:s:" 
#elif defined TURBOC            
#define GETOPT_SET   "bmvzhy?l:c:k:r:t:s:" 
#elif defined HARD_COLORS       
#define GETOPT_SET    "mvzhy?l:c:k:r:t:s:f:b:" 
#else 
#define GETOPT_SET    "mvzhy?l:c:k:r:t:s:" 
#endif 
#else 
#if defined OS2 || defined __MSDOS__ 
#define GETOPT_SET "gbomvzhy?l:c:k:r:t:" 
#elif defined TURBOC            
#define GETOPT_SET   "bmvzhy?l:c:k:r:t:" 
#elif defined HARD_COLORS       
#define GETOPT_SET    "mvzhy?l:c:k:r:t:f:b:" 
#else 
#define GETOPT_SET    "mvzhy?l:c:k:r:t:" 
#endif 
#endif 
   while ( ( c = getopt( argc, argv, GETOPT_SET ) ) != EOF )
   {                            
      switch ( c )
      {
         case 'l':             /* lines */
            screen_rows = atoi( optarg );
            break;
         case 'c':             /* columns */
            screen_cols = atoi( optarg );
            break;
         case 'r':             /* right margin */
            right_margin = atoi( optarg );
            break;
         case 't':             /* top margin */
            top_margin = atoi( optarg );
            break;
         case 'k':             /* number of K for hist_buf_size */
            size = atoi( optarg );
            hist_buf_size = ( hist_buf_size > size ) ? hist_buf_size : size;
            if ( hist_buf_size > 16384 )
               hist_buf_size = 16384;
            break;
         case 'y':             /* Tandy */
            fTandy = 1;         
            break;              
#if defined OS2 || defined __MSDOS__ 
         case 'g':             /* Beyond Zork or other games using IBM graphics */
            fIBMGraphics = 1;   
            break;              
#endif 
         case 'v':             /* version information */

            fprintf( stdout, "\nJZIP - An Infocom Z-code Interpreter Program \n" );
            fprintf( stdout, "       %s %s\n", JZIPVER, JZIPRELDATE );
            if ( STANDALONE_FLAG )
            {
               fprintf( stdout, "       Standalone game: %s\n", argv[0] );
            }
            fprintf( stdout, "---------------------------------------------------------\n" );
            fprintf( stdout, "Author          :  %s\n", JZIPAUTHOR );
            fprintf( stdout, "Official Webpage: %s\n", JZIPURL );
            fprintf( stdout, "IF Archive      : ftp://ftp.gmd.de/if-archive/interpreters/zip/\n" );
            fprintf( stdout, "         Based on ZIP 2.0 source code by Mark Howell\n\n" );
            fprintf( stdout,
                     "Bugs:    Please report bugs and portability bugs to the maintainer." );
            fprintf( stdout, "\n\nInterpreter:\n\n" );
            fprintf( stdout, "\tThis interpreter will run all Infocom V1 to V5 and V8 games.\n" );
            fprintf( stdout,
                     "\tThis is a Z-machine standard 1.0 interpreter, including support for\n" );
            fprintf( stdout, "\tthe Quetzal portable save file format, ISO 8859-1 (Latin-1)\n" );
            fprintf( stdout,
                     "\tinternational character support, and the extended save and load opcodes.\n" );
            fprintf( stdout, "\t\n" );
            infoflag++;
            break;
#if defined (HARD_COLORS)
         case 'f':
            default_fg = atoi( optarg );
            break;
         case 'b':
            default_bg = atoi( optarg );
            break;
#endif
#if defined OS2 || defined __MSDOS__ 
         case 'm':             /* monochrome */
            iPalette = 2;       
            break;              
         case 'b':             /* black-and-white */
            iPalette = 1;       
            break;              
         case 'o':             /* color */
            iPalette = 0;       
            break;              
#else 
         case 'm':
            monochrome = 1;
            break;
#endif 
#if defined TURBOC              
         case 'b':
            bigscreen = 1;
            break;
#endif 
#ifdef STRICTZ
         case 's':             /* strictz reporting mode */
            strictz_report_mode = atoi( optarg );
            if ( strictz_report_mode < STRICTZ_REPORT_NEVER ||
                 strictz_report_mode > STRICTZ_REPORT_FATAL )
            {
               errflg++;
            }
            break;
#endif /* STRICTZ */

         case 'z':
            print_license(  );
            infoflag++;
            break;

         case 'h':
         case '?':
         default:
            errflg++;
      }
   }

   if ( infoflag )
      exit( EXIT_SUCCESS );

   if ( STANDALONE_FLAG )
      expected_args = 0;
   else
      expected_args = 1;

   /* Display usage */

   if ( errflg || optind + expected_args != argc )
   {

      if ( STANDALONE_FLAG )
         fprintf( stdout, "usage: %s [options...]\n", argv[0] ); 
      else
         fprintf( stdout, "usage: %s [options...] story-file\n", argv[0] ); 

      fprintf( stdout, "JZIP - an Infocom story file interpreter.\n" );
      fprintf( stdout, "      Version %s by %s.\n", JZIPVER, JZIPAUTHOR );
      fprintf( stdout, "      Release %s.\n", JZIPRELDATE );
      fprintf( stdout, "      Based on ZIP V2.0 source by Mark Howell\n" );
      fprintf( stdout, "      Plays types 1-5 and 8 Infocom and Inform games.\n\n" );
      fprintf( stdout, "\t-l n lines in display\n" );
      fprintf( stdout, "\t-c n columns in display\n" );
      fprintf( stdout, "\t-r n text right margin (default = %d)\n", DEFAULT_RIGHT_MARGIN );
      fprintf( stdout, "\t-t n text top margin (default = %d)\n", DEFAULT_TOP_MARGIN );
      fprintf( stdout, "\t-k n set the size of the command history buffer to n bytes\n" );
      fprintf( stdout, "\t     (Default is 1024 bytes.  Maximum is 16384 bytes.)\n" );
      fprintf( stdout, "\t-y   turn on the legendary \"Tandy\" bit\n" ); 
      fprintf( stdout, "\t-v   display version information\n" );
      fprintf( stdout, "\t-h   display this usage information\n" );

#if defined (HARD_COLORS)
      fprintf( stdout, "\t-f n foreground color\n" );
      fprintf( stdout, "\t-b n background color (-1 to ignore bg color (try it on an Eterm))\n" );
      fprintf( stdout, "\t     Black=0 Red=1 Green=2 Yellow=3 Blue=4 Magenta=5 Cyan=6 White=7\n" );
#endif
      fprintf( stdout, "\t-m   force monochrome mode\n" ); 
#if defined __MSDOS__ || defined OS2 
      fprintf( stdout, "\t-b   force black-and-white mode\n" ); 
      fprintf( stdout, "\t-o   force color mode\n" ); 
      fprintf( stdout, "\t-g   use \"Beyond Zork\" graphics, rather than standard international\n" ); 
#elif defined TURBOC            
      fprintf( stdout, "\t-b   run in 43/50 line EGA/VGA mode\n" ); 
#endif 

#ifdef STRICTZ
      fprintf( stdout, "\t-s n stricter error checking (default = %d) (0: none; 1: report 1st\n",
               STRICTZ_DEFAULT_REPORT_MODE );
      fprintf( stdout, "\t     error; 2: report all errors; 3: exit after any error)\n" );
#endif /* STRICTZ */

      fprintf( stdout, "\t-z   display license information.\n" );
      exit( EXIT_FAILURE );
   }

   /* Open the story file */

   if ( !STANDALONE_FLAG )      /* mol 951115 */
      open_story( argv[optind] );
   else
   {
      /* standalone, ie. the .exe file _is_ the story file. */
      if ( argv[0][0] == 0 )
      {
         /* some OS's (ie DOS prior to v.3.0) don't supply the path to */
         /* the .exe file in argv[0]; in that case, we give up. (mol) */
         fatal( "process_arguments(): Sorry, this program will not run on this platform." );
      }
      open_story( argv[0] );
   }

}                               /* process_arguments */
Exemple #24
0
int main(int argc, char **argv) {
#ifdef _OPENMP
  printf("ERKALE - population from Hel, OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - population from Hel, serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=2) {
    printf("Usage: %s runfile\n",argv[0]);
    return 1;
  }

  // Parse settings
  Settings set;
  set.add_string("LoadChk","Checkpoint file to load density from","erkale.chk");
  set.add_bool("Bader", "Run Bader analysis?", false);
  set.add_bool("Becke", "Run Becke analysis?", false);
  set.add_bool("Mulliken", "Run Mulliken analysis?", false);
  set.add_bool("Lowdin", "Run Löwdin analysis?", false);
  set.add_bool("IAO", "Run Intrinsic Atomic Orbital analysis?", false);
  set.add_string("IAOBasis", "Minimal basis set for IAO analysis", "MINAO.gbs");
  set.add_bool("Hirshfeld", "Run Hirshfeld analysis?", false);
  set.add_string("HirshfeldMethod", "Method to use for Hirshfeld(-I) analysis", "HF");
  set.add_bool("IterativeHirshfeld", "Run iterative Hirshfeld analysis?", false);
  set.add_bool("Stockholder", "Run Stockholder analysis?", false);
  set.add_bool("Voronoi", "Run Voronoi analysis?", false);
  set.add_double("Tol", "Grid tolerance to use for the charges", 1e-5);
  set.add_bool("OrbThr", "Compute orbital density thresholds", false);
  set.add_bool("SICThr", "Compute SIC orbital density thresholds", false);
  set.add_bool("DensThr", "Compute total density thresholds", false);
  set.add_double("OrbThrVal", "Which density threshold to calculate", 0.85);
  set.add_double("OrbThrGrid", "Accuracy of orbital density threshold integration grid", 1e-3);

  // Parse settings
  set.parse(argv[1]);

  // Print settings
  set.print();

  // Initialize libint
  init_libint_base();

  // Load checkpoint
  Checkpoint chkpt(set.get_string("LoadChk"),false);

  // Load basis set
  BasisSet basis;
  chkpt.read(basis);

  // Restricted calculation?
  bool restr;
  chkpt.read("Restricted",restr);

  arma::mat P, Pa, Pb;
  chkpt.read("P",P);
  if(!restr) {
    chkpt.read("Pa",Pa);
    chkpt.read("Pb",Pb);
  }

  double tol=set.get_double("Tol");

  if(set.get_bool("Bader")) {
    if(restr)
      bader_analysis(basis,P,tol);
    else
      bader_analysis(basis,Pa,Pb,tol);
  }

  if(set.get_bool("Becke")) {
    if(restr)
      becke_analysis(basis,P,tol);
    else
      becke_analysis(basis,Pa,Pb,tol);
  }

  std::string hmet=set.get_string("HirshfeldMethod");

  if(set.get_bool("Hirshfeld")) {
    if(restr)
      hirshfeld_analysis(basis,P,hmet,tol);
    else
      hirshfeld_analysis(basis,Pa,Pb,hmet,tol);
  }

  if(set.get_bool("IterativeHirshfeld")) {
    if(restr)
      iterative_hirshfeld_analysis(basis,P,hmet,tol);
    else
      iterative_hirshfeld_analysis(basis,Pa,Pb,hmet,tol);
  }

  if(set.get_bool("IAO")) {
    std::string minbas=set.get_string("IAOBasis");

    if(restr) {
      // Get amount of occupied orbitals
      int Nela;
      chkpt.read("Nel-a",Nela);

      // Get orbital coefficients
      arma::mat C;
      chkpt.read("C",C);

      // Do analysis
      IAO_analysis(basis,C.cols(0,Nela-1),P,minbas);
    } else {
      // Get amount of occupied orbitals
      int Nela, Nelb;
      chkpt.read("Nel-a",Nela);
      chkpt.read("Nel-b",Nelb);

      // Get orbital coefficients
      arma::mat Ca, Cb;
      chkpt.read("Ca",Ca);
      chkpt.read("Cb",Cb);

      // Do analysis
      IAO_analysis(basis,Ca.cols(0,Nela-1),Cb.cols(0,Nelb-1),Pa,Pb,minbas);
    }
  }

  if(set.get_bool("Lowdin")) {
    if(restr)
      lowdin_analysis(basis,P);
    else
      lowdin_analysis(basis,Pa,Pb);
  }

  if(set.get_bool("Mulliken")) {
    if(restr)
      mulliken_analysis(basis,P);
    else
      mulliken_analysis(basis,Pa,Pb);
  }

  if(set.get_bool("Stockholder")) {
    if(restr)
      stockholder_analysis(basis,P,tol);
    else
      stockholder_analysis(basis,Pa,Pb,tol);
  }

  if(set.get_bool("Voronoi")) {
    if(restr)
      voronoi_analysis(basis,P,tol);
    else
      voronoi_analysis(basis,Pa,Pb,tol);
  }

  if(set.get_bool("OrbThr")) {
    // Calculate orbital density thresholds

    // Integration grid
    DFTGrid intgrid(&basis,true);
    intgrid.construct_becke(set.get_double("OrbThrGrid"));

    // Threshold is
    double thr=set.get_double("OrbThrVal");

    if(restr) {
      // Get amount of occupied orbitals
      int Nela;
      chkpt.read("Nel-a",Nela);

      // Get orbital coefficients
      arma::mat C;
      chkpt.read("C",C);

      printf("\n%4s %9s %8s\n","orb","thr","t (s)");
      for(int io=0;io<Nela;io++) {
	Timer t;

	// Orbital density matrix is
	arma::mat Po=C.col(io)*arma::trans(C.col(io));
	double val=compute_threshold(intgrid,Po,thr,false);

	// Print out orbital threshold
	printf("%4i %8.3e %8.3f\n", io+1, val, t.get());
	fflush(stdout);
      }

    } else {
      // Get amount of occupied orbitals
      int Nela, Nelb;
      chkpt.read("Nel-a",Nela);
      chkpt.read("Nel-b",Nelb);

      // Get orbital coefficients
      arma::mat Ca, Cb;
      chkpt.read("Ca",Ca);
      chkpt.read("Cb",Cb);

      printf("\n%4s %9s %9s %8s\n","orb","thr-a","thr-b","t (s)");
      for(int io=0;io<Nela;io++) {
	Timer t;

	// Orbital density matrix is
	arma::mat Po=Ca.col(io)*arma::trans(Ca.col(io));
	double vala=compute_threshold(intgrid,Po,thr,false);

	if(io<Nelb) {
	  Po=Cb.col(io)*arma::trans(Cb.col(io));
	  double valb=compute_threshold(intgrid,Po,thr,false);

	  // Print out orbital threshold
	  printf("%4i %8.3e %8.3e %8.3f\n", io+1, vala, valb, t.get());
	  fflush(stdout);
	} else {
	  printf("%4i %8.3e %9s %8.3f\n", io+1, vala, "****", t.get());
	  fflush(stdout);
	}
      }

    }
  }

  if(set.get_bool("SICThr")) {
    // Calculate SIC orbital density thresholds

    // Integration grid
    DFTGrid intgrid(&basis,true);
    intgrid.construct_becke(set.get_double("OrbThrGrid"));

    // Threshold is
    double thr=set.get_double("OrbThrVal");

    if(restr) {
      // Get orbital coefficients
      arma::cx_mat CW;
      chkpt.cread("CW",CW);

      printf("\n%4s %9s %8s\n","orb","thr","t (s)");
      for(size_t io=0;io<CW.n_cols;io++) {
	Timer t;

	// Orbital density matrix is
	arma::mat Po=arma::real(CW.col(io)*arma::trans(CW.col(io)));
	double val=compute_threshold(intgrid,Po,thr,false);

	// Print out orbital threshold
	printf("%4i %8.3e %8.3f\n", (int) io+1, val, t.get());
	fflush(stdout);
      }

    } else {
      // Get orbital coefficients
      arma::cx_mat CWa, CWb;
      chkpt.cread("CWa",CWa);
      chkpt.cread("CWb",CWb);

      printf("\n%4s %9s %9s %8s\n","orb","thr-a","thr-b","t (s)");
      for(size_t io=0;io<CWa.n_cols;io++) {
	Timer t;

	// Orbital density matrix is
	arma::mat Po=arma::real(CWa.col(io)*arma::trans(CWa.col(io)));
	double vala=compute_threshold(intgrid,Po,thr,false);

	if(io<CWb.n_cols) {
	  Po=arma::real(CWb.col(io)*arma::trans(CWb.col(io)));
	  double valb=compute_threshold(intgrid,Po,thr,false);

	  // Print out orbital threshold
	  printf("%4i %8.3e %8.3e %8.3f\n", (int) io+1, vala, valb, t.get());
	  fflush(stdout);
	} else {
	  printf("%4i %8.3e %9s %8.3f\n", (int) io+1, vala, "****", t.get());
	  fflush(stdout);
	}
      }
    }
  }

  if(set.get_bool("DensThr")) {
    // Calculate SIC orbital density thresholds

    // Integration grid
    DFTGrid intgrid(&basis,true);
    intgrid.construct_becke(set.get_double("OrbThrGrid"));

    // Threshold is
    double thr=set.get_double("OrbThrVal");

    Timer t;

    printf("\n%10s %9s %8s\n","density","thr","t (s)");
    if(!restr) {
      double aval=compute_threshold(intgrid,Pa,thr*arma::trace(P*basis.overlap()),true);
      printf("%10s %8.3e %8.3f\n", "alpha", aval, t.get());
      fflush(stdout);
      t.set();

      double bval=compute_threshold(intgrid,Pb,thr*arma::trace(P*basis.overlap()),true);
      printf("%10s %8.3e %8.3f\n", "beta", bval, t.get());
      fflush(stdout);
      t.set();
    }

    double val=compute_threshold(intgrid,P,thr*arma::trace(P*basis.overlap()),true);
    printf("%10s %8.3e %8.3f\n", "total", val, t.get());
    fflush(stdout);
  }


  return 0;
}
Exemple #25
0
int main( int argc, char ** argv ) {

	char * input_file;
	FILE * fp;
	node * root;
	int input, range2;
	char instruction;
	char license_part;

	root = NULL;
	verbose_output = false;
/*
	if (argc > 1) {
		order = atoi(argv[1]);
		if (order < MIN_ORDER || order > MAX_ORDER) {
			fprintf(stderr, "Invalid order: %d .\n\n", order);
			usage_3();
			exit(EXIT_FAILURE);
		}
	}

	license_notice();
	usage_1();
	usage_2();
*/
	if (argc > 2) {
		switch (argc[1]) {
			case 's';
				
		}
				
		/*input_file = argv[2];
		fp = fopen(input_file, "r");
		if (fp == NULL) {
			perror("Failure to open input file.");
			exit(EXIT_FAILURE);
		}
		while (!feof(fp)) {
			fscanf(fp, "%d\n", &input);
			root = insert(root, input, input);
		}
		fclose(fp);
		print_tree(root);*/
	}

	printf("> ");
	while (scanf("%c", &instruction) != EOF) {
		switch (instruction) {
		case 'd':
			scanf("%d", &input);
			root = delete_key(root, input);
			print_tree(root);
			break;
		case 'i':
			scanf("%d", &input);
			root = insert(root, input, input);
			print_tree(root);
			break;
		case 'f':
		case 'p':
			scanf("%d", &input);
			find_and_print(root, input, instruction == 'p');
			break;
		case 'r':
			scanf("%d %d", &input, &range2);
			if (input > range2) {
				int tmp = range2;
				range2 = input;
				input = tmp;
			}
			find_and_print_range(root, input, range2, instruction == 'p');
			break;
		case 'l':
			print_leaves(root);
			break;
		case 'q':
			while (getchar() != (int)'\n');
			return EXIT_SUCCESS;
		case 's':
			if (scanf("how %c", &license_part) == 0) {
				usage_2();
				break;
			}
			switch(license_part) {
			case 'w':
				print_license(LICENSE_WARRANTEE);
				break;
			case 'c':
				print_license(LICENSE_CONDITIONS);
				break;
			default:
				usage_2();
				break;
			}
			break;
		case 't':
			print_tree(root);
			break;
		case 'v':
			verbose_output = !verbose_output;
			break;
		case 'x':
			if (root)
				root = destroy_tree(root);
			print_tree(root);
			break;
		default:
			usage_2();
			break;
		}
		while (getchar() != (int)'\n');
		printf("> ");
	}
	printf("\n");

	return EXIT_SUCCESS;
}
Exemple #26
0
int main(int argc, char **argv) {

#ifdef _OPENMP
  printf("ERKALE - Casida from Hel, OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - Casida from Hel, serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=1 && argc!=2) {
    printf("Usage: $ %s (runfile)\n",argv[0]);
    return 0;
  }

  // Initialize libint
  init_libint_base();

  Timer t;
  t.print_time();

  // Parse settings
  Settings set;
  set.add_string("FittingBasis","Basis set to use for density fitting (Auto for automatic)","Auto");
  set.add_string("CasidaX","Exchange functional for Casida","lda_x");
  set.add_string("CasidaC","Correlation functional for Casida","lda_c_vwn");
  set.add_bool("CasidaPol","Perform polarized Casida calculation (when using restricted wf)",false);
  set.add_int("CasidaCoupling","Coupling mode: 0 for IPA, 1 for RPA and 2 for TDLDA",2);
  set.add_double("CasidaTol","Tolerance for Casida grid",1e-4);
  set.add_string("CasidaStates","States to include in Casida calculation, eg ""1,3:7,10,13"" ","");
  set.add_string("CasidaQval","Values of Q to compute spectrum for","");
  set.add_string("LoadChk","Checkpoint to load","erkale.chk");

  if(argc==2)
    set.parse(std::string(argv[1]));
  else
    printf("\nDefault settings used.");

  // Print settings
  set.print();

  // Get functional strings
  int xfunc=find_func(set.get_string("CasidaX"));
  int cfunc=find_func(set.get_string("CasidaC"));

  if(is_correlation(xfunc))
    throw std::runtime_error("Refusing to use a correlation functional as exchange.\n");
  if(is_kinetic(xfunc))
    throw std::runtime_error("Refusing to use a kinetic energy functional as exchange.\n");
  if(is_exchange(cfunc))
    throw std::runtime_error("Refusing to use an exchange functional as correlation.\n");
  if(is_kinetic(cfunc))
    throw std::runtime_error("Refusing to use a kinetic energy functional as correlation.\n");
  set.add_int("CasidaXfunc","Internal variable",xfunc);
  set.add_int("CasidaCfunc","Internal variable",cfunc);

  // Print information about used functionals
  print_info(xfunc,cfunc);

  // Get values of q to compute spectrum for
  std::vector<double> qvals=parse_range_double(set.get_string("CasidaQval"));

  // Load checkpoint
  std::string fchk=set.get_string("LoadChk");
  Checkpoint chkpt(fchk,false);

  // Check that calculation was converged
  bool conv;
  chkpt.read("Converged",conv);
  if(!conv)
    throw std::runtime_error("Refusing to run Casida calculation based on a non-converged SCF density!\n");

  // Parse input states
  std::string states=set.get_string("CasidaStates");
  std::string newstates=parse_states(chkpt,states);
  set.set_string("CasidaStates",newstates);
  if(states.compare(newstates)!=0)
    printf("CasidaStates has been parsed to \"%s\".\n",newstates.c_str());

  // Load basis set
  BasisSet basis;
  chkpt.read(basis);

  Casida cas;
  bool restr;
  chkpt.read("Restricted",restr);

  if(restr) {
    // Load energy and orbitals
    arma::mat C, P;
    arma::vec E;
    std::vector<double> occs;

    chkpt.read("P",P);
    chkpt.read("C",C);
    chkpt.read("E",E);
    chkpt.read("occs",occs);

    // Check orthonormality
    check_orth(C,basis.overlap(),false);

    if(set.get_bool("CasidaPol")) {
      // Half occupancy (1.0 instead of 2.0)
      std::vector<double> hocc(occs);
      for(size_t i=0;i<hocc.size();i++)
	hocc[i]/=2.0;
      cas=Casida(set,basis,E,E,C,C,P/2.0,P/2.0,hocc,hocc);
    }
    else
      cas=Casida(set,basis,E,C,P,occs);

  } else {
    arma::mat Ca, Cb;
    arma::mat Pa, Pb;
    arma::vec Ea, Eb;
    std::vector<double> occa, occb;

    chkpt.read("Pa",Pa);
    chkpt.read("Pb",Pb);
    chkpt.read("Ca",Ca);
    chkpt.read("Cb",Cb);
    chkpt.read("Ea",Ea);
    chkpt.read("Eb",Eb);
    chkpt.read("occa",occa);
    chkpt.read("occb",occb);

    // Check orthonormality
    check_orth(Ca,basis.overlap(),false);
    check_orth(Cb,basis.overlap(),false);

    cas=Casida(set,basis,Ea,Eb,Ca,Cb,Pa,Pb,occa,occb);
  }

  // Dipole transition
  print_spectrum("casida.dat",cas.dipole_transition(basis));
  // Q dependent stuff
  for(size_t iq=0;iq<qvals.size();iq++) {
    // File to save output
    char fname[80];
    sprintf(fname,"casida-%.2f.dat",qvals[iq]);

    print_spectrum(fname,cas.transition(basis,qvals[iq]));
  }

  printf("\nRunning program took %s.\n",t.elapsed().c_str());
  t.print_time();

  return 0;
}