示例#1
0
void initProgram(int argc, char ** argv, char ** envp)
{
	cfg.argc = argc;
	cfg.argv = argv;
	cfg.envp = envp;
	cfg.help = 0;
	cfg.debug = 0;
	cfg.daemon = 0;
	cfg.version = 0;
	cfg.syslog = 0;

	cfg.port = 0;
	cfg.passkey = NULL;

	initOptions();

	printDebug();
	printHelp();
	printVersion();

	signal(SIGINT, mySignal);

	daemonize();
	initLogging();

	initServer();
}
示例#2
0
ConfigurationManager::ConfigurationManager(ItemFactory *itemFactory, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ConfigurationManager)
    , m_options()
{
    ui->setupUi(this);
    connectSlots();
    setWindowIcon(appIcon());

    connect( ui->configTabShortcuts, &ConfigTabShortcuts::commandsSaved,
             this, &ConfigurationManager::commandsSaved );

    ui->spinBoxItems->setMaximum(Config::maxItems);

    if ( itemFactory && itemFactory->hasLoaders() )
        initPluginWidgets(itemFactory);
    else
        ui->tabItems->hide();

    initOptions();

    if (itemFactory)
        ui->configTabAppearance->createPreview(itemFactory);

    loadSettings();

    if (itemFactory)
        ui->configTabShortcuts->addCommands( itemFactory->commands() );
}
示例#3
0
文件: main.c 项目: b4n/fishman-ctags
extern int main (int __unused__ argc, char **argv)
{
	cookedArgs *args;
#ifdef VMS
	extern int getredirection (int *ac, char ***av);

	/* do wildcard expansion and I/O redirection */
	getredirection (&argc, &argv);
#endif

#ifdef AMIGA
	/* This program doesn't work when started from the Workbench */
	if (argc == 0)
		exit (1);
#endif

#ifdef __EMX__
	_wildcard (&argc, &argv);  /* expand wildcards in argument list */
#endif

#if defined (macintosh) && BUILD_MPW_TOOL == 0
	argc = ccommand (&argv);
#endif

	setCurrentDirectory ();
	setExecutableName (*argv++);
	sanitizeEnviron ();
	checkRegex ();

	args = cArgNewFromArgv (argv);
	previewFirstOption (args);
	testEtagsInvocation ();
	initializeParsing ();
	initOptions ();
	readOptionConfiguration ();
	verbose ("Reading initial options from command line\n");
	parseOptions (args);
	checkOptions ();
	unifyLanguageMaps ();
	makeTags (args);

	/*  Clean up.
	 */
	cArgDelete (args);
	freeKeywordTable ();
	freeRoutineResources ();
	freeSourceFileResources ();
	freeTagFileResources ();
	freeOptionResources ();
	freeParserResources ();
	freeRegexResources ();
	freeXcmdResources ();

	if (Option.guessParser)
		return (Option.guessParser == TRUE)? 0: 1;

	exit (0);
	return 0;
}
示例#4
0
/**
 * Sets project options.
 * @param	opt	A structure containing the new parameters to set
 */
void Project::setOptions(const Options& opt)
{
	// Write the options to the configuration nfile
	writeOptions(m_pConf, opt);
				
	// Update project parameters
	initOptions();
}
示例#5
0
文件: title.c 项目: LibreGames/tbftss
static void options(void)
{
	selectWidget("ok", "options");
	
	show = SHOW_OPTIONS;
	
	initOptions(returnFromOptions);
}
示例#6
0
ConfigurationManager::ConfigurationManager()
    : ui(new Ui::ConfigurationManager)
    , m_options()
{
    ui->setupUi(this);
    connectSlots();
    initOptions();
}
示例#7
0
文件: java.cpp 项目: nomit007/f4
int runJava()
{
  if (findJvmPath())  return -1;
  if (initOptions())  return -1;
  if (loadJava())     return -1;
  if (checkVersion()) return -1;
  if (runJavaMain())  return -1;
  return 0;
}
示例#8
0
AppConfigDialog::AppConfigDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::AppConfigDialog)
    , _options()
{
    ui->setupUi(this);
    initOptions();
    initLanguages();
    initThemes();
}
void PrintDialogController::options(QString symbol,int print,QString copy)
{
    setCopyOrOriginal(copy);
    setSymbol(symbol);
    if(copy=="ORYGINAŁ"||copy=="DUPLIKAT")
    initOptions();
    setOutputFile();
    if(print) //usuniecie deafultowego miejsca zapisania powoduje przekierowanie na drukarke
    getPrinter()->setOutputFileName("");

}
示例#10
0
int  main()
/*********/

