/*!

 */
bool
Strategy::init( CmdLineParser & cmd_parser )
{
    ParamMap param_map( "HELIOS_base options" );

    // std::string fconf;
    //param_map.add()
    //    ( "fconf", "", &fconf, "another formation file." );

    //
    //
    //

    if ( cmd_parser.count( "help" ) > 0 )
    {
        param_map.printHelp( std::cout );
        return false;
    }

    //
    //
    //

    cmd_parser.parse( param_map );

    return true;
}
/*!

 */
bool
SampleTrainer::initImpl( CmdLineParser & cmd_parser )
{
    bool result = TrainerAgent::initImpl( cmd_parser );

#if 0
    ParamMap my_params;

    std::string formation_conf;
    my_map.add()
        ( &conf_path, "fconf" )
        ;

    cmd_parser.parse( my_params );
#endif

    if ( cmd_parser.failed() )
    {
        std::cerr << "coach: ***WARNING*** detected unsupported options: ";
        cmd_parser.print( std::cerr );
        std::cerr << std::endl;
    }

    if ( ! result )
    {
        return false;
    }

    //////////////////////////////////////////////////////////////////
    // Add your code here.
    //////////////////////////////////////////////////////////////////

    return true;
}
Beispiel #3
0
int main(int argc, char** argv)
{
   cout << SectorVersionString << endl;

   SlaveConf global_conf;

   CmdLineParser clp;
   clp.parse(argc, argv);

   for (map<string, string>::const_iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "mh")
         global_conf.m_strMasterHost = i->second;
      else if (i->first == "mp")
         global_conf.m_iMasterPort = atoi(i->second.c_str());
      else if (i->first == "h")
      {
         global_conf.m_strHomeDir = i->second;
      }
      else if (i->first == "ds")
         global_conf.m_llMaxDataSize = atoll(i->second.c_str()) * 1024 * 1024;
      else if (i->first == "log")
         global_conf.m_iLogLevel = atoi(i->second.c_str());
      else
      {
         cout << "warning: unrecognized flag " << i->first << endl;
         help();
      }
   }

   string base = "";
   if (clp.m_vParams.size() == 1)
      base = clp.m_vParams.front();
   else if (clp.m_vParams.size() > 1)
      cout << "warning: wrong parameters ignored.\n";

   Slave s;

   if (s.init(&base, &global_conf) < 0)
   {
      cout << "error: failed to initialize the slave. check slave configurations.\n";
      return-1;
   }

   if (s.connect() < 0)
   {
      cout << "error: failed to connect to the master, or the connection request is rejected.\n";
      return -1;
   }

   s.run();

   s.close();

   return 0;
}
Beispiel #4
0
int main(int argc, char *argv[]) {
  QCoreApplication app (argc, argv);
  QTime time;
  int   duration;

 
  CmdLineParser cmd (app.arguments());
  CmdLineParser::Result res = cmd.parse();
  if (res == CmdLineParser::Help)
      return 0;
  else if (res == CmdLineParser::Error)
      return -1;

  QString filename = cmd.file();
  if (!QFile::exists ( filename )) {
    qCritical ("The file you specified doesn't exist!");
    exit (1);
  }
  
  Parser parser;
  bool ok;

  QFile file (filename);
  time.start();
  QVariant data = parser.parse (&file, &ok);
  duration = time.elapsed();
  if (!ok) {
    qCritical("%s:%i - Error: %s", filename.toLatin1().data(), parser.errorLine(), qPrintable(parser.errorString()));
    exit (1);
  }
  else {
    qDebug() << "Parsing of" << filename << "took" << duration << "ms";
    if (!cmd.quiet())
      qDebug() << data;
  }

  if (cmd.serialize()) {
    // serializer tests
    qDebug() << "Serializing... ";
    QJson::Serializer serializer;
    serializer.setIndentMode(cmd.indentationMode());
    time.start();
    QByteArray b = serializer.serialize(data);
    duration = time.elapsed();
    qDebug() << "Serialization took:" << duration << "ms";
    if (!cmd.quiet())
     qDebug() << b;
  }

  qDebug() << "JOB DONE, BYE";
  return 0;
}
 /**
  * Creates a command line parser initialized with default values.
  * @return a command line parser initialized with default values.
  */
 CmdLineParser get_cmd_line_parser() {
   CmdLineParser parser;
   parser.add_legal("-h --help -L --list -v --verbose -V --version -a --all -f --conformity --conformity-format --max-time");
   const int argc = 3;
   const char *defaults[argc] = {
     "--conformity-format=*Test|test_*|*",
     "-f=%p::%n - %m (%ts)%N(Registered at %f:%l)",
     "--max-time=1e+10",
   };
   parser.parse(argc, defaults);
   CPUNIT_ITRACE("EntryPoint - Default arguments:"<<parser.to_string());
   return parser;
 }
Beispiel #6
0
/*!

 */
