示例#1
0
文件: ui.c 项目: jens-na/abook-call
void
ui_open_datafile()
{
    char *filename;

    filename = ask_filename(_("File to open: "));

    if(!filename || ! *filename) {
        free(filename);
        refresh_screen();
        return;
    }

    if(opt_get_bool(BOOL_AUTOSAVE))
        save_database();
    else if(statusline_ask_boolean(_("Save current database"), FALSE))
        save_database();

    close_database();

    load_database(filename);

    if(list_is_empty()) {
        statusline_msg(_("Sorry, the specified file appears not to be a valid abook addressbook"));
        load_database(datafile);
    } else {
        free(datafile);
        datafile = xstrdup(filename);
    }

    refresh_screen();
    free(filename);

    alternative_datafile = TRUE;
}
示例#2
0
static int
try_db_name(void)
{int i,n;struct database_handle**db=get_database_list(&n);
 if(*db_name)for(i=0;i<n;i++)if(!StrCompare(db[i]->name,db_name))
  if(!load_database(i))return 0;
 *db_name=0;if(n>0)return load_database(0);
 FrmAlert(No_Dictionary_Alert_id);return!0;
}enum aux_flags_bits{list_mode_bit=0};
示例#3
0
bool Schema::load_databases(TiXmlElement *schema_node, SchemaServer &server)
{
    if(NULL == schema_node)
    {
        Log::get_instance().log().error("schema element is NULL."); 
        return false;
    }
    
    Log::get_instance().log().info("find Databases."); 
    TiXmlElement *databases_element = schema_node->FirstChildElement("Databases");
    if(NULL == databases_element)
    {
        Log::get_instance().log().error("databases element is NULL."); 
        return false;
    }
    
    Log::get_instance().log().info("find Database."); 
    TiXmlElement *database_element = databases_element->FirstChildElement("Database");   
    while(NULL != database_element)
    {       
        SchemaDatabase database;                
        if(false == load_database(database_element, database))
        {
             Log::get_instance().log().error("load databases element failure."); 
             return false;
        }     
        
        Log::get_instance().log().info("load database name %s successful.", database.name.c_str()); 
        server.databases.insert(std::pair<string, SchemaDatabase>(database.name, database));     
        
        database_element = database_element->NextSiblingElement("Database");
    }
    
    return true;
}
示例#4
0
R2RDatabase* load_data()
{
        R2RDatabase *database = g_malloc(sizeof(R2RDatabase));

        load_info_file(database);
        load_database(database);

        return database;
}
示例#5
0
int main(int argc, char **argv)
{
    init_args(argc, argv);
    load_params();
    init_graphics();

    /* not used */
    load_database();
    draw();
    set_texture_coord();
    save_database();
    return 0;
}
示例#6
0
bool DBBrowserDB::reload( const QString & filename, int * lineErr)
{
    /*to avoid a nested transaction error*/
    sqlite3_exec(_db,"COMMIT;", NULL,NULL,NULL);
    FILE * cfile = fopen((const char *) filename, (const char *) "r");
    load_database(_db, cfile, lineErr);
    fclose(cfile);
    setDirty(false);
    if ((*lineErr)!=0)
    {
        return false;
    }
    return true;
}
示例#7
0
int main(int argc, char **argv)
{
  char option;
  int op;
  RBTree *tree = NULL;

  while ( 1 )
  {
    show_menu(tree);

    printf("Indiqui la opcio: ");
    scanf("%c", &option);
    flush();
    
    printf("option: [%c]\n", option);

    switch ( option )
    {
      case '1':
        clean_up(tree);
        tree = import_database();
        break;
      case '2':
        save_database(tree);
        break;
      case '3':
        clean_up(tree);
        tree = malloc(sizeof(RBTree));
        op = load_database(tree);
        if ( op == PRS_FILE_NOT_FOUND ) {
          free(tree);
          tree = NULL;
        }
        break;
      case '4':
        generate_statistics(tree);
        break;
      case '5':
        clean_up(tree);
        exit(0);
        break;
      default:
        printf("\nOption not recognised.\n");
        break;
    }
  }

  return 0;
}
static gboolean
refine_rating (GsPlugin *plugin, GsApp *app, GCancellable *cancellable, GError **error)
{
	GsPluginData *priv = gs_plugin_get_data (plugin);
	GPtrArray *sources;
	guint i;

	/* Load database once */
	if (g_once_init_enter (&priv->db_loaded)) {
		gboolean ret = load_database (plugin, cancellable, error);
		g_once_init_leave (&priv->db_loaded, TRUE);
		if (!ret)
			return FALSE;
	}

	/* Skip if already has a rating */
	if (gs_app_get_rating (app) != -1)
		return TRUE;

	sources = gs_app_get_sources (app);
	for (i = 0; i < sources->len; i++) {
		const gchar *package_name;
		gint rating;
		gint review_ratings[6];
		gboolean ret;

		/* Otherwise use the statistics */
		package_name = g_ptr_array_index (sources, i);
		ret = get_review_stats (plugin, package_name, &rating, review_ratings, error);
		if (!ret)
			return FALSE;
		if (rating != -1) {
			g_autoptr(GArray) ratings = NULL;

			g_debug ("ubuntu-reviews setting rating on %s to %i%%",
				 package_name, rating);
			gs_app_set_rating (app, rating);
			ratings = g_array_sized_new (FALSE, FALSE, sizeof (gint), 6);
			g_array_append_vals (ratings, review_ratings, 6);
			gs_app_set_review_ratings (app, ratings);
			if (rating > 80)
				gs_app_add_kudo (app, GS_APP_KUDO_POPULAR);
		}
	}

	return TRUE;
}
示例#9
0
文件: ui.c 项目: jens-na/abook-call
void
ui_read_database()
{
    char *msg;

    if(!list_is_empty()) {
        msg = strdup_printf(_("Your current data will be lost - "
                              "Press '%c' to continue"),
                            *(S_("keybinding for yes|y")));
        if(!statusline_ask_boolean(msg, FALSE)) {
            free(msg);
            return;
        }
        free(msg);
    }

    load_database(datafile);
    refresh_list();
}
示例#10
0
int main(int argc, char**argv)
{
  ProtobufC_RPC_Server *server;
  ProtobufC_RPC_AddressType address_type=0;
  const char *name = NULL;
  unsigned i;

  for (i = 1; i < (unsigned) argc; i++)
    {
      if (starts_with (argv[i], "--port="))
        {
          address_type = PROTOBUF_C_RPC_ADDRESS_TCP;
          name = strchr (argv[i], '=') + 1;
        }
      else if (starts_with (argv[i], "--unix="))
        {
          address_type = PROTOBUF_C_RPC_ADDRESS_LOCAL;
          name = strchr (argv[i], '=') + 1;
        }
      else if (starts_with (argv[i], "--database="))
        {
          load_database (strchr (argv[i], '=') + 1);
        }
      else
        usage ();
    }

  if (database_size == 0)
    die ("missing --database=FILE (try --database=example.database)");
  if (name == NULL)
    die ("missing --port=NUM or --unix=PATH");
  
  signal (SIGPIPE, SIG_IGN);

  server = protobuf_c_rpc_server_new (address_type, name, (ProtobufCService *) &the_dir_lookup_service, NULL);

  for (;;)
    protobuf_c_rpc_dispatch_run (protobuf_c_rpc_dispatch_default ());
  return 0;
}
示例#11
0
void init_graphics ()
{
    int   fake_argc = 1 ;
    char *fake_argv[3] ;
    fake_argv[0] = "TexMapper" ;
    fake_argv[1] = "Texture Auto Mapper" ;
    fake_argv[2] = NULL ;

    /*
      Initialise GLUT
    */

    glutInitWindowPosition(0, 0);
    glutInitWindowSize(ImgSize, ImgSize);
    glutInit(&fake_argc, fake_argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow(fake_argv[1]);
 
    /* Callbacks */
    glutDisplayFunc(Display);
    
    /*
      Initialise SSG
    */
    ssgInit();

    /*
      Some basic OpenGL setup
    */
    glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();

    load_database();

    glutMainLoop();
}
// global variables used: clouds_dir, database_dir
int 
vtree_user::start()
{
	//if init build and save the database
	if (command.compare("/init") == 0)
	{
		build_database(clouds_dir);
		save_database(database_dir);
	}
	//load previously built database and perform recognition
	else if (command.compare("/load") == 0)
		load_database(database_dir);

	//only extract features and save them in a specified images_directory
	else if (command.compare("/features_only") == 0)
	{
		std::vector<FeatureVector> clouds;
		trace_directory(clouds_dir.c_str(), "", clouds, true);	// TODO: What does this do?
	}
	else
		return 1;
	
	return 0;
}
示例#13
0
int main(void)
{
  system(CLEAR_SC);

  /* Creation/Load of the database */

  database = open ("database", O_RDWR | O_CREAT,S_IRWXU);

  if(database==ERROR)
    return ERROR;

  /* Initialize the flock structure. */
  lock.l_type = F_WRLCK; /* A write lock also blocks readers */
  lock.l_start = 0;
  lock.l_len = 0;
  lock.l_whence = SEEK_SET;

  /* Lock the database */

  printf("Accesing the database\n");

  if(fcntl (database, F_SETLKW, &lock)==ERROR)
    return ERROR;

  printf("Access granted\n");

  /* Assign handler for SIGINT (AKA Ctl+C) */
  struct sigaction sa;
  memset (&sa, 0, sizeof (sa));

  sa.sa_handler=&sigint_handler;

  if(sigaction(SIGINT,&sa,NULL)==-1)
    return SIGNAL_ERROR;

  /*Binary semaphore creation - MUTEX*/

  semaphore=binary_semaphore_allocation(IPC_PRIVATE,IPC_CREAT);
  binary_semaphore_initialize(semaphore);

  /*Shared Memory Allocation*/

  users_shared_memory = shmget(IPC_PRIVATE,sizeof(data_person)*MAX_USERS,IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR );
  newid_shared_memory = shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR );

  /* Shared Memory Attach */
  int * newid = (int *) shmat(newid_shared_memory,0,0);

  data_person * users = (data_person *) shmat(users_shared_memory,0,0);

  /* Shared Memory initialization */
  *newid=0;

  /* Load data from the database */
  load_database(users,newid);

  /* Shared Memory Detach */
  shmdt(newid);
  shmdt(users);

  /*Client-Server comunication*/
  if(initialize()==ERROR)
  {
    printf("The port 49500 was not available\n");
    sigint_handler(0);
  }

  start_connection(&application_request,MAX_QUEUE);

  return 0;
}
示例#14
0
int
main (int argc, char *argv[])
{
  cron_db database;
  char *config_file;		/*Name of our configuration file; NULL if none */
  struct sigaction my_sigaction;

  /* We need to put Program_Name in its own storage because later we will
   * modify argv[0] in an attempt to change the process name.
   */
  ProcessName = argv[0];
  ProgramName = strdup (argv[0]);

#if HAVE_SETLINEBUF
  setlinebuf (stdout);
  setlinebuf (stderr);
#endif /*HAVE_SETLINEBUF */

  parse_args (argc, argv, &pass_environment, &config_file);

  read_config (config_file, &allow_only_root, &log_syslog, &allow_file,
	       &deny_file, &crondir, &spool_dir, &log_file, &syscrontab,
	       &lastrun_file, &pidfile, &mailprog, &mailargs);

#ifdef USE_SIGCHLD
  memset (&my_sigaction, 0, sizeof (my_sigaction));
  my_sigaction.sa_handler = sigchld_handler;
  my_sigaction.sa_flags |= SA_NOCLDSTOP | SA_NODEFER;
  if (sigaction (SIGCHLD, &my_sigaction, NULL))
    perror ("sigaction");
#else
  (void) signal (SIGCHLD, SIG_IGN);
#endif

  memset (&my_sigaction, 0, sizeof (my_sigaction));
  my_sigaction.sa_handler = sigterm_handler;
  if (sigaction (SIGTERM, &my_sigaction, NULL))
    perror ("sigaction");

  memset (&my_sigaction, 0, sizeof (my_sigaction));
  my_sigaction.sa_handler = sighup_handler;
  if (sigaction (SIGHUP, &my_sigaction, NULL))
    perror ("sigaction");

  acquire_daemonlock (0);
  set_cron_uid ();
  set_cron_cwd ();

#if HAVE_SETENV
  if (!pass_environment)
    setenv ("PATH", _PATH_DEFPATH, 1);
#endif

  /* if there are no debug flags turned on, fork as a daemon should. */

#if DEBUGGING
  if (DebugFlags)
    {
#else
  if (0)
    {
#endif
      (void) fprintf (stderr, "[%d] cron started\n", getpid ());
    }
  else
    {
      switch (fork ())
	{
	case -1:
	  log_it ("CRON", getpid (), "DEATH", "can't fork");
	  exit (0);
	  break;
	case 0:
	  /* child process */
	  log_it ("CRON", getpid (), "STARTUP", "fork ok");
	  (void) setsid ();
	  break;
	default:
	  /* parent process should just die */
	  _exit (0);
	}
    }

  acquire_daemonlock (0);

  /* initialize waiting for busy disk */
  init_diskload ();

  database.head = NULL;
  database.tail = NULL;
  database.mtime = (time_t) 0;

  Debug (DMISC, ("about to load database"));
  load_database (&database);
  Debug (DMISC, ("about to build catch up list"));
  build_cu_list (&database, &CatchUpList);
  Debug (DMISC, ("about to run reboot jobs"));
  run_reboot_jobs (&database);

  while (TRUE)
    {
      cron_sync (); 
# if DEBUGGING
      if (!(DebugFlags & DTEST))
# endif	 /*DEBUGGING*/
	  cron_sleep ();

      load_database (&database);

      /* first catch up any jobs that are on the CatchUpList */
      if (CatchUpList && (!jhead))
	CatchUpList = run_cu_list (CatchUpList);
      /* then run the regular jobs for this minute */
      cron_tick (&database);
    }
}


static void
run_reboot_jobs (cron_db * db)
{
  register user *u;
  register entry *e;

  for (u = db->head; u != NULL; u = u->next)
    {
      for (e = u->crontab; e != NULL; e = e->next)
	{
	  if (e->flags & WHEN_REBOOT)
	    {
	      job_add (e, u);
	    }
	}
    }
  (void) job_runqueue ();
}


static void
cron_tick (cron_db * db)
{
  register struct tm *tm = localtime (&TargetTime);
  register int minute, hour, dom, month, dow;
  register user *u;
  register entry *e;

  /* make 0-based values out of these so we can use them as indicies
   */
  minute = tm->tm_min - FIRST_MINUTE;
  hour = tm->tm_hour - FIRST_HOUR;
  dom = tm->tm_mday - FIRST_DOM;
  month = tm->tm_mon + 1 /* 0..11 -> 1..12 */  - FIRST_MONTH;
  dow = tm->tm_wday - FIRST_DOW;

  Debug (DSCH, ("[%d] tick(%d,%d,%d,%d,%d)\n",
		getpid (), minute, hour, dom, month, dow));
  /* the dom/dow situation is odd.  '* * 1,15 * Sun' will run on the
   * first and fifteenth AND every Sunday;  '* * * * Sun' will run *only*
   * on Sundays;  '* * 1,15 * *' will run *only* the 1st and 15th.  this
   * is why we keep 'e->dow_star' and 'e->dom_star'.  yes, it's bizarre.
   * like many bizarre things, it's the standard.
   */
  for (u = db->head; u != NULL; u = u->next)
    {
      for (e = u->crontab; e != NULL; e = e->next)
	{
	  Debug (DSCH | DEXT, ("user [%s:%d:%d:...] cmd=\"%s\"\n",
			       env_get ("LOGNAME", e->envp),
			       e->uid, e->gid, e->cmd));
	  if (bit_test (e->minute, minute)
	      && bit_test (e->hour, hour)
	      && bit_test (e->month, month)
	      && (((e->flags & DOM_STAR) || (e->flags & DOW_STAR))
		  ? (bit_test (e->dow, dow) && bit_test (e->dom, dom))
		  : (bit_test (e->dow, dow) || bit_test (e->dom, dom))))
	    {
	      job_add (e, u);
	    }
	}
    }
}


/* the task here is to figure out how long it's going to be until :00 of the
 * following minute and initialize TargetTime to this value.  TargetTime
 * will subsequently slide 60 seconds at a time, with correction applied
 * implicitly in cron_sleep().  it would be nice to let cron execute in
 * the "current minute" before going to sleep, but by restarting cron you
 * could then get it to execute a given minute's jobs more than once.
 * instead we have the chance of missing a minute's jobs completely, but
 * that's something sysadmin's know to expect what with crashing computers..
 * 
 * Patch from <*****@*****.**>:
 *   Do cron_sync() before each cron_sleep(), to handle changes to the system
 *   time.
 */
static void
cron_sync (void)
{
  register struct tm *tm;

  TargetTime = time ((time_t *) 0);
  tm = localtime (&TargetTime);
  TargetTime += (60 - tm->tm_sec);
}


static void
cron_sleep (void)
{
  register int seconds_to_wait;

  do
    {
      seconds_to_wait = (int) (TargetTime - time ((time_t *) 0));
      Debug (DSCH, ("[%d] TargetTime=%ld, sec-to-wait=%d\n",
		    getpid (), TargetTime, seconds_to_wait));
      /* if we intend to sleep, this means that it's finally
       * time to empty the job queue (execute it).
       *
       * if we run any jobs, we'll probably screw up our timing,
       * so go recompute.
       *
       * note that we depend here on the left-to-right nature
       * of &&, and the short-circuiting.
       */
    }
  while (seconds_to_wait > 0 && job_runqueue ());

  while (seconds_to_wait > 0)
    {
      Debug (DSCH, ("[%d] sleeping for %d seconds\n",
		    getpid (), seconds_to_wait));
      seconds_to_wait = (int) sleep ((unsigned int) seconds_to_wait);
    }
}


#ifdef USE_SIGCHLD
static RETSIGTYPE
sigchld_handler (int x)
{
  WAIT_T waiter;
  pid_t pid;

  for (;;)
    {
#if 1
      pid = waitpid (-1, &waiter, WNOHANG);
#else
      pid = wait3 (&waiter, WNOHANG, (struct rusage *) 0);
#endif
      switch (pid)
	{
	case -1:
	  Debug (DPROC, ("[%d] sigchld...no children\n", getpid ()));
	  return;
	case 0:
	  Debug (DPROC, ("[%d] sigchld...no dead kids\n", getpid ()));
	  return;
	default:
	  Debug (DPROC,
		 ("[%d] sigchld...pid #%d died, stat=%d\n",
		  getpid (), pid, WEXITSTATUS (waiter)));
	  save_lastrun (CatchUpList);
	}
    }
}
示例#15
0
	foreach(myLang l, languages) {
		QAction *a = new QAction(l.english, langGroup);
		a->setToolTip(l.native);
		a->setData(QVariant(l.locale));
		a->setDisabled(!XCA_application::languageAvailable(l.locale));
		a->setCheckable(true);
		langGroup->addAction(a);
		languageMenu->addAction(a);
		if (l.locale == XCA_application::language())
			a->setChecked(true);
	}
	file = menuBar()->addMenu(tr("&File"));
	file->addAction(tr("&New DataBase"), this, SLOT(new_database()),
			QKeySequence::New)
			->setEnabled(OpenDb::hasSqLite());
	file->addAction(tr("&Open DataBase"), this, SLOT(load_database()),
			QKeySequence::Open)
			->setEnabled(OpenDb::hasSqLite());
	file->addAction(tr("Open Remote DataBase"),
			this, SLOT(openRemoteSqlDB()))
			->setEnabled(OpenDb::hasRemoteDrivers());
	file->addMenu(historyMenu);
	file->addAction(tr("Set as default DataBase"), this,
				SLOT(default_database()));
	acList += file->addAction(tr("&Close DataBase"), this,
		SLOT(close_database()), QKeySequence(QKeySequence::Close));

	a = new QAction(tr("Options"), this);
	connect(a, SIGNAL(triggered()), this, SLOT(setOptions()));
	a->setMenuRole(QAction::PreferencesRole);
	file->addAction(a);
示例#16
0
/**
 * Constructor for the library class
 */
library::library(QString loc){
    load_database(loc);
}
示例#17
0
// -------------------------------------------------------------------------------------------------
int main(int argc, char**argv)
{
	try
	{

		// Settings
		aq::Settings settings;      
    settings.outputFile = "stdout";

		// log options
		std::string mode;
		std::string ident;
		unsigned int level;
		bool lock_mode = false;
		bool date_mode = false;
		bool pid_mode = false;

		// aq options
    std::string aqHome;
    std::string aqName;
		std::string propertiesFile;
		std::string queryIdent;
		std::string sqlQuery;
		std::string sqlQueriesFile;
		std::string baseDescr;
    std::string DLLFunction;
		unsigned int worker;
		bool multipleAnswerFiles = false;
		bool keepFiles = false;
		bool display = false;
    bool displayCount = false;
    bool trace = false;
		bool loadDatabase = false;
    bool force = false;
    bool useTextAQMatrix = false;

    // testing purpose options
		std::string aqMatrixFileName;
		bool transform = false;
    bool checkDatabase = false;
		bool simulateAQEngine = false;
		bool skipNestedQuery = false;

    // load option
    std::string tableNameToLoad;

    // generate tmp table option
    unsigned int nbValues = 100;
    unsigned int minValue = 0;
    unsigned int maxValue = 100;
    unsigned int nbTables = 1;
    bool generateTmpTable = false;

    char * s = ::getenv("AQ_HOME");
    if (s != NULL)
      aqHome = s;

    //
    // initialize verb builder
    aq::VerbBuilder vb;
    aq::verb::VerbFactory::GetInstance().setBuilder(&vb);

    //
    // if aq.ini exists in current directory, use it as default settings
    settings.iniFile = "aq.ini";
    boost::filesystem::path iniFile(settings.iniFile);
    if (boost::filesystem::exists(iniFile))
    {
      settings.load(settings.iniFile);
    }

    //
    // look for properties file in args
    for (size_t i = 1; i < argc; i++)
    {
      //
      // read ini file
      if ((strcmp(argv[i], "-s") == 0) || (strcmp(argv[i], "--settings") == 0))
      {
        if ((i + 1) < argc)
        {
          propertiesFile = argv[i+1];
          settings.load(propertiesFile);
        }
      }

    }

    //
    // command line arguments are prior to settings file
    po::options_description all("Allowed options");
		all.add_options()
			("help,h", "produce help message")
      ;

    po::options_description log_options("Logging");
    log_options.add_options()
			("log-output", po::value<std::string>(&mode)->default_value("STDOUT"), "[STDOUT|LOCALFILE|SYSLOG]")
			("log-level,v", po::value<unsigned int>(&level)->default_value(AQ_LOG_WARNING), "CRITICAL(2), ERROR(3), WARNING(4), NOTICE(5), INFO(6), DEBUG(7)")
			("log-lock", po::bool_switch(&lock_mode), "for multithread program")
			("log-date", po::bool_switch(&date_mode), "add date to log")
			("log-pid", po::bool_switch(&pid_mode), "add thread id to log")
			("log-ident", po::value<std::string>(&ident)->default_value("aq_query_resolver"), "")
			;

    po::options_description engine("Engine");
    engine.add_options()
      ("settings,s", po::value<std::string>(&propertiesFile), "")
      ("aq-engine,e", po::value<std::string>(&settings.aqEngine))
      ("aq-home,r", po::value<std::string>(&aqHome)->default_value(aqHome), "set AQ Home (AQ_HOME environment variable)")
      ("aq-name,n", po::value<std::string>(&aqName), "")
			("query-ident,i", po::value<std::string>(&queryIdent), "")
      ("queries-file,f", po::value<std::string>(&sqlQueriesFile), "")
			("output,o", po::value<std::string>(&settings.outputFile), "")
			("worker,w", po::value<unsigned int>(&worker), "number of thread assigned to resolve the bunch of sql queries")
			("parralellize,p", po::value<size_t>(&settings.process_thread)->default_value(settings.process_thread), "number of thread assigned resolve one sql queries")
			("display-count", po::bool_switch(&displayCount), "")
      ("force", po::bool_switch(&force), "force use of directory if it already exists")
			("keep-file,k", po::bool_switch(&keepFiles), "")
      ("trace,t", po::bool_switch(&trace), "")
      ;

    po::positional_options_description positionalOptions; 
    positionalOptions.add("aq-name", -1); 

    po::options_description testing("Testing");
    testing.add_options()
      ("simulate-aq-engine,z", po::bool_switch(&simulateAQEngine), "")
			("transform", po::bool_switch(&transform), "")
			("skip-nested-query", po::value<bool>(&settings.skipNestedQuery), "")
			("aq-matrix", po::value<std::string>(&aqMatrixFileName), "")
      ("check-database", po::bool_switch(&checkDatabase), "")
      ;

    po::options_description external("External");
    external.add_options()
      ("use-dll-function", po::value<std::string>(&DLLFunction), "Choise your own .dll to use your function")
      ("use-bin-aq-matrix", po::bool_switch(&useTextAQMatrix), "")
      ;

    po::options_description loader("Loader");
    loader.add_options()
      ("aq-loader,l", po::value<std::string>(&settings.aqLoader))
			("load-db", po::bool_switch(&loadDatabase), "")
      ("load-table", po::value<std::string>(&tableNameToLoad), "")
			;
    
    po::options_description genTmpTable("GenerateTmpTable [TESTING PURPOSE]");
    genTmpTable.add_options()
      ("gen-tmp-table", po::bool_switch(&generateTmpTable), "")
			("nb-values", po::value<unsigned int>(&nbValues), "")
      ("min-value", po::value<unsigned int>(&minValue), "")
      ("max-value", po::value<unsigned int>(&maxValue), "")
      ("nb-tables", po::value<unsigned int>(&nbTables), "")
			;

    all.add(log_options).add(engine).add(testing).add(external).add(loader).add(genTmpTable);

		po::variables_map vm;
		po::store(po::command_line_parser(argc, argv).options(all).positional(positionalOptions).run(), vm);
		po::notify(vm);    

		if (vm.count("help"))
		{
			std::cout << all << "\n";
			return 1;
		}

    // parse positional options
    if (vm.count("aq-name"))
    {
      aqName = vm["aq-name"].as<std::string>();
    }
		
    //
    // settings flags bool
    settings.trace = trace || settings.trace;
    settings.displayCount = displayCount || settings.displayCount;
    settings.cmdLine = _isatty(_fileno(stdin)) != 0;
    
    //
    //
    boost::replace_all(aqHome, "\\", "/");
    boost::replace_all(aqHome, "//", "/");
    if ((!aqHome.empty()) && (*aqHome.rbegin() != '/'))
    {
      aqHome = aqHome + "/";
    }

    //
    //
    if (aqName == "")
    {
      aqName = settings.aqName;
    }
    if ((aqHome != "") && (aqName != ""))
    {
      settings.initPath(aqHome + aqName);
    }

		//
		// Initialize Logger
		aq::Logger::getInstance(ident.c_str(), mode == "STDOUT" ? STDOUT : mode == "LOCALFILE" ? LOCALFILE : mode == "SYSLOG" ? SYSLOG : STDOUT);
		aq::Logger::getInstance().setLevel(level);
		aq::Logger::getInstance().setLockMode(lock_mode);
		aq::Logger::getInstance().setDateMode(date_mode);
		aq::Logger::getInstance().setPidMode(pid_mode);
    
		//
		// print Project Settings
    aq::Logger::getInstance().log(AQ_DEBUG, "Settings:\n%s\n", settings.to_string().c_str());

		//
		// If Load database is invoked
		if (loadDatabase)
		{
      aq::base_t bd;
      if (aq::build_base_from_raw(settings.dbDesc.c_str(), bd) != -1)
      {
        return load_database(settings, bd, tableNameToLoad);
      }
      else
      {
        aq::Logger::getInstance().log(AQ_CRITICAL, "cannot find database desc file '%s'\n", settings.dbDesc.c_str());
        return EXIT_FAILURE;
      }
      assert(false);
		}

    //
    // Check Database
    if (checkDatabase)
    {
      return check_database(settings);
    }

    //
    // If generated temporary table is invoked
    if (generateTmpTable)
    {
      aq::base_t bd;
      if (aq::build_base_from_raw(settings.dbDesc.c_str(), bd) != -1)
      {
        int rc = 0;
        while ((nbTables-- > 0) && ((rc = generate_tmp_table(settings, bd, nbValues, minValue, maxValue)) == 0));
        return rc;
      }
      else
      {
        aq::Logger::getInstance().log(AQ_CRITICAL, "cannot find database desc file '%s'\n", settings.dbDesc.c_str());
        return EXIT_FAILURE;
      }
    }

    //
    // Solve Queries
    aq::Base bd(settings.dbDesc);
    return parse_queries(
      aqHome, aqName, queryIdent, sqlQueriesFile, aqMatrixFileName, 
      settings, bd,
      transform, simulateAQEngine, keepFiles, force);

  }
	catch (const aq::generic_error& error)
	{
    aq::Logger::getInstance().log(AQ_CRITICAL, error.what());
		std::cerr << "generic error: " << error.what() << std::endl;
		return error.getType();
	}
	catch (const std::exception& ex)
	{
		std::cerr << "standard exception" << ex.what() << std::endl;
		return EXIT_FAILURE;
	}
	catch (...)
	{
		std::cerr << "UNHANDLE EXCEPTION" << std::endl;
		return EXIT_FAILURE;
	}

  if (failedQueries) return EXIT_FAILURE;
	return EXIT_SUCCESS;
}
示例#18
0
文件: MW_menu.cpp 项目: J-Javan/xca
void MainWindow::init_menu()
{
	QMenu *file, *help, *import, *token;

	file = menuBar()->addMenu(tr("&File"));
	file->addAction(tr("&New DataBase"), this, SLOT(new_database()),
		QKeySequence::New);
	file->addAction(tr("&Open DataBase"), this, SLOT(load_database()),
		QKeySequence::Open);
	file->addAction(tr("Generate DH parameter"), this,
				 SLOT(generateDHparam()));
	acList += file->addAction(tr("&Close DataBase"), this,
		SLOT(close_database()), QKeySequence(QKeySequence::Close));
	acList += file->addAction(tr("&Dump DataBase"), this,
				SLOT(dump_database()));
	acList += file->addAction(tr("C&hange DataBase password"), this,
				SLOT(changeDbPass()));
	acList += file->addAction(tr("&Import old db_dump"), this,
				SLOT(import_dbdump()));
	acList += file->addAction(tr("&Undelete items"), this,
				SLOT(undelete()));
	file->addSeparator();
	acList += file->addAction(tr("Options"), this, SLOT(setOptions()));
	file->addSeparator();
	file->addAction(tr("Exit"), qApp, SLOT(quit()), Qt::ALT+Qt::Key_F4);

	import = menuBar()->addMenu(tr("I&mport"));
	import->addAction(tr("Keys"), this,
				SLOT(on_BNimportKey_clicked()) );
	import->addAction(tr("Requests"), this,
				SLOT(on_BNimportReq_clicked()) );
	import->addAction(tr("Certificates"), this,
				SLOT(on_BNimportCert_clicked()) );
	import->addAction(tr("PKCS#12"), this,
				SLOT(on_BNimportPKCS12_clicked()) );
	import->addAction(tr("PKCS#7"), this,
				SLOT(on_BNimportPKCS7_clicked()) );
	import->addAction(tr("Template"), this,
				SLOT(on_BNimportTemp_clicked()) );
	import->addAction(tr("Revocation list"), this,
				SLOT(on_BNimportCrl_clicked()) );
	import->addAction(tr("PEM file"), this,
				SLOT(loadPem()) );
	import->addAction(tr("paste PEM file"), this,
				SLOT(pastePem()) );

	token = menuBar()->addMenu(tr("&Token"));
	token->addAction(tr("&Manage Security token"), this,
				SLOT(manageToken()));
	token->addAction(tr("&Init Security token"),  this,
				SLOT(initToken()));
	token->addAction(tr("&Change PIN"), this,
				SLOT(changePin()) );
	token->addAction(tr("Change &SO PIN"), this,
				SLOT(changeSoPin()) );
	token->addAction(tr("Init PIN"), this,
				SLOT(initPin()) );

	help = menuBar()->addMenu(tr("&Help") );
	help->addAction(tr("&Content"), this, SLOT(help()),
			QKeySequence::HelpContents);
	help->addAction(tr("&About"), this, SLOT(about()) );
	help->addAction(tr("Donations"), this, SLOT(donations()) );
	wdList += import;
	scardList += token;
}
示例#19
0
bool CConfigLoader::load(const std::string& filepath)
{
    Json::Reader reader;
    Json::Value root;
    std::ifstream fs(filepath.c_str());
    struct DbInfo* db_info_array[MAX_DB_CONNECTION] = { NULL };
    struct QueryInfo* query_info_array[MAX_SQL_TEMPLATE] = { NULL };
    struct UpdateInfo* update_info_array[MAX_SQL_TEMPLATE] = { NULL };

    if (_md5_sum.empty())
    {
        MYLOG_INFO("loading %s\n", filepath.c_str());
    }
    else
    {
        MYLOG_DETAIL("loading %s\n", filepath.c_str());
    }
    if (!fs)
    {
        MYLOG_ERROR("load %s failed: %s\n", filepath.c_str(), strerror(errno));
        return false;
    }
    if (!reader.parse(fs, root))
    {
        MYLOG_ERROR("parse %s failed: %s\n", filepath.c_str(), reader.getFormattedErrorMessages().c_str());
        return false;
    }

    // 检查文件是否有修改过
    std::string md5_sum = utils::CMd5Helper::lowercase_md5("%s", root.toStyledString().c_str());
    if (md5_sum == _md5_sum)
    {
        MYLOG_DETAIL("not changed: (%s)%s\n", md5_sum.c_str(), filepath.c_str());
        return true; // 未发生变化
    }

    init_db_info_array(db_info_array);
    init_query_info_array(query_info_array);
    init_update_info_array(update_info_array);
    if (!load_database(root["database"], db_info_array))
        return false;
    if (!load_query(root["query"], query_info_array))
        return false;
    if (!load_update(root["update"], update_info_array))
        return false;

    int i; // 加写锁
    sys::WriteLockHelper write_lock(_read_write_lock);

    release_db_info_array(_db_info_array);
    release_query_info_array(_query_info_array);
    release_update_info_array(_update_info_array);
    for (i=0; i<MAX_DB_CONNECTION; ++i)
    {
        if (db_info_array[i] != NULL)
        {
            // 启动时即连接一下,以早期发现配置等问题
            _db_info_array[i] = new struct DbInfo(*db_info_array[i]);
            sys::DBConnection* db_connection = init_db_connection(i, false);
            if (db_connection != NULL)
            {
                delete db_connection;
                db_connection = NULL;
            }
        }
    }
    for (i=0; i<MAX_SQL_TEMPLATE; ++i)
    {
        if (query_info_array[i] != NULL)
            _query_info_array[i] = new struct QueryInfo(*query_info_array[i]);
        if (update_info_array[i] != NULL)
            _update_info_array[i] = new struct UpdateInfo(*update_info_array[i]);
    }

    _md5_sum = md5_sum;
    MYLOG_INFO("loaded %s[%s] successfully\n", filepath.c_str(), _md5_sum.c_str());
    return true;
}
		Review(bool load) : m_db(DATABASE_FILE, load)
			{ if (load) load_database(); }
示例#21
0
文件: cron.c 项目: enukane/netbsd-src
int
main(int argc, char *argv[]) {
	struct sigaction sact;
	cron_db	database;

	setprogname(argv[0]);
	(void)setlocale(LC_ALL, "");

	(void)setvbuf(stdout, NULL, _IOLBF, 0);
	(void)setvbuf(stderr, NULL, _IOLBF, 0);

	NoFork = 0;
	parse_args(argc, argv);

	(void)memset(&sact, 0, sizeof sact);
	(void)sigemptyset(&sact.sa_mask);
	sact.sa_flags = 0;
#ifdef SA_RESTART
	sact.sa_flags |= SA_RESTART;
#endif
	sact.sa_handler = sigchld_handler;
	(void) sigaction(SIGCHLD, &sact, NULL);
	sact.sa_handler = sighup_handler;
	(void) sigaction(SIGHUP, &sact, NULL);
	sact.sa_handler = quit;
	(void) sigaction(SIGINT, &sact, NULL);
	(void) sigaction(SIGTERM, &sact, NULL);

	acquire_daemonlock(0);
	set_cron_uid();
	set_cron_cwd();

	if (setenv("PATH", _PATH_DEFPATH, 1) < 0) {
		log_it("CRON", getpid(), "DEATH", "can't malloc");
		exit(1);
	}

	/* if there are no debug flags turned on, fork as a daemon should.
	 */
	if (DebugFlags) {
#if DEBUGGING
		(void)fprintf(stderr, "[%ld] cron started\n", (long)getpid());
#endif
	} else if (NoFork == 0) {
		if (daemon(1, 0)) {
			log_it("CRON",getpid(),"DEATH","can't fork");
			exit(1);
		}
	}

	acquire_daemonlock(0);
	database.head = NULL;
	database.tail = NULL;
	database.mtime = (time_t) 0;
	load_database(&database);
	set_time(TRUE);
	run_reboot_jobs(&database);
	timeRunning = virtualTime = clockTime;

	/*
	 * Too many clocks, not enough time (Al. Einstein)
	 * These clocks are in minutes since the epoch, adjusted for timezone.
	 * virtualTime: is the time it *would* be if we woke up
	 * promptly and nobody ever changed the clock. It is
	 * monotonically increasing... unless a timejump happens.
	 * At the top of the loop, all jobs for 'virtualTime' have run.
	 * timeRunning: is the time we last awakened.
	 * clockTime: is the time when set_time was last called.
	 */
	for (;;) {
		int timeDiff;
		enum timejump wakeupKind;

		/* ... wait for the time (in minutes) to change ... */
		do {
			cron_sleep(timeRunning + 1);
			set_time(FALSE);
		} while (clockTime == timeRunning);
		timeRunning = clockTime;

		/*
		 * Calculate how the current time differs from our virtual
		 * clock.  Classify the change into one of 4 cases.
		 */
		timeDiff = timeRunning - virtualTime;

		/* shortcut for the most common case */
		if (timeDiff == 1) {
			virtualTime = timeRunning;
			find_jobs(virtualTime, &database, TRUE, TRUE);
		} else {
			if (timeDiff > (3*MINUTE_COUNT) ||
			    timeDiff < -(3*MINUTE_COUNT))
				wakeupKind = large;
			else if (timeDiff > 5)
				wakeupKind = medium;
			else if (timeDiff > 0)
				wakeupKind = small;
			else
				wakeupKind = negative;

			switch (wakeupKind) {
			case small:
				/*
				 * case 1: timeDiff is a small positive number
				 * (wokeup late) run jobs for each virtual
				 * minute until caught up.
				 */
				Debug(DSCH, ("[%ld], normal case %d minutes to go\n",
				    (long)getpid(), timeDiff));
				do {
					if (job_runqueue())
						(void)sleep(10);
					virtualTime++;
					find_jobs(virtualTime, &database,
					    TRUE, TRUE);
				} while (virtualTime < timeRunning);
				break;

			case medium:
				/*
				 * case 2: timeDiff is a medium-sized positive
				 * number, for example because we went to DST
				 * run wildcard jobs once, then run any
				 * fixed-time jobs that would otherwise be
				 * skipped if we use up our minute (possible,
				 * if there are a lot of jobs to run) go
				 * around the loop again so that wildcard jobs
				 * have a chance to run, and we do our
				 * housekeeping.
				 */
				Debug(DSCH, ("[%ld], DST begins %d minutes to go\n",
				    (long)getpid(), timeDiff));
				/* run wildcard jobs for current minute */
				find_jobs(timeRunning, &database, TRUE, FALSE);
	
				/* run fixed-time jobs for each minute missed */
				do {
					if (job_runqueue())
						(void)sleep(10);
					virtualTime++;
					find_jobs(virtualTime, &database,
					    FALSE, TRUE);
					set_time(FALSE);
				} while (virtualTime < timeRunning &&
				    clockTime == timeRunning);
				break;
	
			case negative:
				/*
				 * case 3: timeDiff is a small or medium-sized
				 * negative num, eg. because of DST ending.
				 * Just run the wildcard jobs. The fixed-time
				 * jobs probably have already run, and should
				 * not be repeated.  Virtual time does not
				 * change until we are caught up.
				 */
				Debug(DSCH, ("[%ld], DST ends %d minutes to go\n",
				    (long)getpid(), timeDiff));
				find_jobs(timeRunning, &database, TRUE, FALSE);
				break;
			default:
				/*
				 * other: time has changed a *lot*,
				 * jump virtual time, and run everything
				 */
				Debug(DSCH, ("[%ld], clock jumped\n",
				    (long)getpid()));
				virtualTime = timeRunning;
				find_jobs(timeRunning, &database, TRUE, TRUE);
			}
		}

		/* Jobs to be run (if any) are loaded; clear the queue. */
		(void)job_runqueue();

		/* Check to see if we received a signal while running jobs. */
		if (got_sighup) {
			got_sighup = 0;
			log_close();
		}
		if (got_sigchld) {
			got_sigchld = 0;
			sigchld_reaper();
		}
		load_database(&database);
	}
}
示例#22
0
// main() function - where the action all starts...
int main(int argc, char *argv[])
{
	int selection, i,j;
	char ch;
	char name[NAMELENGTH],phone[NOLENGTH];
	struct entry *p;
	
	for (i=0;i<SIZE;i++)
		head[i] = tail[i] = NULL;

	if (argc == 2)
	{
		load_database(argv[1]);
	}
	else
		argv[1] = "phonebook.txt";
    
	printf("********************************\n");
   	printf("Welcome to the SAT Phone Book!\n");
    
   	while (selection  != 5)
   	{
        	printf("Please make your selection.\n");
          	printf("1 - Add a Name to the Phone Book\n");
          	printf("2 - Delete a Name from the Phone Book\n");
          	printf("3 - Display all Names in the Phone Book\n");
          	printf("4 - Display all Names of A Specific Letter\n");
		printf("5 - Quit\n");
          
		selection = 0;
		scanf("%d",&selection);
		  
		printf("********************************\n");
		  
		switch (selection)
		{
			case 1:
				printf("Type in the First Name\n");
				scanf("%s",name);
				printf("Type in the Phone Number\n");
				scanf("%s",phone);
			      	insert(name,phone);
			      	break;
			case 2:
				printf("Type in the First Name\n");
				scanf("%s",name);
				delete(name);
			      	break;
			case 3:
			      	display();
			      	break;
			case 4:
				printf("What is the first letter ");
				printf("of the first name?\n");
				scanf("\n%c",&ch);
				display_letter(&ch);
				break;

			case 5:
				save_database(argv[1]);
				break;
			default:
				printf("Sorry, your menu selection ");
				printf("is invalid.\n");
				break;
		}
		  
		printf("********************************\n");
	}
	    
	return 0;
}