{
    char                *cmd;
    void               (*parse_object)( void );

#if defined( _M_I86SM ) || defined( _M_I86MM )
    _heapgrow();    /* grow the near heap */
#endif
    if( !MsgInit() ) return( EXIT_FAILURE );
    cmd = AllocMem( CMD_LINE_SIZE );
    getcmd( cmd );
    InitOutput();
    initOptions();
    parseOptions( cmd );
    openFiles();
    InitObj();
    parse_object = InitORL() ? ParseObjectORL : ParseObjectOMF;
    for( ;; ) {
        InitTables();
        ModNameORL = rootName;
        parse_object();
        if( Mod == NULL ) {
            break;
        }
        if( srcReqd ) {
            if( SrcName == NULL ) {
                if( CommentName != NULL ) {
                    SrcName = CommentName;
                } else if( Mod->name != NULL ) {
                    SrcName = Mod->name;
                } else {
                    SrcName = rootName;
                }
            }
            OpenSource();
        }
        DisAssemble();
        if( Source != NULL ) {
            CloseTxt( Source );
        }
        SrcName = NULL;         /* if another module, get name from obj file */
    }
    if( UseORL ) FiniORL();
    CloseBin( ObjFile );
    CloseTxt( Output );
    MsgFini();
    return( 0 );
}
示例#11
0
文件: bc.c 项目: Zubnix/aura
static int bcmain(int argc, char* argv[]) {
    initOptions();
    if (!rvmInitOptions(argc, argv, &options, FALSE)) {
        fprintf(stderr, "rvmInitOptions(...) failed!\n");
        return 1;
    }
    Env* env = rvmStartup(&options);
    if (!env) {
        fprintf(stderr, "rvmStartup(...) failed!\n");
        return 1;
    }
    vm = env->vm;
    jint result = rvmRun(env) ? 0 : 1;
    rvmShutdown(env, result);
    return result;
}
示例#12
0
bool CFrameWndFactory::CreateFrameWnd(LPCWSTR factoryFile)
{
    CXTPWinDwmWrapper().SetProcessDPIAware();   // Support high DPI on Vista or above.

    std::wstring xtpfile(getTranslationsPath(L"ToolkitPro.Resource.xml"));
    if (PathFileExistsW(xtpfile.c_str()))
        XTPResourceManager()->SetResourceFile(xtpfile.c_str());
    else
        TRACE1("Warning: no translation file '%s'\n", xtpfile.c_str());

    Object<IConfigXml> xmlfile(x3::clsidXmlFile);
    ASSERT_MESSAGE(xmlfile, "Need the configxml plugin.");
    xmlfile->SetFileName((getConfigPath() + factoryFile).c_str());
    ASSERT_MESSAGE(xmlfile->Reload(), "No xml file or need to setup MSXML4.");

    ConfigSection root(xmlfile->GetData()->GetSection(L""));
    ConfigSection mainframe(root.GetSection(L"mainframe"));
    bool mdi = root->GetBool(L"mdi", false);

    g_factoryRoot = root;
    g_factoryRoot->SetString(L"_appid", m_appid.c_str());

    Object<IUIOptionsInit> initOptions(clsidUIOptions);
    initOptions->setFileName((getConfigPath() + 
        root->GetString(L"optionsFile", L"uioptions.xml")).c_str());

    RegisterDocTemplate(mdi, mainframe, root.GetSection(L"views"));
    if (mdi)
    {
        CMainMDIFrame* pFrame = new CMainMDIFrame;
        if (!pFrame->LoadFrame(0))
            return FALSE;

        std::vector<ViewItem>::const_iterator it = s_views.begin();
        for (; it != s_views.end(); ++it)
        {
            if (!it->caption.empty())
            {
                CDocument* pDoc = it->pTemplate->OpenDocumentFile(NULL);
                pDoc->SetTitle(it->caption.c_str());
            }
        }
    }

    return ProcessShellCommand();
}
示例#13
0
文件: nm2tsv.c 项目: diversys/bezilla
int main(int inArgc, char** inArgv)
{
    int retval = 0;
    Options options;

    retval = initOptions(&options, inArgc, inArgv);
    if(options.mHelp)
    {
        showHelp(&options);
    }
    else if(0 == retval)
    {
        retval = nm2tsv(&options);
    }

    cleanOptions(&options);
    return retval;
}
示例#14
0
bool Project::open(const QString& sPath)
{
	QString sConfFile;
	Options opt;
	
	// Associate the object with the project directory
	m_dir.setPath(sPath);
	if (!m_dir.exists()) {
		KMessageBox::error(0, i18n("Project directory does not exist"));
		return false;
	}
	
	// Initialise the file-list file object
	m_fiFileList.setName(sPath + "/cscope.files");

	// Open the configuration files
	m_pConf = new KConfig(sPath + "/cscope.proj");

	// Verify the configuration file's version is compatible
	m_pConf->setGroup("");
	if (m_pConf->readUnsignedNumEntry("Version", 0) != PROJECT_CONFIG_VER) {
		KMessageBox::error(0, i18n("Your project is not compatible with this "
				"version of KScope.\nPlease re-create the project."));
		return false;
	}
	
	// Get the project name
	m_pConf->setGroup("Project");
	m_sName = m_pConf->readEntry("Name");
	if (m_sName == QString::null) {
		KMessageBox::error(0, i18n("Cannot read project name"));
		return false;
	}
	
	// Get stored options
	initOptions();
	
	// Set default make values for new projects (overriden in loadSession(), 
	// which is not called for new projects)
	m_sMakeRoot = getSourceRoot();
	m_sMakeCmd = "make";
	
	return true;
}
示例#15
0
int CDECL main(int argc, char **argv)
{
   if (argc ==1)
   {
	 cerr << "Usage: makeeco eco_file" << endl;
	 return -1;
   }
   Bitboard::init();
   initOptions(argv[0]);
   Attacks::init();
   Scoring::init();
   if (!initGlobals(argv[0], false)) {
       cleanupGlobals();
       exit(-1);
   }
   atexit(cleanupGlobals);
   
   ifstream eco_file( argv[argc-1], ios::in);
   if (!eco_file.good())
   {
         cerr << "Cannot open file: " << argv[argc-1] << endl;
	 return -1;
   }
   Board b;
   cout << "// This is a machine-generated file.  Do not edit." << endl;
   cout << endl;   
   cout << "#include \"ecodata.h\"" << endl << endl;
   cout << "const struct ECOData eco_codes[] =" << endl;
   cout << "{{" << '"' << "A00" << '"' << ", ";
   write_64(b.hashCode(),cout);
   cout << ", " << '"' << '"' << "}," << endl;
   int lines = 1;
   while (eco_file.good() && !eco_file.eof())
   {
       string eco_line;
       getline(eco_file,eco_line);
       if (do_eco(eco_line)) {
           cerr << "error in ECO file, line " << lines << endl;
       }
       ++lines;
   }
   cout << "{0,0," << '"' << '"' << "}};" << endl;
   return 0;
}
示例#16
0
文件: bc.c 项目: Zubnix/aura
jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* pvm_args) {
    initOptions();

    JavaVMInitArgs* vmArgs = (JavaVMInitArgs*) pvm_args;
    if (vmArgs) {
        for (int i = 0; i < vmArgs->nOptions; i++) {
            JavaVMOption* opt = &vmArgs->options[i];
            if (startsWith(opt->optionString, "-rvm:")) {
                char* arg = &opt->optionString[5];
                rvmParseOption(arg, &options);
            } else if (startsWith(opt->optionString, "-X")) {
                char* arg = &opt->optionString[2];
                rvmParseOption(arg, &options);
            } else if (startsWith(opt->optionString, "-D")) {
                char* arg = &opt->optionString[1];
                rvmParseOption(arg, &options);
            } else if (startsWith(opt->optionString, "-verbose")) {
                rvmParseOption("log=trace", &options);
            }
        }
    }

    if (!rvmInitOptions(0, NULL, &options, FALSE)) {
        return JNI_ERR;
    }

    // Start up robovm (JNI)
    Env* env = rvmStartup(&options);
    if (!env) {
        return JNI_ERR;
    }

    vm = env->vm;

    // Return values.
    if (p_vm) {
        *p_vm = &vm->javaVM;
    }
    if (p_env) {
        *p_env = &env->jni;
    }

    return JNI_OK;
}
示例#17
0
文件: main.c 项目: koron/ctags
extern int main (int __unused__ argc, char **argv)
{
	cookedArgs *args;

	setCurrentDirectory ();
	setExecutableName (*argv++);
	sanitizeEnviron ();
	checkRegex ();

	args = cArgNewFromArgv (argv);
	previewFirstOption (args);
	testEtagsInvocation ();
	initializeParsing ();
	initOptions ();
	readOptionConfiguration ();
	verbose ("Reading initial options from command line\n");
	parseOptions (args);
	checkOptions ();
	unifyLanguageMaps ();
	makeTags (args);

	/*  Clean up.
	 */
	cArgDelete (args);
	freeKeywordTable ();
	freeRoutineResources ();
	freeSourceFileResources ();
	freeTagFileResources ();
	freeOptionResources ();
	freeParserResources ();
	freeRegexResources ();
	freeXcmdResources ();
#ifdef HAVE_ICONV
	freeEncodingResources ();
#endif

	if (Option.printLanguage)
		return (Option.printLanguage == TRUE)? 0: 1;

	exit (0);
	return 0;
}
示例#18
0
void plottingmacro()
{
 setTDRStyle();
 gROOT->ForceStyle();
 initOptions();

 std::vector<Sample> s = samples();
 Sample data(1,"fake data","S1.root",0,true,1000);

 for(size_t i=0;i< s.size();i++) if(s[i].data) {data=s[i];break;}
 data.file()->ls(); 
 for(size_t i=0;i< s.size();i++) s[i].dump(data.lumi());

 std::vector<std::string> names;

 TList * subs = data.file()->GetListOfKeys();
 for(size_t i=0;i< subs->GetSize();i++)
  {
    TList * objs = ((TDirectoryFile *) data.file()->Get(subs->At(i)->GetName()))->GetListOfKeys();
     for(size_t j=0;j< objs->GetSize();j++)
     {
         names.push_back(subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName());
 //      std::cout << subs->At(i)->GetName() << "/"  << objs->At(j)->GetName() << std::endl;
         //TODO: select plots via regexp
     }
    
  }

 for(size_t i = 0 ; i < names.size() ; i++) 
  {
   std::map<std::string,TH1F *> grouped;
   TString n=names[i];
   if(!n.Contains(TRegexp("V.*RegionH.*mu.*HiggsMass"))) continue;
   TCanvas *c = new TCanvas();
   c->SetLogy(true);
   c->SetTitle(names[i].c_str());
   TH1F *hd = ((TH1F*)data.file()->Get(names[i].c_str()));
   Options o=options[names[i]];
   hd->Rebin(o.rebin);
   hd->SetMarkerStyle(21);
   hd->Draw("E1");
   hd->SetYTitle(o.yaxis.c_str());
   THStack * sta = new THStack("sta",hd->GetTitle());
   TLegend * l = new TLegend(o.legendx1,o.legendy1,o.legendx2,o.legendy2); //0.7,0.1,0.9,0.6);
  
   l->AddEntry(hd, "Data","LP");

   for(size_t j=0;j< s.size() ;j++) 
   { 
       if(!s[j].data) 
      {
       TH1F * h = ((TH1F*)s[j].file()->Get(names[i].c_str()));
       h->Scale(s[j].scale(data.lumi()));
       h->SetLineColor(s[j].color);
       h->SetFillColor(s[j].color);
       h->Rebin(options[names[i]].rebin);
       if(grouped.find(s[j].name)==grouped.end()) {
          grouped[s[j].name]=(TH1F *)h->Clone(("_"+names[i]).c_str());
          l->AddEntry(h,s[j].name.c_str(),"F");
       }
       else
       {
        grouped[s[j].name]->Add(h);
       }
       sta->Add(h);
//     h->Draw("same");
      }
   }
   sta->Draw("same");
   hd->Draw("E1same");
   hd->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
   l->Draw();


   std::cout << names[i] << " d: " <<  hd->Integral() << " ";
   THStack * sta2 = new THStack("sta2",hd->GetTitle());
   float tot=0;
   float toterr2=0;

   for(std::map<std::string,TH1F *>::iterator it = grouped.begin(); it != grouped.end();it++)
   {
             std::cout << it->first << " " << it->second->Integral() << " | " ;
             if(it->second->GetEntries() > 0) {
             float er=1.*sqrt(it->second->GetEntries())/it->second->GetEntries()*it->second->Integral();
             toterr2+=er*er;
             }
	     tot+=it->second->Integral();
             sta2->Add(it->second);
   }   
    std::cout << " Tot: " << tot << "+-" << sqrt(toterr2) <<  " SF: " << hd->Integral()/tot << std::endl;
    c = new TCanvas();
    sta2->Draw();
    hd->Draw("E1,same");
    sta2->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
    hd->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
    l->Draw();

   

  }

}
示例#19
0
Tetris::Tetris(int cmdlLevel):
	themeno (0),
	field(0),
	paused(false),
	timeoutId(0),
	onePause(false),
	inPlay(false),
	useTarget(false),
	bgimage(0),
	setupdialog(0),
	cmdlineLevel(cmdlLevel),
	fastFall(false),
	dropBlock(false)
{
	GtkUIManager *ui_manager;
	GtkAccelGroup *accel_group;
	GtkActionGroup *action_group;
	GtkWidget *vbox;
	GtkWidget *aspect_frame;
	GtkWidget *menubar;

	gchar *outdir;
	const char *dname;

	const GtkTargetEntry targets[] = {{(gchar*) "text/uri-list", 0, URI_LIST},
					  {(gchar*) "property/bgimage", 0, URI_LIST},
					  {(gchar*) "text/plain", 0, TEXT_PLAIN},
					  {(gchar*) "STRING", 0, TEXT_PLAIN},
					  {(gchar*) "application/x-color", 0, COLOUR},
					  {(gchar*) "x-special/gnome-reset-background", 0, RESET}};

	const GtkActionEntry actions[] = {
	{ "GameMenu", NULL, N_("_Game") },
	{ "SettingsMenu", NULL, N_("_Settings") },
	{ "HelpMenu", NULL, N_("_Help") },
	{ "NewGame", GAMES_STOCK_NEW_GAME, NULL, NULL, NULL, G_CALLBACK (gameNew) },
	{ "Pause", GAMES_STOCK_PAUSE_GAME, NULL, NULL, NULL, G_CALLBACK (gamePause) },
	{ "Resume", GAMES_STOCK_RESUME_GAME, NULL, NULL, NULL, G_CALLBACK (gamePause) },
	{ "Scores", GAMES_STOCK_SCORES, NULL, NULL, NULL, G_CALLBACK (gameTopTen) },
	{ "EndGame", GAMES_STOCK_END_GAME, NULL, NULL, NULL, G_CALLBACK (gameEnd) },
	{ "Quit", GTK_STOCK_QUIT, NULL, NULL, NULL, G_CALLBACK (gameQuit) },
	{ "Preferences", GTK_STOCK_PREFERENCES, NULL, NULL, NULL, G_CALLBACK (gameProperties) },
#ifdef WITH_GAMEPLAYDOC
	{ "Contents", GAMES_STOCK_CONTENTS, NULL, NULL, NULL, G_CALLBACK (gameHelp) },
#endif
	{ "About", GTK_STOCK_ABOUT, NULL, NULL, NULL, G_CALLBACK (gameAbout) }
	};

	const char ui_description[] =
	"<ui>"
	"  <menubar name='MainMenu'>"
	"    <menu action='GameMenu'>"
	"      <menuitem action='NewGame'/>"
	"      <menuitem action='Pause'/>"
	"      <menuitem action='Resume'/>"
	"      <separator/>"
	"      <menuitem action='Scores'/>"
	"      <menuitem action='EndGame'/>"
	"      <separator/>"
	"      <menuitem action='Quit'/>"
	"    </menu>"
	"    <menu action='SettingsMenu'>"
	"      <menuitem action='Preferences'/>"
	"    </menu>"
	"    <menu action='HelpMenu'>"
#ifdef WITH_GAMEPLAYDOC
	"      <menuitem action='Contents'/>"
#endif
	"      <menuitem action='About'/>"
	"    </menu>"
	"  </menubar>"
	"</ui>";


	/* Locate our background image. */

	outdir = g_build_filename (g_get_user_data_dir (), "gnometris", NULL);
	if (!g_file_test (outdir, G_FILE_TEST_EXISTS))
#ifdef _WIN32
	    mkdir (outdir);
#else
	    mkdir (outdir, 0700);
#endif
	bgPixmap = g_build_filename (outdir, "background.bin", NULL);
	g_free (outdir);

	/*  Use default background image, if none found in user's home dir.*/
	if (!g_file_test (bgPixmap, G_FILE_TEST_EXISTS)) {
		dname = games_runtime_get_directory (GAMES_RUNTIME_GAME_PIXMAP_DIRECTORY);
		defaultPixmap = g_build_filename (dname, "gnometris.svg", NULL);
		default_bgimage = true;
	}

	w = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title (GTK_WINDOW (w), _("Gnometris"));

	g_signal_connect (w, "delete_event", G_CALLBACK (gameQuit), this);
	gtk_drag_dest_set (w, GTK_DEST_DEFAULT_ALL, targets,
			   G_N_ELEMENTS(targets),
			   GDK_ACTION_MOVE);
	g_signal_connect (G_OBJECT (w), "drag_data_received",
			  G_CALLBACK (dragDrop), this);
	g_signal_connect (G_OBJECT (w), "focus_out_event",
			  G_CALLBACK (focusOut), this);

	line_fill_height = 0;
	line_fill_prob = 5;

	gtk_window_set_default_size (GTK_WINDOW (w), DEFAULT_WIDTH, DEFAULT_HEIGHT);
	games_conf_add_window (GTK_WINDOW (w), KEY_SAVED_GROUP);

	preview = new Preview ();
	field = new Field();
	field->setUseTarget (false);

	initOptions ();

	/* prepare menus */
	games_stock_init ();
	action_group = gtk_action_group_new ("MenuActions");
	gtk_action_group_set_translation_domain (action_group, GETTEXT_PACKAGE);
	gtk_action_group_add_actions (action_group, actions, G_N_ELEMENTS (actions), this);
	ui_manager = gtk_ui_manager_new ();
	gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);
	gtk_ui_manager_add_ui_from_string (ui_manager, ui_description, -1, NULL);
	accel_group = gtk_ui_manager_get_accel_group (ui_manager);
	gtk_window_add_accel_group (GTK_WINDOW (w), accel_group);

	new_game_action = gtk_action_group_get_action (action_group, "NewGame");
	pause_action = gtk_action_group_get_action (action_group, "Pause");
	resume_action = gtk_action_group_get_action (action_group, "Resume");
	scores_action = gtk_action_group_get_action (action_group, "Scores");
	end_game_action = gtk_action_group_get_action (action_group, "EndGame");
	preferences_action = gtk_action_group_get_action (action_group, "Preferences");

	games_stock_set_pause_actions (pause_action, resume_action);

	menubar = gtk_ui_manager_get_widget (ui_manager, "/MainMenu");

	GtkWidget * hb = gtk_hbox_new(FALSE, 0);

	vbox = gtk_vbox_new (FALSE, 0);
	gtk_container_add (GTK_CONTAINER (w), vbox);
	gtk_box_pack_start (GTK_BOX (vbox), menubar, FALSE, FALSE, 0);
	gtk_box_pack_start (GTK_BOX (vbox), hb, TRUE, TRUE, 0);

	aspect_frame = gtk_aspect_frame_new (NULL, 0.5, 0.5, (float) COLUMNS / (float) LINES, FALSE);
	gtk_frame_set_shadow_type (GTK_FRAME (aspect_frame), GTK_SHADOW_NONE);
	gtk_container_add (GTK_CONTAINER (aspect_frame), field->getWidget());

	gtk_widget_set_events(w, gtk_widget_get_events(w) |
						  GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);

	GtkWidget *vb1 = gtk_vbox_new(FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(vb1), 10);
	gtk_box_pack_start(GTK_BOX(vb1), aspect_frame, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(hb), vb1, TRUE, TRUE, 0);

	setupPixmap();

	g_signal_connect (w, "key_press_event", G_CALLBACK (keyPressHandler), this);
	g_signal_connect (w, "key_release_event", G_CALLBACK (keyReleaseHandler), this);

	GtkWidget *vb2 = gtk_vbox_new(FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(vb2), 10);
	gtk_box_pack_end(GTK_BOX(hb), vb2, 0, 0, 0);

	gtk_box_pack_start(GTK_BOX(vb2), preview->getWidget(), FALSE, FALSE, 0);

	scoreFrame = new ScoreFrame(cmdlineLevel);

	gtk_box_pack_end(GTK_BOX(vb2), scoreFrame->getWidget(), TRUE, FALSE, 0);
	high_scores = new HighScores ();

	setOptions ();

	themeList = NULL;

	gtk_widget_show(vbox);
	gtk_widget_show(hb);
	gtk_widget_show(vb1);
	gtk_widget_show(vb2);
	gtk_widget_show(aspect_frame);
	gtk_widget_show(field->getWidget());
	gtk_widget_show(preview->getWidget());
	scoreFrame->show();
	gtk_widget_show(w);

	gtk_action_set_sensitive(pause_action, FALSE);
	gtk_action_set_sensitive(end_game_action, FALSE);
	gtk_action_set_sensitive(preferences_action, TRUE);

	confNotifyID = g_signal_connect (games_conf_get_default (),
					 "value-changed",
					 G_CALLBACK (confNotify),
					 this);
}
示例#20
0
void GameBox::initGui()
{
  mOpenGLGraphics = new gcn::OpenGLGraphics();
  mOpenGLGraphics->setTargetPlane(mWidth, mHeight);
  mOpenGLImageLoader = new gcn::OpenGLSDLImageLoader();
  gcn::Image::setImageLoader(mOpenGLImageLoader);

  mSDLInput = new gcn::SDLInput();
//try/catch?  YES
  mFont = new gcn::ImageFont(Pathfinder::Image_Path+"techyfontbig2.png"," abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\"");
  mHighLightFont = new gcn::ImageFont(Pathfinder::Image_Path+"techyfontbighighlight.png",
                   " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\"");
  mWhiteFont = new gcn::ImageFont(Pathfinder::Image_Path+"techyfontwhite.png"," abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%@`'*#=[]\"");
  gcn::Widget::setGlobalFont(mWhiteFont);  //what is this line?

  mTop = new gcn::Container();
  mTop->setOpaque(false);
  mMain = new gcn::Container();
  mMain->setOpaque(false);
  mTop->add(mMain);

  mSingleplayButton = new FPSButton("PLAY DEMO 2.5",boombox);
  mOptionsButton = new FPSButton("OPTIONS",boombox);
  mAboutButton = new FPSButton("ABOUT",boombox);
  mQuitButton = new FPSButton("QUIT",boombox);

  mSingleplayButton->setHighLightFont(mHighLightFont);
  mSingleplayButton->adjustSize();
  mSingleplayButton->setActionEventId("play");
  mSingleplayButton->addActionListener(this);
  mSingleplayButton->setFont(mFont);
  mSingleplayButton->adjustSize();
  mMain->add(mSingleplayButton);/////////////
  mOptionsButton->setHighLightFont(mHighLightFont);
  mOptionsButton->adjustSize();
  mOptionsButton->setActionEventId("options");
  mOptionsButton->addActionListener(this);
  mOptionsButton->setFont(mFont);
  mOptionsButton->adjustSize();
  mMain->add(mOptionsButton);////////////
  mAboutButton->setHighLightFont(mHighLightFont);
  mAboutButton->adjustSize();
  mAboutButton->setActionEventId("about");
  mAboutButton->addActionListener(this);
  mAboutButton->setFont(mFont);
  mAboutButton->adjustSize();
  mMain->add(mAboutButton);/////////////
  mQuitButton->setHighLightFont(mHighLightFont);
  mQuitButton->adjustSize();
  mQuitButton->setActionEventId("quit");
  mQuitButton->addActionListener(this);
  mQuitButton->setFont(mFont);
  mQuitButton->adjustSize();
  mMain->add(mQuitButton);

	mWebLabel = new gcn::Label("www.icecubeflower.com");
	mWebLabel->setFont(mWhiteFont);
	mWebLabel->adjustSize();
	mMain->add(mWebLabel);

  //gcn::OpenGLImage* image;  //wtf?

  mBoxImage = gcn::Image::load("Data/Images/box.png");

  mGui = new gcn::Gui();
  mGui->setGraphics(mOpenGLGraphics);
  mGui->setInput(mSDLInput);

  mGui->setTop(mTop);

  initOptions();
  initAbout();

  mTop->setDimension(gcn::Rectangle(0, 0, mWidth, mHeight));
  mMain->setDimension(gcn::Rectangle(0, 0, mWidth, mHeight));
  mOptions->setDimension(gcn::Rectangle(0, 0, mWidth, mHeight));
  mAbout->setDimension(gcn::Rectangle(0, 0, mWidth, mHeight));

  mSingleplayButton->setPosition(mWidth/8, mHeight/8);
  mOptionsButton->setPosition(mWidth/8, mHeight/8+40);
  mAboutButton->setPosition(mWidth/8, mHeight/8+80);
  mQuitButton->setPosition(mWidth/8, mHeight/8 +120);
  mOptionsBoxIcon->setPosition(mWidth/2 - 300, mHeight/2 - 150);
  mAboutBoxIcon->setPosition(mWidth/2 - 300, mHeight/2 - 150);
  mOptionsLabel->setPosition(mWidth/2 + 150, mHeight/2 - 145);
  mAboutLabel->setPosition(mWidth/2 + 150, mHeight/2 - 145);
  mFullScreen->setPosition(mWidth/2 - 200, mHeight/2 -100);
  mResolution->setPosition(mWidth/2 - 90, mHeight/2 -70);
  mResolutionLabel->setPosition(mWidth/2 -200, mHeight/2-70);
  mOptionsBackButton->setPosition(mWidth/2 - 290, mHeight/2 + 180);
  mAboutBackButton->setPosition(mWidth/2 - 290, mHeight/2 + 180);

  mAboutText->setPosition(mWidth/2 - 285, mHeight/2 - 120);

  mWebLabel->setPosition(30, mHeight-30);
}
示例#21
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_all_mods = false;

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#ifdef USE_HOME_DIR
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standart_filenames();

    MAP_SHARING::setDefaults();

    // Process CLI arguments
    int saved_argc = --argc; // skip program name
    char **saved_argv = ++argv;

    while (argc) {
        if(std::string(argv[0]) == "--seed") {
            argc--;
            argv++;
            if(argc) {
                seed = djb2_hash((unsigned char *)argv[0]);
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--jsonverify") {
            argc--;
            argv++;
            verifyexit = true;
        } else if(std::string(argv[0]) == "--check-mods") {
            argc--;
            argv++;
            check_all_mods = true;
        } else if(std::string(argv[0]) == "--basepath") {
            argc--;
            argv++;
            if(argc) {
                PATH_INFO::init_base_path(std::string(argv[0]));
                PATH_INFO::set_standart_filenames();
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--userdir") {
            argc--;
            argv++;
            if (argc) {
                PATH_INFO::init_user_dir( argv[0] );
                PATH_INFO::set_standart_filenames();
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--username") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::setUsername(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--addadmin") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::addAdmin(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--adddebugger") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::addDebugger(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--shared") {
            argc--;
            argv++;
            MAP_SHARING::setSharing(true);
            MAP_SHARING::setCompetitive(true);
            MAP_SHARING::setWorldmenu(false);
        } else if(std::string(argv[0]) == "--competitive") {
            argc--;
            argv++;
            MAP_SHARING::setCompetitive(true);
        } else { // Skipping other options.
            argc--;
            argv++;
        }
    }
    while (saved_argc) {
        if(std::string(saved_argv[0]) == "--worldmenu") {
            saved_argc--;
            saved_argv++;
            MAP_SHARING::setWorldmenu(true);
        } else if(std::string(saved_argv[0]) == "--datadir") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("datadir", std::string(saved_argv[0]));
                PATH_INFO::update_datadir();
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--savedir") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("savedir", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--configdir") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("config_dir", std::string(saved_argv[0]));
                PATH_INFO::update_config_dir();
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--optionfile") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("options", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--keymapfile") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("keymap", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--autopickupfile") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("autopickup", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--motdfile") {
            saved_argc--;
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("motd", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else { // ignore unknown args.
            saved_argc--;
            saved_argv++;
        }
    }

    // setup debug loggind
#ifdef ENABLE_LOGGING
    setupDebug();
#endif
    // set locale to system default
    setlocale(LC_ALL, "");
#ifdef LOCALIZE
    const char *locale_dir;
#ifdef __linux__
    if (!FILENAMES["base_path"].empty()) {
        locale_dir = std::string(FILENAMES["base_path"] + "share/locale").c_str();
    } else {
        locale_dir = "lang/mo";
    }
#else
    locale_dir = "lang/mo";
#endif // __linux__

    bindtextdomain("cataclysm-dda", locale_dir);
    bind_textdomain_codeset("cataclysm-dda", "UTF-8");
    textdomain("cataclysm-dda");
#endif // LOCALIZE

    // ncurses stuff
    initOptions();
    load_options(); // For getting size options
#ifdef LOCALIZE
    setlocale(LC_ALL, OPTIONS["USE_LANG"].getValue().c_str());
#endif // LOCALIZE
    if (initscr() == NULL) { // Initialize ncurses
        DebugLog() << "initscr failed!\n";
        return 1;
    }
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
            debugmsg("Can't open or create %s. Check permissions.",
                     FILENAMES["user_dir"].c_str());
            exit_handler(-999);
        }
        g->load_static_data();
        if (verifyexit) {
            if(g->game_error()) {
                exit_handler(-999);
            }
            exit_handler(0);
        }
        if (check_all_mods) {
            // Here we load all the mods and check their
            // consistency (both is done in check_all_mod_data).
            g->init_ui();
            popup_nowait("checking all mods");
            g->check_all_mod_data();
            if(g->game_error()) {
                exit_handler(-999);
            }
            // At this stage, the mods (and core game data)
            // are find and we could start playing, but this
            // is only for verifying that stage, so we exit.
            exit_handler(0);
        }
    } catch(std::string &error_message) {
        if(!error_message.empty()) {
            debugmsg("%s", error_message.c_str());
        }
        exit_handler(-999);
    }

    // Now we do the actuall game

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#if (!(defined _WIN32 || defined WINDOWS))
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = exit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);
#endif

    bool quit_game = false;
    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}