bool
SamplePlayer::initImpl( CmdLineParser & cmd_parser )
{
    bool result = PlayerAgent::initImpl( cmd_parser );

    // read additional options
    result &= Strategy::instance().init( cmd_parser );

    rcsc::ParamMap my_params( "Additional options" );
#if 0
    std::string param_file_path = "params";
    param_map.add()
    ( "param-file", "", &param_file_path, "specified parameter file" );
#endif

    cmd_parser.parse( my_params );

    if ( cmd_parser.count( "help" ) > 0 )
    {
        my_params.printHelp( std::cout );
        return false;
    }

    if ( cmd_parser.failed() )
    {
        std::cerr << "player: ***WARNING*** detected unsuppprted options: ";
        cmd_parser.print( std::cerr );
        std::cerr << std::endl;
    }

    if ( ! result )
    {
        return false;
    }

    if ( ! Strategy::instance().read( config().configDir() ) )
    {
        std::cerr << "***ERROR*** Failed to read team strategy." << std::endl;
        return false;
    }

    if ( KickTable::instance().read( config().configDir() + "/kick-table" ) )
    {
        std::cerr << "Loaded the kick table: ["
                  << config().configDir() << "/kick-table]"
                  << std::endl;
    }

    return true;
}
Beispiel #7
0
int main(int argc, char** argv)
{
   cout << SectorVersionString << endl;

   Sector client;
   if (Utility::login(client) < 0)
      return -1;

   bool address = false;

   CmdLineParser clp;
   if (clp.parse(argc, argv) < 0)
   {
      help();
      return -1;
   }

   for (map<string, string>::const_iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "a")
         address = true;
      else
      {
         help();
         return -1;
      }
   }

   for (vector<string>::const_iterator i = clp.m_vSFlags.begin(); i != clp.m_vSFlags.end(); ++ i)
   {
      if (*i == "a")
         address = true;
      else
      {
         help();
         return -1;
      }
   }

   SysStat sys;
   int result = client.sysinfo(sys);
   if (result >= 0)
      print(sys, address);
   else
      Utility::print_error(result);

   Utility::logout(client);

   return result;
}
Beispiel #8
0
int main(int argc, char** argv)
{
   string sector_home;
   if (ConfLocation::locate(sector_home) < 0)
   {
      cerr << "no Sector information located; nothing to stop.\n";
      return -1;
   }

   string slaves_list = sector_home + "/conf/slaves.list";
   bool force = false;

   CmdLineParser clp;
   clp.parse(argc, argv);
   for (map<string, string>::const_iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "s")
         slaves_list = i->second;
      else
      {
         help();
         return 0;
      }
   }
   for (vector<string>::const_iterator i = clp.m_vSFlags.begin(); i != clp.m_vSFlags.end(); ++ i)
   {
      if ((*i == "f") || (*i == "force"))
         force = true;
      else
      {
         help();
         return 0;
      }
   }

   cout << "This will stop this master and all slave nodes by brutal forces. If you need a graceful shutdown, use ./tools/sector_shutdown.\n";

   if (!force)
   {
      cout << "Do you want to continue? Y/N:";
      char answer;
      cin >> answer;
      if ((answer != 'Y') && (answer != 'y'))
      {
         cout << "aborted.\n";
         return -1;
      }
   }
int main(int argc, char** argv)
{
   CmdLineParser clp;
   if (clp.parse(argc, argv) <= 0)
   {
      help();
      return -1;
   }

   int32_t id = 0;
   string addr;
   int32_t code = 0;
   for (map<string, string>::iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "i")
         id = atoi(i->second.c_str());
      else if (i->first == "d")
         addr = i->second;
      else if (i->first == "c")
         code = atoi(i->second.c_str());
      else
      {
         help();
         return -1;
      }
   }

   if (((id == 0) && (addr.c_str()[0] == 0))|| (code == 0))
   {
      help();
      return -1;
   }

   Session s;
   s.loadInfo("../conf/client.conf");

   Client c;
   if (c.init(s.m_ClientConf.m_strMasterIP, s.m_ClientConf.m_iMasterPort) < 0)
      return -1;

   string passwd = s.m_ClientConf.m_strPassword;
   if (s.m_ClientConf.m_strUserName != "root")
   {
      cout << "please input root password:";
      cin >> passwd;
   }
Beispiel #10
0
/*!

 */