示例#22
0
int main(int argc, char **argv)
{
    int OPT_N  = 4000000;
    int OPT_SZ = OPT_N * sizeof(float);

    printf("Initializing data...\n");

    float *callResult, *putResult, *stockPrice, *optionStrike, *optionYears;

    checkCuda( cudaMallocHost((void**)&callResult,     OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&putResult,      OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&stockPrice,     OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&optionStrike,   OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&optionYears,    OPT_SZ) );

    initOptions(OPT_N, stockPrice, optionStrike, optionYears);

    printf("Running Host Version...\n");

    StartTimer();

    BlackScholesLaunch_host(callResult, putResult, stockPrice, optionStrike,
                            optionYears, RISKFREE, VOLATILITY, OPT_N);

    printf("Option 0 call: %f\n", callResult[0]);
    printf("Option 0 put:  %f\n", putResult[0]);

    double ms = GetTimer();

    //Both call and put is calculated
    printf("Options count             : %i     \n", 2 * OPT_N);
    printf("\tBlackScholes() time    : %f msec\n", ms);
    printf("\t%f GB/s, %f GOptions/s\n",
           ((double)(5 * OPT_N * sizeof(float)) * 1E-9) / (ms * 1E-3),
           ((double)(2 * OPT_N) * 1E-9) / (ms * 1E-3));

    float *d_callResult, *d_putResult;
    float *d_stockPrice, *d_optionStrike, *d_optionYears;

    checkCuda( cudaMalloc    ((void**)&d_callResult,   OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_putResult,    OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_stockPrice,   OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_optionStrike, OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_optionYears,  OPT_SZ) );

    printf("Running Device Version...\n");

    StartTimer();
    cudaMemcpy(d_stockPrice, stockPrice, OPT_SZ, cudaMemcpyHostToDevice);
    cudaMemcpy(d_optionStrike, optionStrike, OPT_SZ, cudaMemcpyHostToDevice);
    cudaMemcpy(d_optionYears, optionYears, OPT_SZ, cudaMemcpyHostToDevice);

    BlackScholesLaunch_device(d_callResult, d_putResult, d_stockPrice, d_optionStrike,
                              d_optionYears, RISKFREE, VOLATILITY, OPT_N);

    cudaMemcpy(callResult, d_callResult, OPT_SZ, cudaMemcpyDeviceToHost);
    cudaMemcpy(putResult, d_putResult, OPT_SZ, cudaMemcpyDeviceToHost);

    printf("Option 0 call: %f\n", callResult[0]);
    printf("Option 0 put:  %f\n", putResult[0]);

    ms = GetTimer();

    //Both call and put is calculated
    printf("Options count             : %i     \n", 2 * OPT_N);
    printf("\tBlackScholes() time    : %f msec\n", ms);
    printf("\t%f GB/s, %f GOptions/s\n",
           ((double)(5 * OPT_N * sizeof(float)) * 1E-9) / (ms * 1E-3),
           ((double)(2 * OPT_N) * 1E-9) / (ms * 1E-3));

    checkCuda( cudaFree(d_stockPrice) );
    checkCuda( cudaFree(d_optionStrike) );
    checkCuda( cudaFree(d_optionYears) );
    checkCuda( cudaFreeHost(callResult) );
    checkCuda( cudaFreeHost(putResult) );
    checkCuda( cudaFreeHost(stockPrice) );
    checkCuda( cudaFreeHost(optionStrike) );
    checkCuda( cudaFreeHost(optionYears) );
}
示例#23
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
 int argc = __argc;
 char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
#ifdef ENABLE_LOGGING
  setupDebug();
#endif
 int seed = time(NULL);

// set locale to system default
 setlocale(LC_ALL, "");
#ifdef LOCALIZE
 bindtextdomain("cataclysm-dda", "lang/mo");
 bind_textdomain_codeset("cataclysm-dda", "UTF-8");
 textdomain("cataclysm-dda");
#endif

//args: world seeding only.
 argc--; argv++;
 while (argc){
  if(std::string(argv[0]) == "--seed"){
   argc--; argv++;
   if(argc){
    seed = djb2_hash((unsigned char*)argv[0]);
    argc--; argv++;
   }
  }
  else // ignore unknown args.
   argc--; argv++;
 }

// ncurses stuff
 initOptions();
 load_options(); // For getting size options
 initscr(); // Initialize ncurses
 #ifdef SDLTILES
 init_tiles();
 #endif // SDLTILES
 noecho();  // Don't echo keypresses
 cbreak();  // C-style breaks (e.g. ^C to SIGINT)
 keypad(stdscr, true); // Numpad is numbers
 init_colors(); // See color.cpp
// curs_set(0); // Invisible cursor
 set_escdelay(10); // Make escape actually responsive

 std::srand(seed);

 bool quit_game = false;
 g = new game;
 g->init_data();
 if(g->game_error())
  exit_handler(-999);
 g->init_ui();
 MAPBUFFER.set_game(g);
 if(g->game_error())
  exit_handler(-999);

 curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

 #if (!(defined _WIN32 || defined WINDOWS))
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = exit_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);
 #endif

 do {
  if(!g->opening_screen()) {
     quit_game = true;
  }
  while (!g->do_turn()) ;
  if (g->game_quit() || g->game_error())
   quit_game = true;
 } while (!quit_game);


 exit_handler(-999);

 return 0;
}
示例#24
0
static void options(void)
{
	show = SHOW_OPTIONS;

	initOptions(returnFromOptions);
}
示例#25
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
#ifdef ENABLE_LOGGING
    setupDebug();
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    // set locale to system default
    setlocale(LC_ALL, "");