bool
SampleCoach::initImpl( CmdLineParser & cmd_parser )
{
    bool result =CoachAgent::initImpl( cmd_parser );

#if 0
    ParamMap my_params;
    if ( cmd_parser.count( "help" ) )
    {
       my_params.printHelp( std::cout );
       return false;
    }
    cmd_parser.parse( my_params );
#endif

    if ( cmd_parser.failed() )
    {
        std::cerr << "coach: ***WARNING*** detected unsupported options: ";
        cmd_parser.print( std::cerr );
        std::cerr << std::endl;
    }

    if ( ! result )
    {
        return false;
    }

    //////////////////////////////////////////////////////////////////
    // Add your code here.
    //////////////////////////////////////////////////////////////////

    if ( config().useTeamGraphic() )
    {
        if ( config().teamGraphicFile().empty() )
        {
            M_team_graphic.createXpmTiles( team_logo_xpm );
        }
        else
        {
            M_team_graphic.readXpmFile( config().teamGraphicFile().c_str() );
        }
    }

    return true;
}
int main(int argc, char *argv[]) {
  QCoreApplication app (argc, argv);
 
  CmdLineParser cmd (app.arguments());
  CmdLineParser::Result res = cmd.parse();
  if (res == CmdLineParser::Help)
      return 0;
  else if (res == CmdLineParser::Error)
      return -1;


  QString filename = cmd.file();
  if (!QFile::exists ( filename )) {
    qCritical ("The file you specified doesn't exist!");
    exit (1);
  }
  
  Parser parser;
  bool ok;

  QFile file (filename);
  QVariant data = parser.parse (&file, &ok);
  if (!ok) {
    qCritical("%s:%i - Error: %s", filename.toLatin1().data(), parser.errorLine(), qPrintable(parser.errorString()));
    exit (1);
  }
  else {
    qDebug() << "json object successfully converted to:";
    qDebug() << data;
  }

  if (cmd.serialize()) {
    // serializer tests
    qDebug() << "Serialization output";
    QJson::Serializer serializer;
    serializer.setIndentMode(cmd.indentationMode());
    QByteArray b = serializer.serialize(data);
    qDebug() << b;
  }

  qDebug() << "JOB DONE, BYE";
  return 0;
}
Beispiel #12
0
int main(int argc, char * argv[])
{
	using namespace lyx;
	lyxerr.setStream(cerr);

	char const * const lyxsocket = getenv("LYXSOCKET");
	if (lyxsocket)
		cmdline::serverAddress = from_local8bit(lyxsocket);

	CmdLineParser args;
	args.helper["-h"] = cmdline::h;
	args.helper["-c"] = cmdline::c;
	args.helper["-g"] = cmdline::g;
	args.helper["-n"] = cmdline::n;
	args.helper["-a"] = cmdline::a;
	args.helper["-t"] = cmdline::t;
	args.helper["-p"] = cmdline::p;

	// Command line failure conditions:
	if ((!args.parse(argc, argv))
	   || (args.isset["-c"] && args.isset["-g"])
	   || (args.isset["-a"] && args.isset["-p"])) {
		cmdline::usage();
		return 1;
	}

	scoped_ptr<LyXDataSocket> server;

	if (!cmdline::serverAddress.empty()) {
		server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
		if (!server->connected()) {
			cerr << "lyxclient: " << "Could not connect to "
			     << to_utf8(cmdline::serverAddress) << endl;
			return EXIT_FAILURE;
		}
	} else {
		// We have to look for an address.
		// serverPid can be empty.
		FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
		FileNameList::const_iterator addr = addrs.begin();
		FileNameList::const_iterator end = addrs.end();
		for (; addr != end; ++addr) {
			// Caution: addr->string() is in filesystem encoding
			server.reset(new LyXDataSocket(*addr));
			if (server->connected())
				break;
			lyxerr << "lyxclient: " << "Could not connect to "
			     << addr->absFileName() << endl;
		}
		if (addr == end) {
			lyxerr << "lyxclient: No suitable server found."
			       << endl;
			return EXIT_FAILURE;
		}
		cerr << "lyxclient: " << "Connected to " << addr->absFileName() << endl;
	}

	int const serverfd = server->fd();

	IOWatch iowatch;
	iowatch.addfd(serverfd);

	// Used to read from server
	string answer;

	// Send greeting
	server->writeln("HELLO:" + to_utf8(cmdline::clientName));
	// wait at most 2 seconds until server responds
	iowatch.wait(2.0);
	if (iowatch.isset(serverfd) && server->readln(answer)) {
		if (prefixIs(answer, "BYE:")) {
			cerr << "lyxclient: Server disconnected." << endl;
			cout << answer << endl;
			return EXIT_FAILURE;
		}
	} else {
		cerr << "lyxclient: No answer from server." << endl;
		return EXIT_FAILURE;
	}

	if (args.isset["-g"] || args.isset["-c"]) {
		server->writeln(to_utf8(cmdline::singleCommand));
		iowatch.wait(2.0);
		if (iowatch.isset(serverfd) && server->readln(answer)) {
			cout << answer;
			if (prefixIs(answer, "ERROR:"))
				return EXIT_FAILURE;
			return EXIT_SUCCESS;
		} else {
			cerr << "lyxclient: No answer from server." << endl;
			return EXIT_FAILURE;
		}
	}

	// Take commands from stdin
	iowatch.addfd(0); // stdin
	bool saidbye = false;
	while ((!saidbye) && server->connected()) {
		iowatch.wait();
		if (iowatch.isset(0)) {
			string command;
			getline(cin, command);
			if (command.empty())
				continue;
			if (command == "BYE:") {
				server->writeln("BYE:");
				saidbye = true;
			} else {
				server->writeln("LYXCMD:" + command);
			}
		}
		if (iowatch.isset(serverfd)) {
			while(server->readln(answer))
				cout << answer << endl;
		}
	}

	return EXIT_SUCCESS;
}
Beispiel #13
0
int main(int argc, char* argv[]) {
	int ctThreads = tbb::task_scheduler_init::default_num_threads();
	tbb::task_scheduler_init init(ctThreads);
 	cout << "started tbb with " << ctThreads << " threads." << endl;

	//parser
    g_parser.addSwitch("--disjoint", "-d", "converts splitted part to disjoint meshes", "0");
    g_parser.addSwitch("--ringscalpel", "-r", "If the switch presents then the ring scalpel will be used");
    g_parser.addSwitch("--verbose", "-v", "prints detailed description.");
    g_parser.addSwitch("--input", "-i", "[filepath] set input file in vega format", "internal");
    //g_parser.addSwitch("--example", "-e", "[one, two, cube, eggshell] set an internal example", "two");
    //g_parser.addSwitch("--gizmo", "-g", "loads a file to set gizmo location and orientation", "gizmo.ini");

	if(g_parser.parse(argc, argv) < 0)
		exit(0);

	//file path
    g_strIniFilePath = AnsiStr(g_parser.value("input").c_str());
    if(FileExists(g_strIniFilePath))
        vloginfo("input file: %s.", g_strIniFilePath.cptr());
    else {
        vlogerror("Unable to find input filepath: [%s]", g_strIniFilePath.cptr());
        exit(1);
    }


    //GLFW LIB
    g_lpWindow = NULL;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit()) {
        vlogerror("Failed to init glfw");
        exit(EXIT_FAILURE);
    }

    /*
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    */

    g_lpWindow = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "tetcutter - Pourya Shirazian", NULL, NULL);
    if (!g_lpWindow)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(g_lpWindow);
    glfwSwapInterval(1);
    glfwSetKeyCallback(g_lpWindow, key_callback);
    glfwSetCursorPosCallback(g_lpWindow, mouse_motion_callback);
    glfwSetMouseButtonCallback(g_lpWindow, mouse_button_callback);
    glfwSetScrollCallback(g_lpWindow, scroll_callback);

	//init gl
	def_initgl();

	//Build Shaders for drawing the mesh
    IniFile ini(g_strIniFilePath, IniFile::fmRead);

    AnsiStr strRoot = ini.readString("system", "data");
    AnsiStr strShaderRoot = strRoot + "shaders/";
    AnsiStr strTextureRoot = strRoot + "textures/";
    AnsiStr strFontsRoot = strRoot + "fonts/";

	//convert mesh