#ifdef LOCALIZE
    bindtextdomain("cataclysm-dda", "lang/mo");
    bind_textdomain_codeset("cataclysm-dda", "UTF-8");
    textdomain("cataclysm-dda");
#endif

    //args: world seeding only.
    argc--;
    argv++;
    while (argc) {
        if(std::string(argv[0]) == "--seed") {
            argc--;
            argv++;
            if(argc) {
                seed = djb2_hash((unsigned char *)argv[0]);
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--jsonverify") {
            argc--;
            verifyexit = true;
        } else { // ignore unknown args.
            argc--;
        }
        argv++;
    }

    // ncurses stuff
    initOptions();
    load_options(); // For getting size options
    initscr(); // Initialize ncurses
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    bool quit_game = false;
    g = new game;
    g->init_data();
    if(g->game_error()) {
        exit_handler(-999);
    }
    if ( verifyexit ) {
        item_controller->check_itype_definitions();
        item_controller->check_items_of_groups_exist();
        MonsterGenerator::generator().check_monster_definitions();
        MonsterGroupManager::check_group_definitions();
        check_recipe_definitions();
        exit_handler(0);
    }

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#if (!(defined _WIN32 || defined WINDOWS))
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = exit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);
#endif

    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}
示例#26
0
int main(int argc, char *argv[])
{
	int i, npart;
	idxtype *part;
	float ncut=0;
	GraphType graph;
	char filename[256],outputFile[256];
	int wgtflag = 0, addSelfLoop=1, outputFileGiven=0, txtFormat=0 ;
	int randomInit = 0;
	idxtype minEdgeWeight = 0;
	Options opt;
	timer TOTALTmr, METISTmr, IOTmr;

	initOptions(&opt);

	if (argc < 2) {
		print_help(argv[0]);
		exit(0);
	}
	
	for (argv++; *argv != NULL; argv++){
	    if ((*argv)[0] == '-')
		{
			int temp;
	      	switch ((*argv)[1])
			{
			case 'b':
			case 'B':
			  opt.penalty_power=atof(*(++argv));
			  break;
			case 'i':
			case 'I':
			  opt.gamma=atof(*(++argv));
			  break;
			case 'o':
			case 'O':
			  strcpy(outputFile,*(++argv));
			  outputFileGiven=1;
			  break;
			case 'D'://quality threshold. This is a post-processing step proposed in SR-MCL. If you dont want post-processing (this is what original MLR-MCL, R-MCL, MCL do, please set "-d 0"  
			case 'd':
			  opt.quality_threshold = atof(*(++argv));
			  break;
			case 'w':
			case 'W':
		          opt.weighted_density = true; 
			  break;

			case 'c':
			case 'C':
			  opt.coarsenTo= atoi(*(++argv));
			  break;
			default:
			  printf("Invalid option %s\n", *argv);
			  print_help(argv[0]);
			  exit(0);
			}
		}
	    else
		{
	      strcpy(filename, *argv);
	    }
	}  

	if ( randomInit > 0 )
		InitRandom(time(NULL));
	else
		InitRandom(-1);

	cleartimer(TOTALTmr);
	cleartimer(METISTmr);
	cleartimer(IOTmr);

	starttimer(TOTALTmr);
	starttimer(IOTmr);

	ReadGraph(&graph, filename, &wgtflag, addSelfLoop, txtFormat);

	if ( opt.matchType == MATCH_UNSPECIFIED )
	{
//		opt.matchType = (graph.nvtxs>50000) ? MATCH_POWERLAW_FC :
//							MATCH_SHEMN;
		opt.matchType = MATCH_SHEMN;
	}
	
	stoptimer(IOTmr);

	if (graph.nvtxs <= 0) {
	  printf("Empty graph. Nothing to do.\n");
	  exit(0);
	}

	int noOfSingletons = 0; 
	GraphType *noSingletonGraph ;
	idxtype* nodeMap = lookForSingletons(&graph, &noOfSingletons);
	if ( noOfSingletons > 0 )
	{
		getSubgraph(&graph, nodeMap, graph.nvtxs-noOfSingletons, 
						wgtflag, &noSingletonGraph);
		GKfree((void**)&(graph.xadj), (void**)&(graph.adjncy), LTERM);
		if ( wgtflag&1 > 0 )
			GKfree( (void**)&(graph.adjwgt), LTERM);
//		free(graph.gdata);
		printf("Found %d singleton nodes in the", noOfSingletons);
		printf(" input graph. Removing them.\n");
	}

	if ( !outputFileGiven )
	{
		strcpy(outputFile, filename);

		sprintf(outputFile,"%s.c%d.i%1.1f.b%1.1f",outputFile,opt.coarsenTo,opt.gamma,opt.penalty_power);
	}
	
	printf("Input graph information ---------------------------------------------------\n");
	printf("  Name: %s, #Vertices: %d, #Edges: %d\n", filename, graph.nvtxs, graph.nedges/2);
	printf("Output shall be placed in the file %s\n",
	outputFile);
	fflush(stdout);

	part = idxmalloc(graph.nvtxs, "main: part");

	printf("------------------------------------------------\n");
	printf("Clustering....\n");
	fflush(stdout);
	starttimer(METISTmr);         //YK: main algorithm starts here!

	if ( noOfSingletons > 0 )
	{
		
		mlmcl(&(noSingletonGraph->nvtxs), noSingletonGraph->xadj, noSingletonGraph->adjncy,
			noSingletonGraph->vwgt,noSingletonGraph->adjwgt, &wgtflag, part, opt ); 
	}
	else	
	{
		mlmcl(&graph.nvtxs, graph.xadj, graph.adjncy,graph.vwgt,
			graph.adjwgt, &wgtflag, part, opt ); 
	}

	stoptimer(METISTmr); 

	printf("------------------------------------------------\n");
	if ( noOfSingletons > 0 )
	{
		npart=mapPartition(part,noSingletonGraph->nvtxs);
		ncut=ComputeNCut(noSingletonGraph, part,npart);
//		printf("In graph that does not include singletons,");
//		printf("No. of Clusters: %d, N-Cut value: %.2f\n",npart,ncut);


		idxtype *clusterSizes = histogram(part,
					graph.nvtxs-noOfSingletons, npart);

		int maxSize = clusterSizes[idxamax(npart, clusterSizes)];
		float avgClusterSize =
						(graph.nvtxs-noOfSingletons)*1.0/(npart);
		float balance =	(maxSize*1.0) /
				((graph.nvtxs-noOfSingletons)*1.0/npart);
		float stdDevn = stdDeviation(clusterSizes, npart);
		float avgNcut = ncut * 1.0/npart;
		float normStdDevn = stdDevn/avgClusterSize;

	// Warning: This computation only works if the singletons
	// have been placed in their own clusters. This works for
	// MLR-MCL, in other words, because it is guaranteed to
	// place singletons in their own clusters.
		printf("Output statistics for graph without singletons\n");
		printf("Clusters: %d N-Cut: %.3f", 
					npart, ncut);
		printf(" AvgN-Cut: %.3f Balance in cluster sizes: %.2f ",avgNcut,
					balance); 
		printf("Std_Deviation in cluster sizes: %.2f ", stdDevn);
		printf("Coefficient_of_Variation: %.2f\n", normStdDevn);

		free( clusterSizes );

		npart += noOfSingletons;
	//	ncut += noOfSingletons;
		printf("Output statistics for original graph\n");

		mapIndices(part, nodeMap, graph.nvtxs, npart-noOfSingletons);
	}
	else
	{
		npart=mapPartition(part,graph.nvtxs);
		ncut=ComputeNCut(&graph, part,npart);
	}

	idxtype* clusterSizes = histogram(part, graph.nvtxs, npart);
	int maxSize = clusterSizes[idxamax(npart, clusterSizes)];
	float avgClusterSize = (graph.nvtxs)*1.0/(npart);
	float balance = (maxSize*1.0)/(graph.nvtxs*1.0/npart);
	float stdDevn = stdDeviation(clusterSizes, npart);
	float avgNcut = ncut * 1.0/npart;
	float normStdDevn = stdDevn/avgClusterSize;
	
	printf("Clusters: %d N-Cut: %.3f AvgN-Cut: %.3f", npart,
						ncut, avgNcut );
	printf(" Balance in cluster sizes: %.2f Std.Deviation in cluster sizes: %.2f ",
				 balance, stdDevn);
	printf("Coefficient_of_Variation: %.2f\n", normStdDevn);

	starttimer(IOTmr);
	my_WritePartition(outputFile, part, graph.nvtxs, opt.gamma); 
	if ( noOfSingletons > 0 )
	{
		free(nodeMap);
		nodeMap = NULL;
	}

	printf("\nOutput is written to file: %s\n", outputFile);
	stoptimer(IOTmr);
	stoptimer(TOTALTmr);
	
	printf("\nTiming Information --------------------------------------------------\n");
	printf("  I/O:          \t\t %7.3f\n", gettimer(IOTmr));
	printf("  Partitioning: \t\t %7.3f   (MLR-MCL time)\n", gettimer(METISTmr));
	printf("  Total:        \t\t %7.3f\n", gettimer(TOTALTmr));
	printf("**********************************************************************\n");


	GKfree((void**)&graph.xadj, (void**)&graph.adjncy, (void**)&graph.vwgt, 
				(void**)&graph.adjwgt, (void**)&part, LTERM);
}  
示例#27
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_all_mods = false;

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    PATH_INFO::init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#if (defined USE_HOME_DIR || defined USE_XDG_DIR)
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standard_filenames();

    MAP_SHARING::setDefaults();
    {
        const char *section_default = nullptr;
        const char *section_map_sharing = "Map sharing";
        const char *section_user_directory = "User directories";
        const arg_handler first_pass_arguments[] = {
            {
                "--seed", "<string of letters and or numbers>",
                "Sets the random number generator's seed value",
                section_default,
                [&seed](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    const unsigned char *hash_input = (const unsigned char *) params[0];
                    seed = djb2_hash(hash_input);
                    return 1;
                }
            },
            {
                "--jsonverify", nullptr,
                "Checks the cdda json files",
                section_default,
                [&verifyexit](int, const char **) -> int {
                    verifyexit = true;
                    return 0;
                }
            },
            {
                "--check-mods", nullptr,
                "Checks the json files belonging to cdda mods",
                section_default,
                [&check_all_mods](int, const char **) -> int {
                    check_all_mods = true;
                    return 0;
                }
            },
            {
                "--basepath", "<path>",
                "Base path for all game data subdirectories",
                section_default,
                [](int num_args, const char **params) {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_base_path(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            },
            {
                "--shared", nullptr,
                "Activates the map-sharing mode",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setSharing(true);
                    MAP_SHARING::setCompetitive(true);
                    MAP_SHARING::setWorldmenu(false);
                    return 0;
                }
            },
            {
                "--username", "<name>",
                "Instructs map-sharing code to use this name for your character.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::setUsername(params[0]);
                    return 1;
                }
            },
            {
                "--addadmin", "<username>",
                "Instructs map-sharing code to use this name for your character and give you "
                "access to the cheat functions.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addAdmin(params[0]);
                    return 1;
                }
            },
            {
                "--adddebugger", "<username>",
                "Informs map-sharing code that you're running inside a debugger",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addDebugger(params[0]);
                    return 1;
                }
            },
            {
                "--competitive", nullptr,
                "Instructs map-sharing code to disable access to the in-game cheat functions",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setCompetitive(true);
                    return 0;
                }
            },
            {
                "--userdir", "<path>",
                "Base path for user-overrides to files from the ./data directory and named below",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_user_dir(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            }
        };

        // The following arguments are dependent on one or more of the previous flags and are run
        // in a second pass.
        const arg_handler second_pass_arguments[] = {
            {
                "--worldmenu", nullptr,
                "Enables the world menu in the map-sharing code",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setWorldmenu(true);
                    return true;
                }
            },
            {
                "--datadir", "<directory name>",
                "Sub directory from which game data is loaded",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("datadir", params[0]);
                    PATH_INFO::update_datadir();
                    return 1;
                }
            },
            {
                "--savedir", "<directory name>",
                "Subdirectory for game saves",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("savedir", params[0]);
                    return 1;
                }
            },
            {
                "--configdir", "<directory name>",
                "Subdirectory for game configuration",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("config_dir", params[0]);
                    PATH_INFO::update_config_dir();
                    return 1;
                }
            },
            {
                "--memorialdir", "<directory name>",
                "Subdirectory for memorials",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("memorialdir", params[0]);
                    return 1;
                }
            },
            {
                "--optionfile", "<filename>",
                "Name of the options file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("options", params[0]);
                    return 1;
                }
            },
            {
                "--keymapfile", "<filename>",
                "Name of the keymap file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("keymap", params[0]);
                    return 1;
                }
            },
            {
                "--autopickupfile", "<filename>",
                "Name of the autopickup options file within the configdir",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("autopickup", params[0]);
                    return 1;
                }
            },
            {
                "--motdfile", "<filename>",
                "Name of the message of the day file within the motd directory",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("motd", params[0]);
                    return 1;
                }
            },
        };

        // Process CLI arguments.
        const size_t num_first_pass_arguments =
            sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]);
        const size_t num_second_pass_arguments =
            sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]);
        int saved_argc = --argc; // skip program name
        const char **saved_argv = (const char **)++argv;
        while (argc) {
            if(!strcmp(argv[0], "--help")) {
                printHelpMessage(first_pass_arguments, num_first_pass_arguments,
                                 second_pass_arguments, num_second_pass_arguments);
                return 0;
            } else {
                bool arg_handled = false;
                for (size_t i = 0; i < num_first_pass_arguments; ++i) {
                    auto &arg_handler = first_pass_arguments[i];
                    if (!strcmp(argv[0], arg_handler.flag)) {
                        argc--;
                        argv++;
                        int args_consumed = arg_handler.handler(argc, (const char **)argv);
                        if (args_consumed < 0) {
                            printf("Failed parsing parameter '%s'\n", *(argv - 1));
                            exit(1);
                        }
                        argc -= args_consumed;
                        argv += args_consumed;
                        arg_handled = true;
                        break;
                    }
                }
                // Skip other options.
                if (!arg_handled) {
                    --argc;
                    ++argv;
                }
            }
        }
        while (saved_argc) {
            bool arg_handled = false;
            for (size_t i = 0; i < num_second_pass_arguments; ++i) {
                auto &arg_handler = second_pass_arguments[i];
                if (!strcmp(saved_argv[0], arg_handler.flag)) {
                    --saved_argc;
                    ++saved_argv;
                    int args_consumed = arg_handler.handler(saved_argc, saved_argv);
                    if (args_consumed < 0) {
                        printf("Failed parsing parameter '%s'\n", *(argv - 1));
                        exit(1);
                    }
                    saved_argc -= args_consumed;
                    saved_argv += args_consumed;
                    arg_handled = true;
                    break;
                }
            }
            // Ingore unknown options.
            if (!arg_handled) {
                --saved_argc;
                ++saved_argv;
            }
        }
    }

    if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
        printf("Can't open or create %s. Check permissions.\n",
               FILENAMES["user_dir"].c_str());
        exit(1);
    }

    setupDebug();

    if (setlocale(LC_ALL, "") == NULL) {
        DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '').";
    }

    // Options strings loaded with system locale
    initOptions();
    load_options();

    set_language(true);

    if (initscr() == NULL) { // Initialize ncurses
        DebugLog( D_ERROR, DC_ALL ) << "initscr failed!";
        return 1;
    }
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        g->load_static_data();
        if (verifyexit) {
            if(g->game_error()) {
                exit_handler(-999);
            }
            exit_handler(0);
        }
        if (check_all_mods) {
            // Here we load all the mods and check their
            // consistency (both is done in check_all_mod_data).
            g->init_ui();
            popup_nowait("checking all mods");
            g->check_all_mod_data();
            if(g->game_error()) {
                exit_handler(-999);
            }
            // At this stage, the mods (and core game data)
            // are find and we could start playing, but this
            // is only for verifying that stage, so we exit.
            exit_handler(0);
        }
    } catch(std::string &error_message) {
        if(!error_message.empty()) {
            debugmsg("%s", error_message.c_str());
        }
        exit_handler(-999);
    }

    // Now we do the actual game.

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#if (!(defined _WIN32 || defined WINDOWS))
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = exit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);
#endif

    bool quit_game = false;
    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}
示例#28
0
int main(int argc, char **argv)
{
    int OPT_N  = 4000000;
    int OPT_SZ = OPT_N * sizeof(float);

    BlackScholes bs;
               
    printf("Initializing data...\n");

    float *callResult, *putResult, *stockPrice, *optionStrike, *optionYears;
    
    checkCuda( cudaMallocHost((void**)&callResult,     OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&putResult,      OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&stockPrice,     OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&optionStrike,   OPT_SZ) );
    checkCuda( cudaMallocHost((void**)&optionYears,    OPT_SZ) );
    
    initOptions(OPT_N, stockPrice, optionStrike, optionYears);

    printf("Running Host Version...\n");

    StartTimer();
    
    // run BlackScholes operator on host
    bs(callResult, putResult, stockPrice, optionStrike, 
       optionYears, RISKFREE, VOLATILITY, OPT_N);

    printf("Option 0 call: %f\n", callResult[0]); 
    printf("Option 0 put:  %f\n", putResult[0]);

    double ms = GetTimer();

    //Both call and put is calculated
    printf("Options count             : %i     \n", 2 * OPT_N);
       printf("\tBlackScholes() time    : %f msec\n", ms);
    printf("\t%f GB/s, %f GOptions/s\n", 
           ((double)(5 * OPT_N * sizeof(float)) * 1E-9) / (ms * 1E-3),
           ((double)(2 * OPT_N) * 1E-9) / (ms * 1E-3));

    float *d_callResult, *d_putResult;
    float *d_stockPrice, *d_optionStrike, *d_optionYears;

    checkCuda( cudaMalloc    ((void**)&d_callResult,   OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_putResult,    OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_stockPrice,   OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_optionStrike, OPT_SZ) );
    checkCuda( cudaMalloc    ((void**)&d_optionYears,  OPT_SZ) );

    printf("Running Device Version...\n");

    StartTimer();
    
    // Launch Black-Scholes operator on device
#ifdef HEMI_CUDA_COMPILER
    cudaMemcpy(d_stockPrice, stockPrice, OPT_SZ, cudaMemcpyHostToDevice);
    cudaMemcpy(d_optionStrike, optionStrike, OPT_SZ, cudaMemcpyHostToDevice);
    cudaMemcpy(d_optionYears, optionYears, OPT_SZ, cudaMemcpyHostToDevice);

    hemi::launch(bs, 
                 d_callResult, d_putResult, d_stockPrice, d_optionStrike, 
                 d_optionYears, RISKFREE, VOLATILITY, OPT_N);

    cudaMemcpy(callResult, d_callResult, OPT_SZ, cudaMemcpyDeviceToHost);
    cudaMemcpy(putResult, d_putResult, OPT_SZ, cudaMemcpyDeviceToHost);
#else // demonstrates that "launch" goes to host when not compiled with NVCC
    hemi::launch(bs, 
                 callResult, putResult, stockPrice, optionStrike, 
                 optionYears, RISKFREE, VOLATILITY, OPT_N);
#endif

    printf("Option 0 call: %f\n", callResult[0]); 
    printf("Option 0 put:  %f\n", putResult[0]);

    ms = GetTimer();

    //Both call and put is calculated
    printf("Options count             : %i     \n", 2 * OPT_N);
       printf("\tBlackScholes() time    : %f msec\n", ms);
    printf("\t%f GB/s, %f GOptions/s\n", 
           ((double)(5 * OPT_N * sizeof(float)) * 1E-9) / (ms * 1E-3),
           ((double)(2 * OPT_N) * 1E-9) / (ms * 1E-3));

    checkCuda( cudaFree(d_stockPrice) );
    checkCuda( cudaFree(d_optionStrike) );
    checkCuda( cudaFree(d_optionYears) );
    checkCuda( cudaFreeHost(callResult) );
    checkCuda( cudaFreeHost(putResult) );
    checkCuda( cudaFreeHost(stockPrice) );
    checkCuda( cudaFreeHost(optionStrike) );
    checkCuda( cudaFreeHost(optionYears) );
}
示例#29
0
void plottingmacro_IVF()
{


  double fa = 0.46502;
  double fb = 0.53498;
  bool debug_ = true;

  //  std::string path("Nov10thFall11Plots/");
  //  std::string path("Nov10Fall1160MTopSlimPlots/");
  std::string path("Nov10Fall1160MTopIVFPlots_b/");

  if(debug_)
    std::cout << "Init the style form setTDRStyle" << std::endl;
  setTDRStyle();
  gStyle->SetErrorX(0.5);
  gROOT->ForceStyle();
  initOptions();
  

  if(debug_)
    std::cout << "Init the sample" << std::endl;
  //  std::vector<Sample> s = Nov10thDiJetPtUpdatedSlimHistos();
  //std::vector<Sample> s = Nov10Fall1160MTopSlimHistos();
  std::vector<Sample> s = Nov10Fall1160MTopIVFHistos();

  Sample data(1,"fake data","S1.root",0,true,1000);

  if(debug_)
    std::cout << "Init the data sample" << std::endl;
  for(size_t i=0;i< s.size();i++) if(s[i].data) {data=s[i];break;}

  if(debug_)
    std::cout << "Ls data sample" << std::endl;
  data.file()->ls(); 

  if(debug_)
    std::cout << "Init the mc sample" << std::endl;
  for(size_t i=0;i< s.size();i++) s[i].dump(1,fa,fb);

  std::vector<std::string> names;

  if(debug_)
    std::cout << "Get List of Keys" << std::endl;
  TList * subs = data.file()->GetListOfKeys();
  for(size_t i=0;i< subs->GetSize();i++)
    {
      TString nn = subs->At(i)->GetName();
      if( nn.Contains(TRegexp("Count*")) )
	continue;
      if(debug_)
	std::cout << "Get List of Keys in subdirs" << std::endl;
      TList * objs = ((TDirectoryFile *)data.file()->Get(subs->At(i)->GetName()))->GetListOfKeys();
      for(size_t j=0;j< objs->GetSize();j++)
	{
	  if(debug_)
	    std::cout << "Name = " << subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName() << std::endl;
	  names.push_back(subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName());
	  //      std::cout << subs->At(i)->GetName() << "/"  << objs->At(j)->GetName() << std::endl;
	  //TODO: select plots via regexp
	}
    }


  if(debug_)
    std::cout << "Starting plotting" << std::endl;

  std::string process;

  for(size_t i = 0 ; i < names.size() ; i++) 
    {
      
      std::map<std::string,TH1F *> grouped;
      TString n=names[i];
      //      if(!n.Contains(TRegexp("VlightRegionHZee/HiggsPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee/ZPtVlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("VlightRegionHZee"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZmmSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZeeSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVPureRegionZcombSV"))) continue;
      //      if(!n.Contains(TRegexp("ZSVTTbarPureRegionZcombSV"))) continue;
      if(!n.Contains(TRegexp("TTbarRegionZeeSVJets"))) continue;

      if(n.Contains(TRegexp("RegionHZcomb")))
	process = "Z(l^{+}l^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZmm")))
	process = "Z(#mu^{+}#mu^{-})H(b#bar{b})";
      if(n.Contains(TRegexp("RegionHZee")))
	process = "Z(e^{+}e^{-})H(b#bar{b})";

      if(debug_)
	std::cout << "Creating the Canvas" << std::endl;

      TCanvas *c = new TCanvas();
      c->SetLogy(false);
      c->SetTitle(names[i].c_str());

      if(debug_)
	std::cout << "Creating histograms" << std::endl;
  
      TH1F *hd = ((TH1F*)data.file()->Get(names[i].c_str()));
      hd->Sumw2();
      Options o=options[names[i]];
      //      hd->Rebin(o.rebin);
      hd->SetMarkerStyle(20);
      hd->GetXaxis()->SetLabelOffset(99);
      hd->SetYTitle(o.yaxis.c_str());
      double nbin = hd->GetNbinsX();
      double min_bin = hd->GetXaxis()->GetXmin();
      double max_bin = hd->GetXaxis()->GetXmax();
      TH1F *hmc = new TH1F("hmc","hmc", nbin, min_bin, max_bin);
      hmc->SetFillColor(kWhite);
      hmc->Sumw2();
      //      hmc->Rebin(o.rebin);

      if(debug_)
	std::cout << "Creating the THStack and Legend" << std::endl;
      THStack * sta = new THStack("sta",hd->GetTitle());
      TLegend * l = new TLegend(o.legendx1,o.legendy1,o.legendx2,o.legendy2); //0.7,0.1,0.9,0.6);
      l->SetFillColor(kWhite);
      l->SetBorderSize(0);
      l->SetTextFont(62);
      l->SetTextSize(0.03);
      if(debug_)
	std::cout << "Adding data to the legend" << std::endl;  
      l->AddEntry(hd, "Data","P");
      if(debug_)
	std::cout << "Adding MC to the THStack" << std::endl;  

      //with the proper trigger eff
      //      double SF[] = {1.01,1.03,1.00};
      //      double SF[] = {1.03,1.054,1.032};
      double SF[] = {1.0,1.0,1.0};

      if(debug_){
	for(int i = 0; i< 3; ++i)
	  std::cout << "SF [" << i << "] = " << SF[i] << std::endl;
      }

      double mcIntegral=0;
      for(size_t j=0;j< s.size() ;j++) 
	{ 
	  if(!s[j].data) 
	    {
	      if(debug_)
		std::cout << "Creating TH1F from file " << s[j].name << std::endl;  
	      TH1F * h = ((TH1F*)s[j].file()->Get(names[i].c_str()));
	      h->Sumw2();
	      if(debug_){
		std::cout << "TH1F created from file " << s[j].name << std::endl;  
		std::cout << "Scaling : " << s[j].scale(data.lumi(),fa,fb) << std::endl;  
		std::cout << "Scaling with SF : " << s[j].scale(data.lumi(),fa,fb,SF) << std::endl;  
		std::cout << "Histo integral before scaling = " << h->Integral() << std::endl;
	      }
	      h->Scale(s[j].scale(data.lumi(),fa,fb,SF));
	      if(debug_){
		std::cout << "Histo integral after scaling = " << h->Integral() << std::endl;
		std::cout << "Managing style... " << std::endl;  
	      }
	      h->SetLineWidth(1.);
	      h->SetFillColor(s[j].color);
	      h->SetLineColor(s[j].color);
	      //	      h->Rebin(options[names[i]].rebin);
	      if(debug_)
		std::cout << "Cloning and update legend " << std::endl;  
	      if(grouped.find(s[j].name) == grouped.end()){
		l->AddEntry(h,s[j].name.c_str(),"F");
	      }
	      std::cout << "Sample : " << s[j].name << " - Integral for plot " << names[i] << " = " << h->Integral(-10000,10000) << std::endl;
	      mcIntegral += h->Integral();
	      sta->Add(h);
	      hmc->Add(h);	      
	      //TO FIX grouped map
	      // sovrascrive histo con lo stesso nome tipo VV o ST etc...
	      grouped[s[j].name]=(TH1F *)h->Clone(("_"+names[i]).c_str());
	    }
	}

      if(debug_){
	std::cout << "Data total = " << hd->Integral() << std::endl;
	std::cout << "MC = " << mcIntegral << std::endl;
	std::cout << "Data/MC = " << hd->Integral()/mcIntegral << std::endl;
      }

      TPad * TopPad = new TPad("TopPad","Top Pad",0.,0.3,1.,1. ) ;
      TPad * BtmPad = new TPad("BtmPad","Bottom Pad",0.,0.,1.,0.313 ) ;
      TopPad->SetBottomMargin(0.02);
      BtmPad->SetTopMargin(0.0);
      BtmPad->SetFillStyle(4000);
      TopPad->SetFillStyle(4000);
      BtmPad->SetFillColor(0);
      BtmPad->SetBottomMargin(0.35);
      TopPad->Draw() ;
      BtmPad->Draw() ;
      std::cout << "hd maximum = " << hd->GetMaximum() << "  sta maximum = " << sta->GetMaximum() << std::endl;
      double maxY;
      if(hd->GetMaximum() > sta->GetMaximum()) maxY = (hd->GetMaximum())*1.5;
      else maxY = (sta->GetMaximum())*1.5;
      TopPad->cd();
      hd->Draw("E1X0");
      sta->Draw("sameHIST");
      hmc->Draw("sameE2");
      hmc->SetFillColor(2);
      hmc->SetMarkerSize(0);
      hmc->SetFillStyle(3013);
      hd->Draw("E1X0same");
      l->Draw("same");
      std::cout << "Set Maximum to = " << maxY << std::endl;
      hd->GetYaxis()->SetRangeUser(0.,maxY);
      hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);

      BtmPad->cd();
      std::cout << "Division" << std::endl;

      TH1D * divisionErrorBand = (TH1D*)(hmc)->Clone("divisionErrorBand");
      divisionErrorBand->Sumw2();
      divisionErrorBand->Divide(hmc);
      divisionErrorBand->Draw("E2");      
      divisionErrorBand->SetMaximum(2.49);
      divisionErrorBand->SetMinimum(0);
      divisionErrorBand->SetMarkerStyle(20);
      divisionErrorBand->SetMarkerSize(0.55);
      divisionErrorBand->GetXaxis()->SetTitleOffset(1.12);
      divisionErrorBand->GetXaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetXaxis()->SetTitleSize(0.5);
      divisionErrorBand->GetYaxis()->SetTitle("Data/MC");
      divisionErrorBand->GetYaxis()->SetLabelSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleSize(0.12);
      divisionErrorBand->GetYaxis()->SetTitleOffset(0.40);
      divisionErrorBand->GetYaxis()->SetNdivisions(505);
      //divisionErrorBand->UseCurrentStyle();
      divisionErrorBand->SetFillColor(2);
      divisionErrorBand->SetFillStyle(3001);
      divisionErrorBand->SetMarkerSize(0.);

      TH1D * division = (TH1D*)(hd)->Clone("division");
      division->Sumw2();
      division->Divide(hmc);