// 	AnsiStr strNodesFP = strRoot + AnsiStr("data/meshes/matlab/nodes.txt");
// 	AnsiStr strFacesFP = strRoot + AnsiStr("data/meshes/matlab/faces.txt");
// 	AnsiStr strCellsFP = strRoot + AnsiStr("data/meshes/matlab/cells.txt");
// 	VolMeshIO::convertMatlabTextToVega(strNodesFP, strFacesFP, strCellsFP);


	//Load Shaders
	TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr());

	//Load Textures
	TheTexManager::Instance().add(strTextureRoot + "wood.png");
	TheTexManager::Instance().add(strTextureRoot + "spin.png");
	TheTexManager::Instance().add(strTextureRoot + "icefloor.png");
//	TheTexManager::Instance().add(strTextureRoot + "rendermask.png");
//	TheTexManager::Instance().add(strTextureRoot + "maskalpha.png");
//	TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png");

    vloginfo("Floor show is set to: [%d]", ini.readBool("visible", "floor"));

	//Ground and Room
	SGQuad* floor = new SGQuad(16.0f, 16.0f, TheTexManager::Instance().get("icefloor"));
	floor->setName("floor");
	floor->transform()->translate(vec3f(0, -0.1f, 0));
	floor->transform()->rotate(vec3f(1.0f, 0.0f, 0.0f), 90.0f);
    floor->setVisible(ini.readBool("visible", "floor"));
    TheEngine::Instance().add(floor);

	//Create Scalpel
	g_lpScalpel = new AvatarScalpel();
	g_lpScalpel->setVisible(false);

	g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin"));
	g_lpRing->setVisible(false);
    TheEngine::Instance().add(g_lpScalpel);
    TheEngine::Instance().add(g_lpRing);

    if(g_parser.value_to_int("ringscalpel") == 1) {
		g_lpAvatar = g_lpRing;
		g_lpRing->setVisible(true);
	}
	else {
		g_lpAvatar = g_lpScalpel;
		g_lpScalpel->setVisible(true);
	}

	g_lpAvatar->setTissue(g_lpTissue);
	g_lpAvatar->setOnCutFinishedEventHandler(cutFinished);
	TheGizmoManager::Instance().setFocusedNode(g_lpAvatar);	
    TheGizmoManager::Instance().readConfig(g_strIniFilePath);

    //setup engine
    TheEngine::Instance().readConfig(g_strIniFilePath);
    TheEngine::Instance().headers()->addHeaderLine("cell", "info");
    TheEngine::Instance().print();

	//reset cuttable mesh
    resetMesh();


    //mainloop
    while (!glfwWindowShouldClose(g_lpWindow))
    {
        //setup projection matrix
        int width = DEFAULT_WIDTH;
        int height = DEFAULT_HEIGHT;
        glfwGetFramebufferSize(g_lpWindow, &width, &height);
        def_resize(width, height);

        //draw frame
        draw();

        timestep();

        glfwSwapBuffers(g_lpWindow);
        glfwPollEvents();
    }

    //destroy window
    glfwDestroyWindow(g_lpWindow);
    glfwTerminate();

    exit(EXIT_SUCCESS);


	return 0;
}
 /**
  * Forward your program parameters directly from main to this function to start CPUnit.
  *  
  * @param argc The number of arguments, including the program name.
  * @param args The program arguments, including the program name.
  * @return 0 if all tests succeed, and >0 elsewise.
  */
 int main(const int argc, const char **args) {
   CmdLineParser parser = get_cmd_line_parser();
   parser.parse(argc-1, args+1);
   return main(parser);
 }