//       division->SetMaximum(2.5);
//       division->SetMinimum(0);
//       division->SetMarkerStyle(20);
//       division->SetMarkerSize(0.55);
//       division->GetXaxis()->SetLabelSize(0.12);
//       division->GetXaxis()->SetTitleSize(0.14);
//       division->GetYaxis()->SetLabelSize(0.10);
//       division->GetYaxis()->SetTitleSize(0.10);
//      division->GetYaxis()->SetTitle("Data/MC");
      Double_t min = division->GetXaxis()->GetXmin();
      Double_t max = division->GetXaxis()->GetXmax();
      division->Draw("E1X0same");

      TLine *line = new TLine(min, 1.0, max, 1.0);
      line->SetLineColor(kRed);
      line->Draw("same");
      
      TLegend * leg3 =new TLegend(0.50,0.86,0.69,0.96);
      leg3->AddEntry(divisionErrorBand,"MC uncert. (stat.)","f");
      leg3->SetFillColor(0);
      leg3->SetLineColor(0);
      leg3->SetShadowColor(0);
      leg3->SetTextFont(62);
      leg3->SetTextSize(0.06);
      leg3->Draw();

      TPaveText *pave = new TPaveText(0.15,0.85,0.32,0.96,"brNDC");
      pave->SetTextAlign(12);
      pave->SetLineColor(0);
      pave->SetFillColor(0);
      pave->SetShadowColor(0);
      //TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",histDt->Chi2Test(histCopyMC5,"UWCHI2/NDF"),histDt->KolmogorovTest(histCopyMC5))); // stat + sys
      TText *text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f",hd->Chi2Test(hmc,"UWCHI2/NDF"),hd->KolmogorovTest(hmc))); // stat only
      text->SetTextFont(62);
      text->SetTextSize(0.08);
      pave->Draw();

      TopPad->cd();
      TLatex latex;
      latex.SetNDC();
      latex.SetTextAlign(12);
      latex.SetTextSize(0.052);
      latex.DrawLatex(0.17,0.89,"CMS Preliminary");
      latex.SetTextSize(0.04);
      latex.DrawLatex(0.17,0.84,"#sqrt{s} = 7 TeV, L = 4.7 fb^{-1}");
      //      latex.DrawLatex(0.17,0.79,"Z(e^{+}e^{-})H(b#bar{b})");
      latex.DrawLatex(0.17,0.79,process.c_str());
      c->Update();
      std::string cName= hd->GetName();
      cName += "_bare.pdf";
      cName = path+cName;
      c->Print(cName.c_str(),"pdf");