Beispiel #15
0
int main(int argc, char** argv)
{
   if (argc < 2)
   {
      help();
      return -1;
   }

   unsigned int thresh = 65536;
   int timeout = 3600 * 24; // default wait for one day

   CmdLineParser clp;
   if (clp.parse(argc, argv) < 0)
   {
      help();
      return -1;
   }

   for (map<string, string>::const_iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "w")
         thresh = atoi(i->second.c_str());
      else if (i->first == "t")
      {
         timeout = atoi(i->second.c_str());
         if (timeout < 0)
            timeout = INT_MAX;
      }
      else
      {
         help();
         return -1;
      }
   }

   Sector client;
   if (Utility::login(client) < 0)
      return -1;   

   list<string> filelist;

   for (vector<string>::iterator i = clp.m_vParams.begin(); i < clp.m_vParams.end(); ++ i)
   {
      vector<string> fl;
      fl.clear();

      bool wc = WildCard::isWildCard(*i);
      if (!wc)
      {
         SNode attr;
         if (client.stat(*i, attr) < 0)
         {
            cerr << "ERROR: source file does not exist.\n";
            return -1;
         }
         getFileList(*i, fl, client, thresh);
      }
      else
      {
         string path = *i;
         string orig = path;
         size_t p = path.rfind('/');
         if (p == string::npos)
            path = "/";
         else
         {
            path = path.substr(0, p);
            orig = orig.substr(p + 1, orig.length() - p);
         }

         vector<SNode> filelist;
         int r = client.list(path, filelist);
         if (r < 0)
            cerr << "ERROR: " << r << " " << SectorError::getErrorMsg(r) << endl;

         for (vector<SNode>::iterator i = filelist.begin(); i != filelist.end(); ++ i)
         {
            if (WildCard::match(orig, i->m_strName))
               getFileList(path + "/" + i->m_strName, fl, client, thresh);
         }
      }

      filelist.insert(filelist.end(), fl.begin(), fl.end());
   }

   int result = -1;

   timeval t;
   gettimeofday(&t, NULL);
   int exp_time = t.tv_sec + timeout;

   int interval = 1;
   int total = -1;
   int new_total = 0;

   while (!filelist.empty())
   {
      new_total = 0;

      for (list<string>::iterator i = filelist.begin(); i != filelist.end();)
      {
         SNode sn;
         if (client.stat(*i, sn) < 0)
         {
            cout << "file " << sn.m_strName << " is lost.\n";
            break;
         }

         int diff = (sn.m_iReplicaNum > int(thresh)) ? (thresh - sn.m_sLocation.size()) : (sn.m_iReplicaNum - int(sn.m_sLocation.size()));

         if (diff <= 0)
         {
            list<string>::iterator j = i;
            ++ i;
            filelist.erase(j);
         }
         else
         {
            if ((result = client.copy(*i, *i)) < 0)
            {
               Utility::print_error(result);

               list<string>::iterator j = i;
               ++ i;
               filelist.erase(j);

               break;
            }

            ++ i;
            new_total += diff;
         }
      }

      timeval curr_time;
      gettimeofday(&curr_time, NULL);
      if (curr_time.tv_sec > exp_time)
      {
         cout << "timeout.\n";
         break;
      }

      //TODO: sleep diff for the last time
      if (interval < exp_time - curr_time.tv_sec)
         sleep(interval);
      else
         sleep(exp_time - curr_time.tv_sec);

      // wait longer if no progress, otherwise continue to wait for 1 sec
      if ((total > 0) && (new_total < total))
      {
         total = new_total;
         interval = 1;
      }
      else if (interval < 16)
      {
         interval <<= 1;
      }
   }

   if (filelist.empty())
   {
      cout << "all files have enough replicas.\n";
      result = 0;
   }

   Utility::logout(client);

   return result;
}
Beispiel #16
0
int main(int argc, char** argv)
{
   CmdLineParser clp;
   if ((clp.parse(argc, argv) < 0) || (clp.m_mDFlags.size() != 1))
   {
      cerr << "usage #1: <your_application> | sector_pipe -d dst_file" << endl;
      cerr << "usage #2: sector_pipe -s src_file | <your_application>" << endl;
      return 0;
   }

   string option = clp.m_mDFlags.begin()->first;

   Sector client;
   if (Utility::login(client) < 0)
      return -1;

   timeval t1, t2;
   gettimeofday(&t1, 0);
   int64_t total_size = 0;

   SectorFile* f = client.createSectorFile();

   if (option == "d")
   {
      if (f->open(argv[2], SF_MODE::WRITE | SF_MODE::APPEND) < 0)
      {
         cerr << "ERROR: unable to open destination file." << endl;
         return -1;
      }

      int size = 1000000;
      char* buf = new char[size];
      int read_size = size;

      // read data from sdtin and write to Sector
      while(true)
      {
         read_size = read(0, buf, size);
         if (read_size <= 0)
            break;
         f->write(buf, read_size);
         total_size += read_size;
      }

      delete [] buf;
   }
   else if (option == "s")
   {
      if (f->open(argv[2], SF_MODE::READ) < 0)
      {
         cerr << "ERROR: unable to open source file." << endl;
         return -1;
      }

      int size = 1000000;
      char* buf = new char[size];
      int read_size = size;

      // read data from Sector and write to stdout
      while(!f->eof())
      {
         read_size = f->read(buf, size);
         if (read_size <= 0)
            break;
         total_size += read_size;
         write(1, buf, read_size);
      }

      delete [] buf;
   }

   f->close();
   client.releaseSectorFile(f);

   gettimeofday(&t2, 0);
   double throughput = total_size * 8.0 / 1000000.0 / ((t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1000000.0);

   cerr << "Pipeline accomplished! " << "AVG speed " << throughput << " Mb/s." << endl << endl ;

   Utility::logout(client);

   return 0;
}
Beispiel #17
0
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");

    CmdLineParser parser;
    parser << CmdLineItem("path", true, false, false, "Каталог для поиска дубликатов файлов");

    int result = parser.parse(argc, argv);
    switch(result)
    {
    case CmdLineParser::Error:
        qDebug() << (parser.getLastError() + "\n\n" + parser.getHelpString()).toStdString().c_str();
        return 0;
        break;
    case CmdLineParser::Help:
        qDebug() << parser.getHelpString().toStdString().c_str();
        return 0;
        break;
    }

    QElapsedTimer timer;
    timer.start();


    QString path = parser.at("path")->getValue().at(0);
    qDebug() << "Указанный каталог: " << path;

    QStringList files = Files::countDir(path, QStringList());
    qDebug() << "Найдено файлов: " << files.size();
    qDebug() << "Timer:" << timer.elapsed();

    QVector<MyFileInfo> fileInfoList;

    for(int i = 0 ; i < files.size(); i++)
    {
        fileInfoList.append(MyFileInfo(files[i]));
        fileInfoList.last().calcSize();
    }

    qDebug() << "Посчитаны размеры всех файлов";
    qDebug() << "Timer:" << timer.elapsed();

    qSort(fileInfoList.begin(), fileInfoList.end(), [](const MyFileInfo &_item1, const MyFileInfo &_item2)
    {
        return _item1.getFileSize() < _item2.getFileSize();
    });

    qDebug() << "Массив отсортирован по размеру";
    qDebug() << "Timer:" << timer.elapsed();

    for(int i = 1 ; i < fileInfoList.size(); i++)
    {
        if(fileInfoList[i].getFileSize() == fileInfoList[i - 1].getFileSize())
        {
            if(!fileInfoList[i].isHashPresent()) fileInfoList[i].calcHash();
            if(!fileInfoList[i - 1].isHashPresent()) fileInfoList[i - 1].calcHash();
            if(fileInfoList[i].getHash() == fileInfoList[i - 1].getHash())
            {
                if(fileInfoList[i].compareFiles(fileInfoList[i - 1]))
                {
                    qDebug() << fileInfoList[i].toString();
                    qDebug() << fileInfoList[i - 1].toString();
                    qDebug() << "------------------------\n";
                }
            }
        }
    }

    qDebug() << "Timer:" << timer.elapsed();
    qDebug() << "Завершено";

    return 0;
}
Beispiel #18
0
int main(int argc, char** argv)
{
   logger::config( "/tmp", "sector-download" );

   for( int arg = 0; arg < argc; ++arg )
      log().debug << argv[ arg ] << ' ';
   log().debug << std::endl;

   if (argc < 3)
   {
      help(argv[0]);
      log().error << "Invalid command-line syntax, exiting with rc = -1" << std::endl;
      return -1;
   }

   CmdLineParser clp;
   if (clp.parse(argc, argv) < 0)
   {
      help(argv[0]);
      log().error << "Invalid command-line syntax, exiting with rc = -1" << std::endl;
      return -1;
   }

   if (clp.m_vParams.size() < 2)
   {
      help(argv[0]);
      log().error << "Invalid command-line syntax, exiting with rc = -1" << std::endl;
      return -1;
   }

   bool encryption = false;
   bool resume = false;

   for (vector<string>::const_iterator i = clp.m_vSFlags.begin(); i != clp.m_vSFlags.end(); ++ i)
   {
      if (*i == "e")
         encryption = true;
      else if( *i == "smart" )
         resume = true;
      else
      {
         help(argv[0]);
         log().error << "Invalid command-line syntax, exiting with rc = -1" << std::endl;
         return -1;
      }
   }

   string newdir = *clp.m_vParams.rbegin();
   clp.m_vParams.erase(clp.m_vParams.begin() + clp.m_vParams.size() - 1);

   // check destination directory, which must exist
   SNode s;
   int r = LocalFS::stat(newdir, s);
   if ((r < 0) || !s.m_bIsDir)
   {
      cerr << "ERROR: destination directory does not exist.\n";
      log().error << "stat failed on destination directory, err = " << r << ", exiting with rc = -1" << std::endl;
      return -1;
   }

   // login to SectorFS
   Sector client;
   int rc = Utility::login(client);
   if (rc < 0)
   {
      cerr << "ERROR: failed to log in to sector\n";
      log().error << "Client login to master failed with err = " << rc << ", exiting with rc = -1" << std::endl;
      return -1;
   }

   // start downloading all files
   for (vector<string>::iterator i = clp.m_vParams.begin(); i != clp.m_vParams.end(); ++ i)
   {
      vector<string> fl;
      bool wc = WildCard::isWildCard(*i);
      if (!wc)
      {
         SNode attr;
         if ((rc = client.stat(*i, attr)) < 0)
         {
            cerr << "ERROR: source file does not exist.\n";
            log().error << "Failed to stat sector file " << *i << ", err = " << rc << std::endl;
            return -1;
         }
         getFileList(*i, fl, client);
      }
      else
      {
         string path = *i;
         string orig = path;
         size_t p = path.rfind('/');
         if (p == string::npos)
            path = "/";
         else
         {
            path = path.substr(0, p);
            orig = orig.substr(p + 1, orig.length() - p);
         }

         vector<SNode> filelist;
         int r = client.list(path, filelist);
         if (r < 0)
            cerr << "ERROR: " << r << " " << SectorError::getErrorMsg(r) << endl;

         for (vector<SNode>::iterator i = filelist.begin(); i != filelist.end(); ++ i)
         {
            if (WildCard::match(orig, i->m_strName))
               getFileList(path + "/" + i->m_strName, fl, client);
         }
      }

      string olddir;
      for (int j = i->length() - 1; j >= 0; -- j)
      {
         if (i->c_str()[j] != '/')
         {
            olddir = i->substr(0, j);
            break;
         }
      }
      size_t p = olddir.rfind('/');
      if (p == string::npos)
         olddir = "";
      else
         olddir = olddir.substr(0, p);

      for (vector<string>::iterator i = fl.begin(); i != fl.end(); ++ i)
      {
         string dst = *i;
         if (olddir.length() > 0)
            dst.replace(0, olddir.length(), newdir);
         else
            dst = newdir + "/" + dst;

         string localdir = dst.substr(0, dst.rfind('/'));

         // if localdir does not exist, create it
         if (LocalFS::stat(localdir, s) < 0)
         {
            for (unsigned int p = 1; p < localdir.length(); ++ p)
            {
               if (localdir.c_str()[p] == '/')
               {
                  string substr = localdir.substr(0, p);

                  if ((-1 == ::mkdir(substr.c_str(), S_IRWXU)) && (errno != EEXIST))
                  {
                     int errno_save = errno;
                     cerr << "ERROR: unable to create local directory " << substr << endl;
                     log().error << "Failed to create local directory " << substr << ", errno = " << errno_save << std::endl;
                     return -1;
                  }
               }
            }

            if ((-1 == ::mkdir(localdir.c_str(), S_IRWXU)) && (errno != EEXIST))
            {
               int errno_save = errno;
               cerr << "ERROR: unable to create local directory " << localdir << endl;
               log().error << "Failed to create local directory " << localdir << ", errno = " << errno_save << std::endl;
               break;
            }
         }

         if (!resume )
         {
            string fileName = *i;
            if( fileName.rfind( '/' ) != fileName.npos )
                fileName = fileName.substr( fileName.rfind( '/' ) + 1 );
            string destFile = localdir + '/' + fileName;
            if( LocalFS::stat( destFile, s ) >= 0 )
            {
                cout << "Destination directory already contains file '" << fileName << "', removing." << endl;
                log().debug << "Destination directory already contains file " << fileName << " and smart not specified, removing file" << std::endl;
                if( LocalFS::erase( destFile ) < 0 )
                {
                   int save_errno = errno;
                   cerr << "ERROR: could not remove destination file: " << strerror( save_errno ) << endl
                       << "NOT downloading file!" << endl;
                   log().error << "Failed to remove destination file " << fileName << ", aborting this file" << std::endl;
                   return -1;
                }
            }
         } 
         else
         {
            string fileName = *i;
            if( fileName.rfind( '/' ) != fileName.npos )
                fileName = fileName.substr( fileName.rfind( '/' ) + 1 );
            string destFile = localdir + '/' + fileName;
            if( LocalFS::stat( destFile, s ) >= 0 )
            {
                cout << "Destination directory already contains file '" << fileName << "', resuming partial download." << endl;
		log().debug << "Destination file already exists with size " << s.m_llSize << ", resuming partial download" << std::endl;
            }
         }

         if (download(i->c_str(), localdir.c_str(), client, encryption) < 0)
         {
            // calculate total available disk size
            int64_t availdisk = 0;
            LocalFS::get_dir_space(localdir, availdisk);
            if (availdisk <= 0)
            {
               // if no disk space svailable, no need to try any more
               cerr << "insufficient local disk space. quit.\n";
               log().error << "Insufficient disk space" << std::endl;
               Utility::logout(client);
            }
            return -1;
         }
      }
   }

   Utility::logout(client);
   log().debug << "Download completed successfully" << std::endl;
   return 0;
}
Beispiel #19
0
int main(int argc, char** argv)
{
   if (argc < 3)
   {
      help();
      return -1;
   }

   CmdLineParser clp;
   if (clp.parse(argc, argv) < 0)
   {
      help();
      return -1;
   }

   if (clp.m_vParams.size() < 2)
   {
      help();
      return -1;
   }

   int replica_num = 1;
   string ip = "";
   string cluster = "";
   int parallel = 1;  // concurrent uploading multiple files

   bool encryption = false;
   bool smart = false;

   for (map<string, string>::const_iterator i = clp.m_mDFlags.begin(); i != clp.m_mDFlags.end(); ++ i)
   {
      if (i->first == "n")
         replica_num = atoi(i->second.c_str());
      else if (i->first == "a")
         ip = i->second;
      else if (i->first == "c")
         cluster = i->second;
      else if (i->first == "p")
         parallel = atoi(i->second.c_str());
      else
      {
         help();
         return -1;
      }
   }

   for (vector<string>::const_iterator i = clp.m_vSFlags.begin(); i != clp.m_vSFlags.end(); ++ i)
   {
      if (*i == "e")
         encryption = true;
      else if (*i == "smart" )
         smart = true;
      else
      {
         help();
         return -1;
      }
   }

   Sector client;
   if (Utility::login(client) < 0)
      return -1;

   string dstdir = *clp.m_vParams.rbegin();
   clp.m_vParams.pop_back();
   
   SNode attr;
   int r = client.stat(dstdir, attr);
   if ((r < 0) || (!attr.m_bIsDir))
   {
      cerr << "destination directory on Sector does not exist.\n";
      Utility::logout(client);
      return -1;
   }

   bool success = true;

   // upload multiple files/dirs
   for (vector<string>::const_iterator param = clp.m_vParams.begin(); param != clp.m_vParams.end(); ++ param)
   {
      string prefix = "";

      vector<string> fl;
      bool wc = WildCard::isWildCard(*param);
      if (!wc)
      {
         SNode s;
         if (LocalFS::stat(*param, s) < 0)
         {
            cerr << "ERROR: source file does not exist.\n";
            return -1;
         }

         if (s.m_bIsDir)
            prefix = *param;
         else
         {
            size_t pos = param->rfind('/');
            if (pos != string::npos)
               prefix = param->substr(0, pos);
         }

         getFileList(*param, fl);
      }
      else
      {
         size_t pos = param->rfind('/');
         if (pos != string::npos)
            prefix = param->substr(0, pos);

         string path = *param;
         string orig = path;
         size_t p = path.rfind('/');
         if (p == string::npos)
         {
            path = ".";
         }
         else
         {
            path = path.substr(0, p);
            orig = orig.substr(p + 1, orig.length() - p);
         }

         // as this is a wildcard, list all files in the current dir, choose those matched ones
         vector<SNode> curr_fl;
         if (LocalFS::list_dir(path, curr_fl) < 0)
            return -1;

         for (vector<SNode>::iterator s = curr_fl.begin(); s != curr_fl.end(); ++ s)
         {
            // skip "." and ".."
            if ((s->m_strName == ".") || (s->m_strName == ".."))
               continue;

            if (WildCard::match(orig, s->m_strName))
            {
               if (path == ".")
                  getFileList(s->m_strName, fl);
               else
                  getFileList(path + "/" + s->m_strName, fl);
            }
         }
      }

      // upload all files in the file list
      for (vector<string>::const_iterator i = fl.begin(); i != fl.end(); ++ i)
      {
         // process directory name change: /src/mydata -> /dst/mydata
         string dst = *i;
         if (prefix.length() > 0)
            dst.replace(0, prefix.length(), dstdir + "/");
         else
            dst = dstdir + "/" + dst;

         SNode s;
         if (LocalFS::stat(*i, s) < 0)
            continue;

         if (s.m_bIsDir)
            client.mkdir(dst);
         else
         {
   
            int result = upload(i->c_str(), dst.c_str(), client, replica_num, ip, cluster, encryption, smart);
            if ((result == SectorError::E_CONNECTION) ||
                (result == SectorError::E_BROKENPIPE))
            {
               // connection fail, retry once.
               result = upload(i->c_str(), dst.c_str(), client, replica_num, ip, cluster, encryption, smart);
            }
 
            if (result < 0)
            {
               // failed, remove the file in Sector.
               client.remove(dst);
               success = false;
               Utility::logout(client);
               return -1;
            }
         }
      }
   }

   Utility::logout(client);
   return success ? 0 : -1;
}
int main(int argc, char* argv[]) {
	cout << "Cutting tets" << endl;

	g_parser.add_option("input", "[filepath] set input file in vega format",
			Value(AnsiStr("internal")));
	g_parser.add_toggle("ringscalpel", "If the switch presents then the ring scalpel will be used");
	g_parser.add_option("example",
			"[one, two, cube, eggshell] set an internal example",
			Value(AnsiStr("two")));
	g_parser.add_option("gizmo",
			"loads a file to set gizmo location and orientation",
			Value(AnsiStr("gizmo.ini")));

	if (g_parser.parse(argc, argv) < 0)
		exit(0);

	//file path
	g_strFilePath = ExtractFilePath(GetExePath()) + g_parser.value<AnsiStr>("input");
	if (FileExists(g_strFilePath))
		LogInfoArg1("input file: %s.", g_strFilePath.cptr());
	else
		g_strFilePath = "";

	//Initialize app
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
	glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	glutCreateWindow("SoftRigidDynamics - Pourya Shirazian");
	glutDisplayFunc(draw);
	glutReshapeFunc(def_resize);
	glutMouseFunc(MousePress);
	glutPassiveMotionFunc(MousePassiveMove);
	glutMotionFunc(MouseMove);
	glutMouseWheelFunc(MouseWheel);
	glutKeyboardFunc(NormalKey);
	glutSpecialFunc(SpecialKey);
	glutCloseFunc(closeApp);
	glutIdleFunc(timestep);

	def_initgl();

	//Build Shaders for drawing the mesh
	AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath()));
	AnsiStr strShaderRoot = strRoot + "data/shaders/";
	AnsiStr strMeshRoot = strRoot + "data/meshes/";
	AnsiStr strTextureRoot = strRoot + "data/textures/";

	AnsiStr strLeftPial = strMeshRoot + "brain/pial_Full_obj/lh.pial.obj";
	AnsiStr strRightPial = strMeshRoot + "brain/pial_Full_obj/rh.pial.obj";

	//Load Shaders
	TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr());

	//Load Textures
	TheTexManager::Instance().add(strTextureRoot + "wood.png");
	TheTexManager::Instance().add(strTextureRoot + "rendermask.png");
	TheTexManager::Instance().add(strTextureRoot + "maskalpha.png");
	TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png");
	TheTexManager::Instance().add(strTextureRoot + "spin.png");

	//Ground and Room
	//TheSceneGraph::Instance().addFloor(32, 32, 0.5f);
	TheSceneGraph::Instance().addSceneBox(AABB(vec3f(-10, -10, -16), vec3f(10, 10, 16)));


	//floor
	Geometry g;
	g.addCube(vec3f(-8, -2.0, -8), vec3f(8, -1.8, 8));
	g.addPerVertexColor(vec4f(0.5, 0.5, 0.5, 1));
	SGBulletRigidMesh* floor = new SGBulletRigidMesh();
	floor->setup(g, 0.0);
	floor->setName("floor");
	TheSceneGraph::Instance().addRigidBody(floor);


	//create rigid bodies
	/*
	Geometry g1;
	g1.addCube(vec3f(0.0, 0.0, 0.0), 1.0);
	g1.addPerVertexColor(vec4f(0, 0, 1, 1));

	for(int i=0; i < 8; i ++) {
		for(int j=0; j < 8; j++) {
			g1.colors().clear();

			float r = RandRangeT<float>(0.0, 1.0);
			float g = RandRangeT<float>(0.0, 1.0);
			float b = RandRangeT<float>(0.0, 1.0);

			g1.addPerVertexColor(vec4f(r, g, b, 1.0f));
			SGBulletRigidMesh* acube = new SGBulletRigidMesh();
			acube->transform()->setTranslate(vec3f(i-3, 10.0, j-3));
			acube->setup(g1, 1.0);
			TheSceneGraph::Instance().addRigidBody(acube);
		}
	}
	*/


	//Scalpel
	g_lpScalpel = new AvatarScalpel();
	g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin"));
	TheSceneGraph::Instance().add(g_lpScalpel);
	TheSceneGraph::Instance().add(g_lpRing);

	if(g_parser.value<int>("ringscalpel")) {
		g_lpAvatar = g_lpRing;
		g_lpScalpel->setVisible(false);
	}
	else {
		g_lpAvatar = g_lpScalpel;
		g_lpRing->setVisible(false);
	}

	g_lpAvatar->setTissue(g_lpTissue);
	g_lpAvatar->setOnCutFinishedEventHandler(finishedcut);
	TheGizmoManager::Instance().setFocusedNode(g_lpAvatar);

	//load gizmo manager file
	AnsiStr strGizmoFP = g_parser.value<AnsiStr>("gizmo");
	TheGizmoManager::Instance().readConfig(strGizmoFP);


	resetMesh();

	//render mask
//	SGRenderMask* renderMask = new SGRenderMask(TheTexManager::Instance().get("maskalpha"));
//	renderMask->setName("rendermask");
//	TheSceneGraph::Instance().add(renderMask);

	glutMainLoop();

	return 0;
}