//       std::cout << names[i] << " d: " <<  hd->Integral() << " ";
//       THStack * sta2 = new THStack("sta2",hd->GetTitle());
//       float tot=0;
//       float toterr2=0;

//       if(debug_)
// 	std::cout << "Putting the iterator in the for loop" << std::endl;
//       for(std::map<std::string,TH1F *>::reverse_iterator it=grouped.rbegin(); it!=grouped.rend();++it)
//  	{
// 	  if(debug_)
// 	    std::cout << "Using the iterator" << std::endl;
// 	  std::cout << (*it).first << " " << (*it).second->Integral() << " | " << std::endl ;
// 	  if((*it).second->GetEntries() > 0) {
// 	    float er=1.*sqrt((*it).second->GetEntries())/(*it).second->GetEntries()*(*it).second->Integral();
// 	    toterr2+=er*er;
// 	  }
// 	  tot+=(*it).second->Integral();
// 	  sta2->Add(it->second);
//  	}
//       std::cout << " Tot: " << tot << "+-" << sqrt(toterr2) <<  " SF: " << hd->Integral()/tot << std::endl;
//       TCanvas *c2 = new TCanvas();
//       c2->SetTitle(names[i].c_str());
//       std::cout << "hd maximum = " << hd->GetMaximum() << "  sta2 maximum = " << sta2->GetMaximum() << std::endl;
//       if(hd->GetMaximum() > sta2->GetMaximum()) maxY =  hd->GetBinContent(hd->GetMaximumBin()) * 1.5;
//       else maxY = ( sta2->GetMaximum())*1.5;
//       //      hd->Draw("E1"); 
//       sta2->Draw("PADSHIST");
//       //    hd->Draw("E1same");
//       //      l->Draw("same");
//       std::cout << "Set Maximum to = " << maxY << std::endl;
//       hd->GetYaxis()->SetRangeUser(0.,maxY);
//       hd->GetXaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
//       c2->Update();

//       std::string c2Name = hd->GetName();
//       c2Name = path+c2Name;
//       c2Name += "_norm.pdf";
//       c2->Print(c2Name.c_str(),"pdf");  

    }

}
FXint
GUILoadThread::run() {
    GUINet *net = 0;
    int simStartTime = 0;
    int simEndTime = 0;

    // remove old options
    OptionsCont &oc = OptionsCont::getOptions();
    oc.clear();
    // within gui-based applications, nothing is reported to the console
    MsgHandler::getErrorInstance()->report2cout(false);
    MsgHandler::getErrorInstance()->report2cerr(false);
    MsgHandler::getWarningInstance()->report2cout(false);
    MsgHandler::getWarningInstance()->report2cerr(false);
    MsgHandler::getMessageInstance()->report2cout(false);
    MsgHandler::getMessageInstance()->report2cerr(false);
    // register message callbacks
    MsgHandler::getMessageInstance()->addRetriever(myMessageRetriever);
    MsgHandler::getErrorInstance()->addRetriever(myErrorRetriever);
    MsgHandler::getWarningInstance()->addRetriever(myWarningRetriever);

    // try to load the given configuration
    if (!initOptions()) {
        // the options are not valid
        submitEndAndCleanup(net, simStartTime, simEndTime);
        return 0;
    }
    MsgHandler::initOutputOptions(true);
    if (!MSFrame::checkOptions()) {
        // the options are not valid
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        submitEndAndCleanup(net, simStartTime, simEndTime);
        return 0;
    }

    RandHelper::initRandGlobal();
    // try to load
    MSFrame::setMSGlobals(oc);
    net = new GUINet(new GUIVehicleControl(), new GUIEventControl(),
                     new GUIEventControl(), new GUIEventControl());
    GUIEdgeControlBuilder *eb = new GUIEdgeControlBuilder(GUIGlObjectStorage::gIDStorage);
    NLJunctionControlBuilder jb(*net, oc);
    GUIDetectorBuilder db(*net);
    GUIGeomShapeBuilder sb(*net, GUIGlObjectStorage::gIDStorage);
    GUITriggerBuilder tb;
    NLHandler handler("", *net, db, tb, *eb, jb, sb);
    tb.setHandler(&handler);
    NLBuilder builder(oc, *net, *eb, jb, db, handler);
    try {
        MsgHandler::getErrorInstance()->clear();
        MsgHandler::getWarningInstance()->clear();
        MsgHandler::getMessageInstance()->clear();
        if (!builder.build()) {
            throw ProcessError();
        } else {
            net->initGUIStructures();
            simStartTime = string2time(oc.getString("begin"));
            simEndTime = string2time(oc.getString("end"));
        }
    } catch (ProcessError &e) {
        if (std::string(e.what())!=std::string("Process Error") && std::string(e.what())!=std::string("")) {
            MsgHandler::getErrorInstance()->inform(e.what());
        }
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        delete net;
        net = 0;
#ifndef _DEBUG
    } catch (std::exception &e) {
        MsgHandler::getErrorInstance()->inform(e.what());
        delete net;
        net = 0;
#endif
    }
    if (net==0) {
        MSNet::clearAll();
    }
    delete eb;
    submitEndAndCleanup(net, simStartTime, simEndTime);
    return 0;
}