Ejemplo n.º 1
0
int main()
{
	printf("Hello");
	unsigned char b;
	for(lset(b,1);lget(b)<=(grid*grid);lset(b,(lget(b)+1)))
		for(rset(b,1);rget(b)<=(grid*grid);rset(b,(rget(b)+1)))
			if(lget(b)%grid != rget(b)%grid)
				printf("A=%d, B=%d\n", lget(b),rget(b));
	return 0;
}
Ejemplo n.º 2
0
/**
 * Initializes the SMTP communications by sending the EHLO
 * If EHLO errors out, it will try the HELO command.
 *
 * Params
 * 	sd - Socket descriptor
 * 	domain - Your domain name.
 *
 * Return
 * 	- ERROR
 * 	- SUCCESS
 */
int
smtpInit(dsocket *sd, const char *domain)
{
	int retval;

	printProgress("Init connection...");
	retval = init(sd);
	if (retval == ERROR) {
		return retval;
	}

	printProgress("Greeting the SMTP server...");
	retval = ehlo(sd, domain);
	if (retval == ERROR) {
		/*
		 * Per RFC, if ehlo error's out, you can
		 * ignore the error, RSET and try a 
		 * regular helo.
		 */
		rset(sd);
		retval = helo(sd, domain);
	}

	return retval;
}
Ejemplo n.º 3
0
MySQL_Warning *
loadMysqlWarnings(sql::Connection * connection, unsigned int warningsCount)
{
  MySQL_Warning * first = NULL, * current = NULL;
  SQLString state;

  if (warningsCount >0 && connection != NULL) {
    boost::scoped_ptr< sql::Statement > stmt(connection->createStatement());
    boost::scoped_ptr< sql::ResultSet > rset(stmt->executeQuery("SHOW WARNINGS"));

    while (rset->next()) {
      // 1 - Level
      // 2 - Code
      // 3 - Message
      int32_t errCode = rset->getInt(2);

      if (current == NULL) {
        first = current = new MySQL_Warning(sql::SQLString(rset->getString(3)), errCode2SqlState(errCode, state), errCode);
      } else {
        MySQL_Warning * tmp= new MySQL_Warning(sql::SQLString(rset->getString(3)), errCode2SqlState(errCode, state), errCode);
        current->setNextWarning(tmp);
        current= tmp;
      }
    }
  }

  return first;
}
/* {{{ MySQL_Connection::getSchema() -I- */
sql::SQLString
MySQL_Connection::getSchema()
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getSchema");
	checkClosed();
	boost::scoped_ptr< sql::Statement > stmt(createStatement());
	boost::scoped_ptr< sql::ResultSet > rset(stmt->executeQuery("SELECT DATABASE()")); //SELECT SCHEMA()
	rset->next();
	return rset->getString(1);
}
Ejemplo n.º 5
0
// A test function.
void SQLiteDatabase::test()
{
//  Sample usage code follows...
	std::string strFileName = "sqlite3.txt";	
	SQLiteDatabase db;	
	try	{
	Verbose::out(1, "*");
	Verbose::out(1, "Create/Open database: sqlite3.txt");
	db.open(strFileName);
	SQLiteRecordset rset(db);

	Verbose::out(1, "create table Test1 (Id int primary key, Name varchar(255))");
	db.execute("create table Test1 (Id int primary key, Name varchar(255))");
	Verbose::out(2, "create table Test1 (Id int primary key, Name varchar(255))");
	db.execute("create table Test2 (Id int primary key, Name varchar(255))");
	
	Verbose::out(1, "Begin transaction...");
	db.beginTransaction();
	for (int iIndex = 1; (iIndex < 10); iIndex++)
	{
		std::string strSQL = "insert into Test1 values (" + ::getInt(iIndex) + ", 'Test1-" + ::getInt(iIndex) + "')";
		Verbose::out(1, "\t" + strSQL);
		db.execute(strSQL);
	}
	for (int iIndex = 1; (iIndex < 10); iIndex++)
	{
		std::string strSQL = "insert into Test2 values (" + ::getInt(iIndex) + ", 'Test2-" + ::getInt(iIndex) + "')";
		Verbose::out(1, "\t" + strSQL);
		db.execute(strSQL);
	}
	Verbose::out(1, "Commit transaction...");
	db.commitTransaction();
	
	Verbose::out(1, "select Test1.id, Test1.Name, Test2.Name from Test1, Test2 where Test1.Id = Test2.id");
	rset.open("select Test1.id, Test1.Name, Test2.Name from Test1, Test2 where Test1.Id = Test2.id");
	while (rset.fetch())
	{
		int iID = rset.getInteger(0);
		std::string strName = rset.getString(1);
		std::string strName2 = rset.getString(2);
		Verbose::out(1, "\tfetched: " + ::getInt(iID) + ", " + strName + ", " + strName2);
	}
	rset.close();	
	
	Verbose::out(1, "drop table Test1");
	db.execute("drop table Test1");
	Verbose::out(1, "drop table Test2");
	db.execute("drop table Test2");
	
	Verbose::out(1, "Closing SQLite database");
	db.close();
	Verbose::out(1, "*");
	} catch (SQLiteException& e) {db.rollbackTransaction(); db.close(); Verbose::out(1, e.getMessage());} 
//  End sample usage code
}
Ejemplo n.º 6
0
/** read_back_view_ddl()
 
 Load back VIEW code from the database for everything we created, so that we know how it was normalized.

 This will go through the whole catalog and read the SQL definition for each view. This is needed because
 the server stores the view definition in a canonical form, which is quite different from what the user
 types (not only formatting is stripped, but object names are expanded and expressions are rewritten).
 That makes it impossible for us to synchronize by comparing the definition in the model with the
 definition in the server. So we need to store the server version of the view right after we create it in
 there and a snapshot of the view that was used to create that view. 
 
 During synchronization, we can detect changes in the model by comparing the model version of the snapshot with 
 the model SQL definition and detect server changes by comparing the server version of the definition with 
 the snapshot for the server. We need to do that separately for every target server that synchronization is 
 used with (using the db.SyncProfile object).
 */
void Db_plugin::read_back_view_ddl()
{
  Db_objects_setup *setup= db_objects_setup_by_type(dbotView);
  setup->reset();

  _grtm->get_grt()->send_info(std::string("Fetching back view definitions in final form."));

  _grtm->get_grt()->send_progress(0.0, std::string("Fetching back view definitions in final form."));

  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());
  std::list<Db_obj_handle> db_objects;

  float total_views = 0;

  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    total_views += schema->views().count();
  }
  if (total_views == 0)
  {
    _grtm->get_grt()->send_progress(1.0, "Finished.");
    _grtm->get_grt()->send_info("Nothing to fetch");
    return;
  }

  int current_view = 0;
  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    for (size_t vc = schema->views().count(), v = 0; v < vc; ++v)
    {
      db_ViewRef view(schema->views()[v]);

      _grtm->get_grt()->send_progress((current_view / total_views),
                                      std::string("Fetch back database view code for ").append(schema->name()).append(".").append(view->name()));
      std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", *schema->name(), "view", true, *view->name()));

      // take a snapshot of the server version of the SQL
      if (rset->next())
        view->oldServerSqlDefinition(grt::StringRef(rset->getString("ddl")));
      else
        _grtm->get_grt()->send_info(base::strfmt("Could not get definition for %s.%s from server", schema->name().c_str(), view->name().c_str()));

      // take a snapshot of the model version of the SQL
      view->oldModelSqlDefinition(view->sqlDefinition());

      current_view++;
    }
  }
  _grtm->get_grt()->send_progress(1.0, "Finished.");
  _grtm->get_grt()->send_info(base::strfmt("%i views were read back.", current_view));
}
Ejemplo n.º 7
0
static void
session_imsgev(struct imsgev *iev, int code, struct imsg *imsg)
{
	struct m_backend	*mb = iev->data;

	switch (code) {
	case IMSGEV_IMSG:
		switch (imsg->hdr.type) {
		case IMSG_MAILDROP_INIT:
			maildrop_init(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_UPDATE:
			update(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_RETR:
			retr(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_DELE:
			dele(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_RSET:
			rset(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_LIST:
			list(iev, imsg, mb);
			break;
		case IMSG_MAILDROP_LISTALL:
			list_all(iev, imsg, mb);
			break;
		default:
			logit(LOG_DEBUG, "%s: unexpected imsg %u",
			    __func__, imsg->hdr.type);
			break;
		}
		break;
	case IMSGEV_EREAD:
	case IMSGEV_EWRITE:
	case IMSGEV_EIMSG:
		fatal("maildrop: imsgev read/write error");
		break;
	case IMSGEV_DONE:
		event_loopexit(NULL);
		break;
	}
}
Ejemplo n.º 8
0
void Db_plugin::load_schemata(std::vector<std::string> &schemata)
{
  _schemata.clear();
  _schemata_ddl.clear();

  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());

  _grtm->get_grt()->send_info(_("Fetching schema list."));
  _grtm->get_grt()->send_progress(0.0, _("Fetching schema list..."));

  const unsigned int major = dbc_meta->getDatabaseMajorVersion();
  const unsigned int minor = dbc_meta->getDatabaseMinorVersion();
  const unsigned int revision = dbc_meta->getDatabasePatchVersion();

  DbMySQLImpl *diffsql_module= _grtm->get_grt()->find_native_module<DbMySQLImpl>("DbMySQL");
  _db_options = diffsql_module->getTraitsForServerVersion(major, minor, revision);
  _db_options.set("CaseSensitive", grt::IntegerRef(dbc_meta->storesMixedCaseIdentifiers()));

  std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", "", "schema"));
  _schemata.reserve(rset->rowsCount());
  float total= (float)rset->rowsCount();
  int current= 0;
  while (rset->next())
  {
    std::string name = rset->getString("name");
    if (name != "mysql" && name != "information_schema" && name != "performance_schema")
    {
      _schemata.push_back(name);
      _schemata_ddl[name]= rset->getString("ddl");
    }
    _grtm->get_grt()->send_progress(current++/total, name, "");
  }

  _grtm->get_grt()->send_progress(1.0, _("Fetch finished."));
  _grtm->get_grt()->send_info("OK");

  schemata= _schemata;
}
/* {{{ MySQL_Connection::getSessionVariable() -I- */
sql::SQLString
MySQL_Connection::getSessionVariable(const sql::SQLString & varname)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getSessionVariable");
	checkClosed();

	if (intern->cache_sql_mode && intern->sql_mode_set == true && !varname.compare("sql_mode")) {
		CPP_INFO_FMT("sql_mode=%s", intern->sql_mode.c_str());
		return intern->sql_mode;
	}
	sql::SQLString q("SHOW SESSION VARIABLES LIKE '");
	q.append(varname).append("'");

	boost::scoped_ptr< sql::ResultSet > rset(service->executeQuery(q));

	if (rset->next()) {
		if (intern->cache_sql_mode && intern->sql_mode_set == false && !varname.compare("sql_mode")) {
			intern->sql_mode = rset->getString(2);
			intern->sql_mode_set = true;
		}
		return rset->getString(2);
	}
	return "";
}
Ejemplo n.º 10
0
int	smunge (userT *user)
{
	// Interactively deals with users pop commands,
	// servicing them from the users pop servers,
	// smunging the results as needed.

	int	argc;
	char	argv0[MAX_ARG_LEN];
	char	argv1[MAX_ARG_LEN];
	char	argv2[MAX_ARG_LEN];
	char	argv3[MAX_ARG_LEN];
	int	i;
	char	response[MAX_LINE];

	if (!user || (user->fd < 1))
	{
		return -1;
	}

	while (user->fd > 0)
	{
		watchdog (user);
		if (user->fd < 0)
		{
			return (-1);
		}
		
		argc=get_command (&user->fd, argv0, argv1, argv2, argv3);
 
		if (argc < 0)
		{
			// there was a problem.
			return (0);
		} else
		if (argc)
		{
			if (!strcmp (argv0, "QUIT"))
			{ 
				quit (user);
				ok (user->fd, "Have a nice day");	
				return (0);
			} else
			if (!strcmp (argv0, "DBUG") && (LOG_LEVEL==666))
			{
				debug (user);
			} else
			if (!strcmp (argv0, "STAT"))
			{
				long messages = 0;
				long size = 0;

				user->time = time(NULL);
				for (i=0; i < user->mailboxes; i++)
				{
					if (user->mailbox[i].fd > 0)
					{
						if (status (user, i, &messages, &size) == -1)
						{
							return (0);
						}
					}
				}
				snprintf (response, MAX_LINE-1, "%ld %ld", messages, size);

				ok (user->fd, response);
			} else
			if (!strcmp (argv0, "LIST"))
			{
				user->time = time(NULL);
				// if given with no arguments
				if (argc == 1)
				{
					if (list (user) == -1)
					{
						return (0);
					}
				} else
				{
					if (list_s (user, atol(argv1)) == -1)
					{
						return (0);
					}
				}
			} else
			if (!strcmp (argv0, "UIDL"))
			{
				user->time = time(NULL);
				// if given with no arguments
				if (argc == 1)
				{
					if (uidl (user) == -1)
					{
						return (0);
					}
				} else
				{
					if (uidl_s (user, atol(argv1)) == -1)
					{
						return (0);
					}
				}
			} else
			if ((argc == 2) && (!strcmp (argv0, "RETR")))
			{
				user->time = time(NULL);
				if (retr (user, atol(argv1), -1) == -1)
				{
					return (0);
				}
			} else
			if ((argc == 2) && (!strcmp (argv0, "DELE")))
			{
				user->time = time(NULL);
				if (dele (user, atol(argv1)) == -1)
				{
					return (0);
				}	
			} else
			if ((argc == 3) && (!strcmp (argv0, "TOP")))
			{
				user->time = time(NULL);

				if (atol(argv2) < 0)
				{
					err (user, "Need to supply a non-negative number of lines");
				} else
				if (retr (user, atol(argv1), atol(argv2)) == -1)
				{
					return (0);
				}
			} else
			if (!strcmp (argv0, "RSET"))
			{
				user->time = time(NULL);
				if (rset (user) == -1)
				{
					return (0);
				}
			} else
			if (!strcmp (argv0, "NOOP"))
			{
				user->time = time(NULL);
				ok (user->fd, "Keeping out of trouble");
			} else
			{
				user->time = time(NULL);
				snprintf (response, MAX_LINE-1, "Invalid commmand - %s", argv0);
				err (user, response); 
			}
		
		} else
		{
			user->time = time(NULL);
			err (user, "Talk to me");
		}
	}

	return (0);
}
Ejemplo n.º 11
0
/*************************************************************************
* Let the game begin
**************************************************************************/
int main(int argc, char *argv[])
{
  idx_t i, j, npes, mype, optype, nparts, adptf, options[10];
  idx_t *part=NULL, *sizes=NULL;
  graph_t graph;
  real_t ipc2redist, *xyz=NULL, *tpwgts=NULL, ubvec[MAXNCON];
  MPI_Comm comm;
  idx_t numflag=0, wgtflag=0, ndims, edgecut;
  char xyzfilename[8192];

  MPI_Init(&argc, &argv);
  MPI_Comm_dup(MPI_COMM_WORLD, &comm);
  gkMPI_Comm_size(comm, &npes);
  gkMPI_Comm_rank(comm, &mype);

  if (argc != 8) {
    if (mype == 0)
      printf("Usage: %s <graph-file> <op-type> <nparts> <adapth-factor> <ipc2redist> <dbglvl> <seed>\n", argv[0]);

    MPI_Finalize();
    exit(0);
  }

  optype     = atoi(argv[2]);
  nparts     = atoi(argv[3]);
  adptf      = atoi(argv[4]);
  ipc2redist = atof(argv[5]);

  options[0] = 1;
  options[PMV3_OPTION_DBGLVL] = atoi(argv[6]);
  options[PMV3_OPTION_SEED]   = atoi(argv[7]);

  if (mype == 0) 
    printf("reading file: %s\n", argv[1]);
  ParallelReadGraph(&graph, argv[1], comm);

  /* Remove the edges for testing */
  /*iset(graph.vtxdist[mype+1]-graph.vtxdist[mype]+1, 0, graph.xadj); */

  rset(graph.ncon, 1.05, ubvec);
  tpwgts = rmalloc(nparts*graph.ncon, "tpwgts");
  rset(nparts*graph.ncon, 1.0/(real_t)nparts, tpwgts);

  /*
  ChangeToFortranNumbering(graph.vtxdist, graph.xadj, graph.adjncy, mype, npes); 
  numflag = 1;

  nvtxs = graph.vtxdist[mype+1]-graph.vtxdist[mype];
  nedges = graph.xadj[nvtxs];
  printf("%"PRIDX" %"PRIDX"\n", isum(nvtxs, graph.xadj, 1), isum(nedges, graph.adjncy, 1));
  */


  if (optype >= 20) { 
    sprintf(xyzfilename, "%s.xyz", argv[1]);
    xyz = ReadTestCoordinates(&graph, xyzfilename, &ndims, comm);
  }

  if (mype == 0) 
    printf("finished reading file: %s\n", argv[1]);
  
  part  = ismalloc(graph.nvtxs, mype%nparts, "main: part");
  sizes = imalloc(2*npes, "main: sizes");

  switch (optype) {
    case 1: 
      wgtflag = 3;
      ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, 
          options, &edgecut, part, &comm);
      WritePVector(argv[1], graph.vtxdist, part, MPI_COMM_WORLD); 
      break;
    case 2:
      wgtflag = 3;
      options[PMV3_OPTION_PSR] = PARMETIS_PSR_COUPLED;
      ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, 
          options, &edgecut, part, &comm);
      WritePVector(argv[1], graph.vtxdist, part, MPI_COMM_WORLD); 
      break;
    case 3:
      options[PMV3_OPTION_PSR] = PARMETIS_PSR_COUPLED;
      graph.vwgt = ismalloc(graph.nvtxs, 1, "main: vwgt");
      if (npes > 1) {
        AdaptGraph(&graph, adptf, comm);
      }
      else {
        wgtflag = 3;
        ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
            graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, 
            ubvec, options, &edgecut, part, &comm);

        printf("Initial partitioning with edgecut of %"PRIDX"\n", edgecut);
        for (i=0; i<graph.ncon; i++) {
          for (j=0; j<graph.nvtxs; j++) {
            if (part[j] == i)
              graph.vwgt[j*graph.ncon+i] = adptf; 
            else
              graph.vwgt[j*graph.ncon+i] = 1; 
          }
        }
      }

      wgtflag = 3;
      ParMETIS_V3_AdaptiveRepart(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          NULL, graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, 
	  &ipc2redist, options, &edgecut, part, &comm);
      break;
    case 4: 
      ParMETIS_V3_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, 
          part, sizes, &comm);
      /* WriteOVector(argv[1], graph.vtxdist, part, comm);   */
      break;

    case 5: 
      ParMETIS_SerialNodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, 
          part, sizes, &comm);
      /* WriteOVector(argv[1], graph.vtxdist, part, comm);  */ 
      printf("%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], sizes[5], sizes[6]);
      break;
    case 11: 
      /* TestAdaptiveMETIS(graph.vtxdist, graph.xadj, graph.adjncy, part, options, adptf, comm); */
      break;
    case 20: 
      wgtflag = 3;
      ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          graph.adjwgt, &wgtflag, &numflag, &ndims, xyz, &graph.ncon, &nparts, 
          tpwgts, ubvec, options, &edgecut, part, &comm);
      break;
    case 21: 
      ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm);
      break;
  }

  /* printf("%"PRIDX" %"PRIDX"\n", isum(nvtxs, graph.xadj, 1), isum(nedges, graph.adjncy, 1)); */

  gk_free((void **)&part, &sizes, &tpwgts, &graph.vtxdist, &graph.xadj, &graph.adjncy, 
         &graph.vwgt, &graph.adjwgt, &xyz, LTERM);

  MPI_Comm_free(&comm);

  MPI_Finalize();

  return 0;
}
Ejemplo n.º 12
0
void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
{
	const InetAddress::IpScope scope = myPhysicalAddress.ipScope();

	// This would be weird, e.g. a public IP talking to 10.0.0.1, so just ignore it.
	// If your network is this weird it's probably not reliable information.
	if (scope != reporterPhysicalAddress.ipScope())
		return;

	// Some scopes we ignore, and global scope IPs are only used for this
	// mechanism if they come from someone we trust (e.g. a root).
	switch(scope) {
		case InetAddress::IP_SCOPE_NONE:
		case InetAddress::IP_SCOPE_LOOPBACK:
		case InetAddress::IP_SCOPE_MULTICAST:
			return;
		case InetAddress::IP_SCOPE_GLOBAL:
			if (!trusted)
				return;
			break;
		default:
			break;
	}

	Mutex::Lock _l(_phy_m);
	PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,reporterPhysicalAddress,scope)];

	if ( ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
		entry.mySurface = myPhysicalAddress;
		entry.ts = now;
		TRACE("physical address %s for scope %u as seen from %s(%s) differs from %s, resetting paths in scope",myPhysicalAddress.toString().c_str(),(unsigned int)scope,reporter.toString().c_str(),reporterPhysicalAddress.toString().c_str(),entry.mySurface.toString().c_str());

		// Erase all entries in this scope that were not reported from this remote address to prevent 'thrashing'
		// due to multiple reports of endpoint change.
		// Don't use 'entry' after this since hash table gets modified.
		{
			Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
			PhySurfaceKey *k = (PhySurfaceKey *)0;
			PhySurfaceEntry *e = (PhySurfaceEntry *)0;
			while (i.next(k,e)) {
				if ((k->reporterPhysicalAddress != reporterPhysicalAddress)&&(k->scope == scope))
					_phy.erase(*k);
			}
		}

		// Reset all paths within this scope
		_ResetWithinScope rset(RR,now,(InetAddress::IpScope)scope);
		RR->topology->eachPeer<_ResetWithinScope &>(rset);

		// Send a NOP to all peers for whom we forgot a path. This will cause direct
		// links to be re-established if possible, possibly using a root server or some
		// other relay.
		for(std::vector< SharedPtr<Peer> >::const_iterator p(rset.peersReset.begin());p!=rset.peersReset.end();++p) {
			if ((*p)->activelyTransferringFrames(now)) {
				Packet outp((*p)->address(),RR->identity.address(),Packet::VERB_NOP);
				RR->sw->send(outp,true,0);
			}
		}
	} else {
		entry.mySurface = myPhysicalAddress;
		entry.ts = now;
	}
}
Ejemplo n.º 13
0
/*************************************************************************
* This function performs a k-way directed diffusion
**************************************************************************/
real_t WavefrontDiffusion(ctrl_t *ctrl, graph_t *graph, idx_t *home)
{
  idx_t ii, i, j, k, l, nvtxs, nedges, nparts;
  idx_t from, to, edge, done, nswaps, noswaps, totalv, wsize;
  idx_t npasses, first, second, third, mind, maxd;
  idx_t *xadj, *adjncy, *adjwgt, *where, *perm;
  idx_t *rowptr, *colind, *ed, *psize;
  real_t *transfer, *tmpvec;
  real_t balance = -1.0, *load, *solution, *workspace;
  real_t *nvwgt, *npwgts, flowFactor, cost, ubfactor;
  matrix_t matrix;
  ikv_t *cand;
  idx_t ndirty, nclean, dptr, clean;

  nvtxs        = graph->nvtxs;
  nedges       = graph->nedges;
  xadj         = graph->xadj;
  nvwgt        = graph->nvwgt;
  adjncy       = graph->adjncy;
  adjwgt       = graph->adjwgt;
  where        = graph->where;
  nparts       = ctrl->nparts;
  ubfactor     = ctrl->ubvec[0];
  matrix.nrows = nparts;

  flowFactor = 0.35;
  flowFactor = (ctrl->mype == 2) ? 0.50 : flowFactor;
  flowFactor = (ctrl->mype == 3) ? 0.75 : flowFactor;
  flowFactor = (ctrl->mype == 4) ? 1.00 : flowFactor;

  /* allocate memory */
  solution                   = rmalloc(4*nparts+2*nedges, "WavefrontDiffusion: solution");
  tmpvec                     = solution + nparts;
  npwgts                     = solution + 2*nparts;
  load                       = solution + 3*nparts;
  matrix.values              = solution + 4*nparts;
  transfer = matrix.transfer = solution + 4*nparts + nedges;

  perm                   = imalloc(2*nvtxs+2*nparts+nedges+1, "WavefrontDiffusion: perm");
  ed                     = perm + nvtxs;
  psize                  = perm + 2*nvtxs;
  rowptr = matrix.rowptr = perm + 2*nvtxs + nparts;
  colind = matrix.colind = perm + 2*nvtxs + 2*nparts + 1;

  /*GKTODO - Potential problem with this malloc */
  wsize     = gk_max(sizeof(real_t)*nparts*6, sizeof(idx_t)*(nvtxs+nparts*2+1));
  workspace = (real_t *)gk_malloc(wsize, "WavefrontDiffusion: workspace");
  cand      = ikvmalloc(nvtxs, "WavefrontDiffusion: cand");


  /*****************************/
  /* Populate empty subdomains */
  /*****************************/
  iset(nparts, 0, psize);
  for (i=0; i<nvtxs; i++) 
    psize[where[i]]++;

  mind = iargmin(nparts, psize);
  maxd = iargmax(nparts, psize);
  if (psize[mind] == 0) {
    for (i=0; i<nvtxs; i++) {
      k = (RandomInRange(nvtxs)+i)%nvtxs; 
      if (where[k] == maxd) {
        where[k] = mind;
        psize[mind]++;
        psize[maxd]--;
        break;
      }
    }
  }

  iset(nvtxs, 0, ed);
  rset(nparts, 0.0, npwgts);
  for (i=0; i<nvtxs; i++) {
    npwgts[where[i]] += nvwgt[i];
    for (j=xadj[i]; j<xadj[i+1]; j++)
      ed[i] += (where[i] != where[adjncy[j]] ? adjwgt[j] : 0);
  }

  ComputeLoad(graph, nparts, load, ctrl->tpwgts, 0);
  done = 0;


  /* zero out the tmpvec array */
  rset(nparts, 0.0, tmpvec);

  npasses = gk_min(nparts/2, NGD_PASSES);
  for (l=0; l<npasses; l++) {
    /* Set-up and solve the diffusion equation */
    nswaps = 0;

    /************************/
    /* Solve flow equations */
    /************************/
    SetUpConnectGraph(graph, &matrix, (idx_t *)workspace);

    /* check for disconnected subdomains */
    for(i=0; i<matrix.nrows; i++) {
      if (matrix.rowptr[i]+1 == matrix.rowptr[i+1]) {
        cost = (real_t)(ctrl->mype); 
	goto CleanUpAndExit;
      }
    }

    ConjGrad2(&matrix, load, solution, 0.001, workspace);
    ComputeTransferVector(1, &matrix, solution, transfer, 0);

    GetThreeMax(nparts, load, &first, &second, &third);

    if (l%3 == 0) {
      FastRandomPermute(nvtxs, perm, 1);
    }
    else {
      /*****************************/
      /* move dirty vertices first */
      /*****************************/
      ndirty = 0;
      for (i=0; i<nvtxs; i++) {
        if (where[i] != home[i])
          ndirty++;
      }

      dptr = 0;
      for (i=0; i<nvtxs; i++) {
        if (where[i] != home[i])
          perm[dptr++] = i;
        else
          perm[ndirty++] = i;
      }

      PASSERT(ctrl, ndirty == nvtxs);
      ndirty = dptr;
      nclean = nvtxs-dptr;
      FastRandomPermute(ndirty, perm, 0);
      FastRandomPermute(nclean, perm+ndirty, 0);
    }

    if (ctrl->mype == 0) {
      for (j=nvtxs, k=0, ii=0; ii<nvtxs; ii++) {
        i = perm[ii];
        if (ed[i] != 0) {
          cand[k].key = -ed[i];
          cand[k++].val = i;
        }
        else {
          cand[--j].key = 0;
          cand[j].val = i;
        }
      }
      ikvsorti(k, cand);
    }


    for (ii=0; ii<nvtxs/3; ii++) {
      i = (ctrl->mype == 0) ? cand[ii].val : perm[ii];
      from = where[i];

      /* don't move out the last vertex in a subdomain */
      if (psize[from] == 1)
        continue;

      clean = (from == home[i]) ? 1 : 0;

      /* only move from top three or dirty vertices */
      if (from != first && from != second && from != third && clean)
        continue;

      /* Scatter the sparse transfer row into the dense tmpvec row */
      for (j=rowptr[from]+1; j<rowptr[from+1]; j++)
        tmpvec[colind[j]] = transfer[j];

      for (j=xadj[i]; j<xadj[i+1]; j++) {
        to = where[adjncy[j]];
        if (from != to) {
          if (tmpvec[to] > (flowFactor * nvwgt[i])) {
            tmpvec[to] -= nvwgt[i];
            INC_DEC(psize[to], psize[from], 1);
            INC_DEC(npwgts[to], npwgts[from], nvwgt[i]);
            INC_DEC(load[to], load[from], nvwgt[i]);
            where[i] = to;
            nswaps++;

            /* Update external degrees */
            ed[i] = 0;
            for (k=xadj[i]; k<xadj[i+1]; k++) {
              edge = adjncy[k];
              ed[i] += (to != where[edge] ? adjwgt[k] : 0);

              if (where[edge] == from)
                ed[edge] += adjwgt[k];
              if (where[edge] == to)
                ed[edge] -= adjwgt[k];
            }
            break;
          }
        }
      }

      /* Gather the dense tmpvec row into the sparse transfer row */
      for (j=rowptr[from]+1; j<rowptr[from+1]; j++) {
        transfer[j] = tmpvec[colind[j]];
        tmpvec[colind[j]] = 0.0;
      }
      ASSERT(fabs(rsum(nparts, tmpvec, 1)) < .0001)
    }

    if (l % 2 == 1) {
      balance = rmax(nparts, npwgts)*nparts;
      if (balance < ubfactor + 0.035)
        done = 1;

      if (GlobalSESum(ctrl, done) > 0)
        break;

      noswaps = (nswaps > 0) ? 0 : 1;
      if (GlobalSESum(ctrl, noswaps) > ctrl->npes/2)
        break;

    }
  }

  graph->mincut = ComputeSerialEdgeCut(graph);
  totalv        = Mc_ComputeSerialTotalV(graph, home);
  cost          = ctrl->ipc_factor * (real_t)graph->mincut + ctrl->redist_factor * (real_t)totalv;


CleanUpAndExit:
  gk_free((void **)&solution, (void **)&perm, (void **)&workspace, (void **)&cand, LTERM);

  return cost;
}
Ejemplo n.º 14
0
Archivo: pcpd.c Proyecto: zixia/nospam
static int doline(struct PCP *pcp, char *p, int acl_flags)
{
	char *q=strtok(p, " ");

	if (!q)
	{
		printf("500 Syntax error\n");
		return (0);
	}

	if (strcasecmp(q, "QUIT") == 0)
	{
		printf("200 Bye.\n");
		return (-1);
	}

	if (strcasecmp(q, "NOOP") == 0)
	{
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "CAPABILITY") == 0)
	{
		printf("100-ACL\n");
		printf("100 PCP1\n");
		return (0);
	}

	if (strcasecmp(q, "LIST") == 0)
	{
		if (check_acl(acl_flags, PCP_ACL_LIST))
			return (0);

		if (list(pcp))
			printf("500 Syntax error\n");
		return (0);
	}

	if (strcasecmp(q, "RETR") == 0)
	{
		if (check_acl(acl_flags, PCP_ACL_RETR))
			return (0);

		if (retr(pcp))
			printf("500 Syntax error\n");
		return (0);
	}


	if (strcasecmp(q, "ACL") == 0 && pcp_has_acl(pcp) && !proxy_userid)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "SET") == 0)
		{
			const char *who=strtok(NULL, " ");

			if (who)
			{
				int flags=0;

				while ((q=strtok(NULL, " ")) != 0)
					flags |= pcp_acl_num(q);

				if (pcp_acl(pcp, who, flags))
				{
					error(0);
					return (0);
				}
				printf("200 Ok\n");
				return (0);
			}
		}
		else if (q && strcasecmp(q, "LIST") == 0)
		{
			listacls(pcp);
			return (0);
		}
	}

	if (strcasecmp(q, "RSET") == 0)
	{
		conflict_flag=0;
		force_flag=0;
		need_rset=0;
		rset(pcp);
		printf("200 Ok.\n");	
		return (0);
	}

	if (need_rset)
	{
		printf("500 RSET required - calendar in an unknown state.\n");
		return (0);
	}

	if (strcasecmp(q, "DELETE") == 0)
	{
		struct PCP_retr r;
		const char *event_id_list[2];

		char *e=strtok(NULL, " ");

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		if (e && deleted_eventid == NULL && new_eventid == NULL)
		{
			if ((deleted_eventid=strdup(e)) == NULL)
			{
				perror("strdup");
				exit(1);
			}
			proxy_list_rset();
			memset(&r, 0, sizeof(r));
			r.callback_retr_participants=open_event_participant;
			event_id_list[0]=deleted_eventid;
			event_id_list[1]=NULL;
			r.event_id_list=event_id_list;
			if (pcp_retr(pcp, &r))
			{
				error(r.errcode);
				proxy_list_rset();
			}
			else
				printf("200 Ok.\n");
			return (0);
		}
	}

	if (strcasecmp(q, "NEW") == 0 && new_eventid == NULL)
	{
		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		new_eventid=readnewevent(pcp);

		if (new_eventid == NULL)
		{
			printf("500 %s\n", strerror(errno));
		}
		else
			printf("109 %s ready to be commited.\n",
			       new_eventid->eventid);
		return (0);
	}

	if (strcasecmp(q, "BOOK") == 0 && new_eventid)
	{
		dobook(pcp);
		return (0);
	}

	if (strcasecmp(q, "CONFLICT") == 0)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "ON") == 0)
		{
			if (check_acl(acl_flags, PCP_ACL_CONFLICT))
				return (0);

			conflict_flag=1;
		}
		else
			conflict_flag=0;
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "FORCE") == 0)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "ON") == 0)
		{
			force_flag=1;
		}
		else
			force_flag=0;
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "COMMIT") == 0)
	{
		if (notbooked)
		{
			printf("500 BOOK required.\n");
		}
		else if (new_eventid && new_commit_times)
		{
			struct proxy_list *pl;

			new_commit.add_conflict_callback=NULL;
			new_commit.add_conflict_callback_ptr=NULL;

			new_commit.flags=
				(conflict_flag ? PCP_OK_CONFLICT:0) |
				(force_flag ? PCP_OK_PROXY_ERRORS:0);

			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (pl->flags & PROXY_IGNORE)
					continue;

				if (pl->flags & PROXY_NEW)
				{
					if (pcp_commit(pl->proxy,
						       pl->newevent,
						       &new_commit))
					{
						syslog(LOG_CRIT,
						       "COMMIT failed for PROXY %s",
						       pl->userid);

						if (!force_flag)
						{
							pl->flags &=
								~PROXY_NEW;
							error(new_commit
							      .errcode);
							return (0);
						}
					}
				}
				else if (pl->old_event_id)
				{
					struct PCP_delete del;

					memset(&del, 0, sizeof(del));

					del.id=pl->old_event_id;

					if (pcp_delete(pl->proxy, &del))
					{
						syslog(LOG_CRIT,
						       "DELETE failed for PROXY %s",
						       pl->userid);
						if (!force_flag)
						{
							error(del.errcode);
							return (0);
						}
						pl->flags |= PROXY_IGNORE;
					}
				}
			}

			if (proxy_userid)
				new_commit.flags |= PCP_BYPROXY;

			if (pcp_commit(pcp, new_eventid, &new_commit))
				error(new_commit.errcode);
			else
			{
				const char *proxy_name=NULL;
				const char *proxy_action=NULL;

				for (pl=proxy_list; pl; pl=pl->next)
				{
					if (proxy_name)
						printf("111-%s %s\n",
						       proxy_action,
						       proxy_name);

					proxy_action=
						!(pl->flags & PROXY_IGNORE)
						&& (pl->flags & PROXY_NEW)
						? "NEW":"DELETE";
					proxy_name=pl->userid;
				}

				if (proxy_name)
					printf("111 %s %s\n",
					       proxy_action,
					       proxy_name);
				else
					printf("200 Ok.\n");
			}	
			rset(pcp);
			return (0);
		}
		else if (!new_eventid && deleted_eventid)
		{
			struct proxy_list *pl;
			struct PCP_delete del;
			const char *proxy_userid;

			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (pl->flags & PROXY_IGNORE)
					continue;

				if (pl->old_event_id)
				{
					memset(&del, 0, sizeof(del));
					del.id=pl->old_event_id;

					if (pcp_delete(pl->proxy, &del))
					{
						syslog(LOG_CRIT,
						       "DELETE failed for PROXY %s",
						       pl->userid);
					}
				}
			}

			memset(&del, 0, sizeof(del));
			del.id=deleted_eventid;

			if (pcp_delete(pcp, &del))
			{
				if (del.errcode != PCP_ERR_EVENTNOTFOUND)
				{
					error(del.errcode);
					return (0);
				}
			}

			proxy_userid=NULL;
			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (proxy_userid)
					printf("111-DELETE %s\n",
					       proxy_userid);

				proxy_userid=pl->userid;
			}

			if (proxy_userid)
				printf("111 DELETE %s\n", proxy_userid);
			else
				printf("200 Ok\n");

			rset(pcp);
			return (0);
		}

		printf("500 There's nothing to commit.\n");
		return (0);
	}

	if (strcasecmp(q, "CANCEL") == 0)
	{
		int errcode;

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		q=strtok(NULL, " ");
		if (!q)
			printf("500 Syntax error\n");
		else if (pcp_cancel(pcp, q, &errcode))
			error(errcode);
		else
			printf("200 Cancelled\n");
		return (0);
	}

	if (strcasecmp(q, "UNCANCEL") == 0)
	{
		struct PCP_uncancel unc;
		struct uncancel_list *list=NULL, **tail= &list;
		struct uncancel_list *p;

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		memset(&unc, 0, sizeof(unc));
		unc.uncancel_conflict_callback=uncancel_callback;
		unc.uncancel_conflict_callback_ptr=&tail;

		q=strtok(NULL, " ");
		if (!q)
			printf("500 Syntax error\n");
		else if (pcp_uncancel(pcp, q,
				      (conflict_flag ? PCP_OK_CONFLICT:0)|
				      (force_flag ? PCP_OK_PROXY_ERRORS:0),
				      &unc))
		{
			if (unc.errcode == PCP_ERR_CONFLICT && list)
			{
				for (p=list; p; p=p->next)
				{
					char from_buf[15];
					char to_buf[15];

					pcp_gmtimestr(p->from, from_buf);
					pcp_gmtimestr(p->to, to_buf);

					printf("403%c%s %s %s %s conflicts.\n",
					       p->next ? '-':' ',
					       p->addr,
					       from_buf,
					       to_buf,
					       p->id);
				}
			}
			else
				error(unc.errcode);
		}
		else
			printf("200 Uncancelled\n");

		while((p=list) != NULL)
		{
			list=p->next;
			free(p->addr);
			free(p->id);
			free(p);
		}
		return (0);
	}

	printf("500 Syntax error\n");
	return (0);
}
Ejemplo n.º 15
0
void TestParMetis_GPart(char *filename, char *xyzfile, MPI_Comm comm)
{
  idx_t ncon, nparts, npes, mype, opt2, realcut;
  graph_t graph, mgraph;
  idx_t *part, *mpart, *savepart, *order, *sizes;
  idx_t numflag=0, wgtflag=0, options[10], edgecut, ndims;
  real_t ipc2redist, *xyz=NULL, *tpwgts = NULL, ubvec[MAXNCON];

  gkMPI_Comm_size(comm, &npes);
  gkMPI_Comm_rank(comm, &mype);

  ParallelReadGraph(&graph, filename, comm);
  if (xyzfile)
    xyz = ReadTestCoordinates(&graph, xyzfile, &ndims, comm);
  gkMPI_Barrier(comm);

  part   = imalloc(graph.nvtxs, "TestParMetis_V3: part");
  tpwgts = rmalloc(MAXNCON*npes*2, "TestParMetis_V3: tpwgts");
  rset(MAXNCON, 1.05, ubvec);

  graph.vwgt = ismalloc(graph.nvtxs*5, 1, "TestParMetis_GPart: vwgt");


  /*======================================================================
  / ParMETIS_V3_PartKway
  /=======================================================================*/
  options[0] = 1;
  options[1] = 3;
  options[2] = 1;
  wgtflag = 2;
  numflag = 0;
  edgecut = 0;

  for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) {
    for (ncon=1; ncon<=NCON; ncon++) {
      if (ncon > 1 && nparts > 1)
        Mc_AdaptGraph(&graph, part, ncon, nparts, comm);
      else
        iset(graph.nvtxs, 1, graph.vwgt);

      if (mype == 0)
        printf("\nTesting ParMETIS_V3_PartKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts);

      rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);
      ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, 
          &edgecut, part, &comm);

      realcut = ComputeRealCut(graph.vtxdist, part, filename, comm);
      if (mype == 0) {
        printf("ParMETIS_V3_PartKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut,
            (edgecut == realcut ? "OK" : "ERROR"), realcut);
      }

      if (mype == 0)
        printf("\nTesting ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts);

      options[3] = PARMETIS_PSR_UNCOUPLED;
      ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
          NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, 
          &edgecut, part, &comm);

      realcut = ComputeRealCut(graph.vtxdist, part, filename, comm);
      if (mype == 0) {
        printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut,
            (edgecut == realcut ? "OK" : "ERROR"), realcut);
      }
    }
  }


  /*======================================================================
  / ParMETIS_V3_PartGeomKway 
  /=======================================================================*/
  if (xyzfile != NULL) {
    options[0] = 1;
    options[1] = 3;
    options[2] = 1;
    wgtflag = 2;
    numflag = 0;

    for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) {
      for (ncon=1; ncon<=NCON; ncon++) {
        if (ncon > 1)
          Mc_AdaptGraph(&graph, part, ncon, nparts, comm);
        else
          iset(graph.nvtxs, 1, graph.vwgt);
  
        if (mype == 0)
          printf("\nTesting ParMETIS_V3_PartGeomKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts);
  
        rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);
        ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, 
            NULL, &wgtflag, &numflag, &ndims, xyz, &ncon, &nparts, tpwgts, ubvec, 
            options, &edgecut, part, &comm);
  
        realcut = ComputeRealCut(graph.vtxdist, part, filename, comm);
        if (mype == 0) 
          printf("ParMETIS_V3_PartGeomKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut,
              (edgecut == realcut ? "OK" : "ERROR"), realcut);
      }
    }
  }



  /*======================================================================
  / ParMETIS_V3_PartGeom 
  /=======================================================================*/
  if (xyz != NULL) {
    wgtflag = 0;
    numflag = 0;
    if (mype == 0)
      printf("\nTesting ParMETIS_V3_PartGeom\n");

      ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm); 

    realcut = ComputeRealCut(graph.vtxdist, part, filename, comm);
    if (mype == 0) 
      printf("ParMETIS_V3_PartGeom reported a cut of %"PRIDX"\n", realcut);
  }


  /*======================================================================
  / Coupled ParMETIS_V3_RefineKway 
  /=======================================================================*/
  options[0] = 1;
  options[1] = 3;
  options[2] = 1;
  options[3] = PARMETIS_PSR_COUPLED;
  nparts = npes;
  wgtflag = 0;
  numflag = 0;
  ncon = 1;
  rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);

  if (mype == 0)
    printf("\nTesting coupled ParMETIS_V3_RefineKway with default options (before move)\n");

  ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, 
      &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, 
      part, &comm);





  /* Compute a good partition and move the graph. Do so quietly! */
  options[0] = 0;
  nparts = npes;
  wgtflag = 0;
  numflag = 0;
  ncon = 1;
  rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);
  ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, 
      &wgtflag, &numflag, &ncon, &npes, tpwgts, ubvec, options, &edgecut, 
      part, &comm);
  TestMoveGraph(&graph, &mgraph, part, comm);
  gk_free((void **)&(graph.vwgt), LTERM);
  mpart    = ismalloc(mgraph.nvtxs, mype, "TestParMetis_V3: mpart");
  savepart = imalloc(mgraph.nvtxs, "TestParMetis_V3: savepart");



  /*======================================================================
  / Coupled ParMETIS_V3_RefineKway 
  /=======================================================================*/
  options[0] = 1;
  options[1] = 3;
  options[2] = 1;
  options[3] = PARMETIS_PSR_COUPLED;
  nparts  = npes;
  wgtflag = 0;
  numflag = 0;

  for (ncon=1; ncon<=NCON; ncon++) {
    if (mype == 0)
      printf("\nTesting coupled ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts);

    rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);
      ParMETIS_V3_RefineKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, 
          &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, 
          mpart, &comm);

    realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, 
                  filename, comm);
    if (mype == 0) 
      printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut,
          (edgecut == realcut ? "OK" : "ERROR"), realcut);
  }


/*ADAPTIVE:*/
  /*======================================================================
  / ParMETIS_V3_AdaptiveRepart
  /=======================================================================*/
  mgraph.vwgt  = ismalloc(mgraph.nvtxs*NCON, 1, "TestParMetis_V3: mgraph.vwgt");
  mgraph.vsize = ismalloc(mgraph.nvtxs, 1, "TestParMetis_V3: mgraph.vsize");
  AdaptGraph(&mgraph, 4, comm); 
  options[0] = 1;
  options[1] = 7;
  options[2] = 1;
  options[3] = PARMETIS_PSR_COUPLED;
  wgtflag = 2;
  numflag = 0;

  for (nparts=2*npes; nparts>=npes/2; nparts = nparts/2) {
    options[0] = 0;
    ncon    = 1;
    wgtflag = 0;
    rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);
    ParMETIS_V3_PartKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, 
        &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, 
        savepart, &comm);

    options[0] = 1;
    wgtflag    = 2;

    for (ncon=1; ncon<=NCON; ncon++) {
      rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts);

      if (ncon > 1)
        Mc_AdaptGraph(&mgraph, savepart, ncon, nparts, comm);
      else
        AdaptGraph(&mgraph, 4, comm); 

      for (ipc2redist=1000.0; ipc2redist>=0.001; ipc2redist/=1000.0) {
        icopy(mgraph.nvtxs, savepart, mpart);

        if (mype == 0)
          printf("\nTesting ParMETIS_V3_AdaptiveRepart with ipc2redist: %.3"PRREAL", ncon: %"PRIDX", nparts: %"PRIDX"\n", 
              ipc2redist, ncon, nparts);

        ParMETIS_V3_AdaptiveRepart(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, 
            mgraph.vwgt, mgraph.vsize, NULL, &wgtflag, &numflag, &ncon, &nparts, 
            tpwgts, ubvec, &ipc2redist, options, &edgecut, mpart, &comm);

        realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, 
                      filename, comm);
        if (mype == 0) 
          printf("ParMETIS_V3_AdaptiveRepart reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut,
              (edgecut == realcut ? "OK" : "ERROR"), realcut);
      }
    }
  }

  gk_free((void **)&tpwgts, &part, &mpart, &savepart, &xyz, &mgraph.vwgt, &mgraph.vsize, LTERM);
}
Ejemplo n.º 16
0
        template<typename T> void load(ts::TimeSeries<T>& series,
                                       const std::string& table,
                                       bpt::ptime start = bpt::ptime(),
                                       bpt::ptime end = bpt::ptime(),
                                       bool print_meta = false)         // throws
        {
            BOOST_STATIC_ASSERT((boost::is_base_of< dp::DataPoint, T>::value));
            
            if( !isConnected() )
                connect();
            
            if( !has_table(table) )
                throw TSDBInterfaceException(2);
            
            if( !_columns_match_type<T>(table) )
                throw TSDBInterfaceException(5);
            
            if( start > end )
                throw TSDBInterfaceException(4);
            
            try{

                std::string cols = boost::algorithm::join(dp::dp_names<T>(), ", ");
                std::string query = "SELECT date_time, "+cols+" FROM "+table;
                unique_ptr<sql::PreparedStatement> pstmt(_con->prepareStatement(query));
                
                if( !start.is_not_a_date_time() && !end.is_not_a_date_time() )
                {
                    query += " WHERE date_time BETWEEN (?) and (?);";
                    pstmt.reset( _con->prepareStatement(query) );
                    pstmt->setDateTime(1, utilities::bpt_to_str(start));
                    pstmt->setDateTime(2, utilities::bpt_to_str(end));
                }
                else if( !start.is_not_a_date_time() && end.is_not_a_date_time() )
                {
                    query += " WHERE date_time >= (?);";
                    pstmt.reset( _con->prepareStatement(query) );
                    pstmt->setDateTime(1, utilities::bpt_to_str(start));
                }
                else if( start.is_not_a_date_time() && !end.is_not_a_date_time() )
                {
                    query += " WHERE date_time <= (?);";
                    pstmt.reset( _con->prepareStatement(query) );
                	pstmt->setDateTime(1, utilities::bpt_to_str(end));
                }
              
                std::unique_ptr<sql::ResultSet> rset( pstmt->executeQuery() );
                sql::ResultSetMetaData* rset_meta( rset->getMetaData() );
                
                if( print_meta )
                    _print_loading_MetaData( rset_meta );
                
                int num_cols = rset_meta->getColumnCount();
                std::vector<double> row;
                row.reserve( num_cols-1 );
                
                while( rset->next() ){
                    
                    for( int i =  2; i <= num_cols; ++i) // MySQL Conn doesn't allow accessing entire row at once
                        row.push_back(rset->getDouble(i));
                    
                    series.insert( utilities::str_to_time_t(rset->getString(1)), T(row) ); //move insert
                    row.clear();
                }
            }
            catch( sql::SQLException& ex ) {
                _print_SQLException(ex);
                throw TSDBInterfaceException(3);
            }
            
        } //load
Ejemplo n.º 17
0
void Db_plugin::load_db_objects(Db_object_type db_object_type)
{
  Db_objects_setup *setup= db_objects_setup_by_type(db_object_type);
  setup->reset();

  _grtm->get_grt()->send_info(std::string("Fetching ").append(db_objects_type_to_string(db_object_type)).append(" list."));
  
  _grtm->get_grt()->send_progress(0.0, std::string("Fetching ").append(db_objects_type_to_string(db_object_type)).append(" list."));
  
  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());
  std::string db_object_type_name= db_objects_type_to_string(db_object_type);
  std::list<Db_obj_handle> db_objects;
  std::list<std::string> db_obj_names;
  
  float total_schemas= (float)_schemata_selection.size();
  int current_schema= 0;
  
  for (std::vector<std::string>::const_iterator iter= _schemata_selection.begin(); 
    iter != _schemata_selection.end(); ++iter)
  {
    const std::string &schema_name= *iter;
    float total_objects;
    int count= 0;
    
    _grtm->get_grt()->send_progress((current_schema / total_schemas), 
                                    std::string("Fetch ").append(db_objects_type_to_string(db_object_type)).append(" objects from ").append(schema_name));

    if (!schema_name.empty())
    {
      std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", schema_name, db_object_type_name));
      total_objects= (float)rset->rowsCount();
      while (rset->next())
      {
        Db_obj_handle db_obj;
        db_obj.schema= schema_name;
        db_obj.name= rset->getString("name");
        db_obj.ddl= rset->getString("ddl");
        setup->all.push_back(db_obj);
        
        // prefixed by schema name
        db_obj_names.push_back(std::string(schema_name).append(".").append(db_obj.name));
        
        _grtm->get_grt()->send_progress((current_schema / total_schemas) + (count / total_objects)/total_schemas,
                                        db_obj_names.back());
        
        count++;
      }
    }

    current_schema++;
    _grtm->get_grt()->send_info(base::strfmt("    %i items from %s", count, schema_name.c_str()));
  }
  
  // copy from temp list (used for performance optimization)
  setup->all.reserve(db_objects.size());
  std::copy(db_objects.begin(), db_objects.end(), setup->all.begin());
  db_objects.clear();

  // initialize db obj selection
  setup->selection.reset(db_obj_names);
  db_obj_names.clear();

  _grtm->get_grt()->send_progress(1.0, "Finished.");
  _grtm->get_grt()->send_info("OK");
}
Ejemplo n.º 18
0
/*************************************************************************
* This function is the entry point of the initial partitioning algorithm.
* This algorithm assembles the graph to all the processors and preceed
* serially.
**************************************************************************/
idx_t Mc_Diffusion(ctrl_t *ctrl, graph_t *graph, idx_t *vtxdist, idx_t *where, 
          idx_t *home, idx_t npasses)
{
  idx_t h, i, j;
  idx_t nvtxs, nedges, ncon, pass, iter, domain, processor;
  idx_t nparts, mype, npes, nlinks, me, you, wsize;
  idx_t nvisited, nswaps = -1, tnswaps, done, alldone = -1;
  idx_t *rowptr, *colind, *diff_where, *sr_where, *ehome, *map, *rmap;
  idx_t *pack, *unpack, *match, *proc2sub, *sub2proc;
  idx_t *visited, *gvisited;
  real_t *transfer, *npwgts, maxdiff, minflow, maxflow;
  real_t lbavg, oldlbavg, ubavg, *lbvec;
  real_t *diff_flows, *sr_flows;
  real_t diff_lbavg, sr_lbavg, diff_cost, sr_cost;
  idx_t *rbuffer, *sbuffer; 
  idx_t *rcount, *rdispl;
  real_t *solution, *load, *workspace;
  matrix_t matrix;
  graph_t *egraph;

  if (graph->ncon > 3)
    return 0;

  WCOREPUSH;

  nvtxs  = graph->nvtxs;
  nedges = graph->nedges;
  ncon   = graph->ncon;

  nparts = ctrl->nparts;
  mype   = ctrl->mype;
  npes   = ctrl->npes;
  ubavg  = ravg(ncon, ctrl->ubvec);

  /* initialize variables and allocate memory */
  lbvec      = rwspacemalloc(ctrl, ncon);
  diff_flows = rwspacemalloc(ctrl, ncon);
  sr_flows   = rwspacemalloc(ctrl, ncon);

  load                       = rwspacemalloc(ctrl, nparts);
  solution                   = rwspacemalloc(ctrl, nparts);
  npwgts = graph->gnpwgts    = rwspacemalloc(ctrl, ncon*nparts);
  matrix.values              = rwspacemalloc(ctrl, nedges);
  transfer = matrix.transfer = rwspacemalloc(ctrl, ncon*nedges);

  proc2sub               = iwspacemalloc(ctrl, gk_max(nparts, npes*2));
  sub2proc               = iwspacemalloc(ctrl, nparts);
  match                  = iwspacemalloc(ctrl, nparts);
  rowptr = matrix.rowptr = iwspacemalloc(ctrl, nparts+1);
  colind = matrix.colind = iwspacemalloc(ctrl, nedges);

  rcount = iwspacemalloc(ctrl, npes);
  rdispl = iwspacemalloc(ctrl, npes+1);

  pack       = iwspacemalloc(ctrl, nvtxs);
  unpack     = iwspacemalloc(ctrl, nvtxs);
  rbuffer    = iwspacemalloc(ctrl, nvtxs);
  sbuffer    = iwspacemalloc(ctrl, nvtxs);
  map        = iwspacemalloc(ctrl, nvtxs);
  rmap       = iwspacemalloc(ctrl, nvtxs);
  diff_where = iwspacemalloc(ctrl, nvtxs);
  ehome      = iwspacemalloc(ctrl, nvtxs);


  wsize = gk_max(sizeof(real_t)*nparts*6, sizeof(idx_t)*(nvtxs+nparts*2+1));
  workspace = (real_t *)gk_malloc(wsize, "Mc_Diffusion: workspace");

  graph->ckrinfo = (ckrinfo_t *)gk_malloc(nvtxs*sizeof(ckrinfo_t), "Mc_Diffusion: rinfo");


  /* construct subdomain connectivity graph */
  matrix.nrows = nparts;
  SetUpConnectGraph(graph, &matrix, (idx_t *)workspace);
  nlinks = (matrix.nnzs-nparts) / 2;

  visited  = iwspacemalloc(ctrl, matrix.nnzs);
  gvisited = iwspacemalloc(ctrl, matrix.nnzs);

  for (pass=0; pass<npasses; pass++) {
    rset(matrix.nnzs*ncon, 0.0, transfer);
    iset(matrix.nnzs, 0, gvisited);
    iset(matrix.nnzs, 0, visited);
    iter = nvisited = 0;

    /* compute ncon flow solutions */
    for (h=0; h<ncon; h++) {
      rset(nparts, 0.0, solution);
      ComputeLoad(graph, nparts, load, ctrl->tpwgts, h);

      lbvec[h] = (rmax(nparts, load)+1.0/nparts) * (real_t)nparts;

      ConjGrad2(&matrix, load, solution, 0.001, workspace);
      ComputeTransferVector(ncon, &matrix, solution, transfer, h);
    }

    oldlbavg = ravg(ncon, lbvec);
    tnswaps = 0;
    maxdiff = 0.0;
    for (i=0; i<nparts; i++) {
      for (j=rowptr[i]; j<rowptr[i+1]; j++) {
        maxflow = rmax(ncon, transfer+j*ncon);
        minflow = rmin(ncon, transfer+j*ncon);
        maxdiff = (maxflow - minflow > maxdiff) ? maxflow - minflow : maxdiff;
      }
    }

    while (nvisited < nlinks) {
      /* compute independent sets of subdomains */
      iset(gk_max(nparts, npes*2), UNMATCHED, proc2sub);
      CSR_Match_SHEM(&matrix, match, proc2sub, gvisited, ncon);

      /* set up the packing arrays */
      iset(nparts, UNMATCHED, sub2proc);
      for (i=0; i<npes*2; i++) {
        if (proc2sub[i] == UNMATCHED)
          break;

        sub2proc[proc2sub[i]] = i/2;
      }

      iset(npes, 0, rcount);
      for (i=0; i<nvtxs; i++) {
        domain = where[i];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          rcount[processor]++;
      }

      rdispl[0] = 0;
      for (i=1; i<npes+1; i++)
        rdispl[i] = rdispl[i-1] + rcount[i-1];

      iset(nvtxs, UNMATCHED, unpack);
      for (i=0; i<nvtxs; i++) {
        domain = where[i];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          unpack[rdispl[processor]++] = i;
      }

      SHIFTCSR(i, npes, rdispl);

      iset(nvtxs, UNMATCHED, pack);
      for (i=0; i<rdispl[npes]; i++) {
        ASSERT(unpack[i] != UNMATCHED);
        domain = where[unpack[i]];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          pack[unpack[i]] = i;
      }

      /* Compute the flows */
      if (proc2sub[mype*2] != UNMATCHED) {
        me  = proc2sub[2*mype];
        you = proc2sub[2*mype+1];
        ASSERT(me != you);

        for (j=rowptr[me]; j<rowptr[me+1]; j++) {
          if (colind[j] == you) {
            visited[j] = 1;
            rcopy(ncon, transfer+j*ncon, diff_flows);
            break;
          }
        }

        for (j=rowptr[you]; j<rowptr[you+1]; j++) {
          if (colind[j] == me) {
            visited[j] = 1;
            for (h=0; h<ncon; h++) {
              if (transfer[j*ncon+h] > 0.0)
                diff_flows[h] = -1.0 * transfer[j*ncon+h];
            }
            break;
          }
        } 

        nswaps = 1;
        rcopy(ncon, diff_flows, sr_flows);

        iset(nvtxs, 0, sbuffer);
        for (i=0; i<nvtxs; i++) {
          if (where[i] == me || where[i] == you)
            sbuffer[i] = 1;
        }

        egraph = ExtractGraph(ctrl, graph, sbuffer, map, rmap);

        if (egraph != NULL) {
          icopy(egraph->nvtxs, egraph->where, diff_where);
          for (j=0; j<egraph->nvtxs; j++)
            ehome[j] = home[map[j]];
 
          RedoMyLink(ctrl, egraph, ehome, me, you, sr_flows, &sr_cost, &sr_lbavg);

          if (ncon <= 4) {
            sr_where      = egraph->where;
            egraph->where = diff_where;

            nswaps = BalanceMyLink(ctrl, egraph, ehome, me, you, diff_flows, maxdiff, 
                         &diff_cost, &diff_lbavg, 1.0/(real_t)nvtxs);

            if ((sr_lbavg < diff_lbavg &&
                (diff_lbavg >= ubavg-1.0 || sr_cost == diff_cost)) ||
                (sr_lbavg < ubavg-1.0 && sr_cost < diff_cost)) {
              for (i=0; i<egraph->nvtxs; i++)
                where[map[i]] = sr_where[i];
            }
            else {
              for (i=0; i<egraph->nvtxs; i++)
                where[map[i]] = diff_where[i];
            }
          }
          else {
            for (i=0; i<egraph->nvtxs; i++)
              where[map[i]] = egraph->where[i];
          }

          gk_free((void **)&egraph->xadj, &egraph->nvwgt, &egraph->adjncy, &egraph, LTERM);
        }

        /* Pack the flow data */
        iset(nvtxs, UNMATCHED, sbuffer);
        for (i=0; i<nvtxs; i++) {
          domain = where[i];
          if (domain == you || domain == me) 
            sbuffer[pack[i]] = where[i];
        }
      }

      /* Broadcast the flow data */
      gkMPI_Allgatherv((void *)&sbuffer[rdispl[mype]], rcount[mype], IDX_T, 
          (void *)rbuffer, rcount, rdispl, IDX_T, ctrl->comm);

      /* Unpack the flow data */
      for (i=0; i<rdispl[npes]; i++) {
        if (rbuffer[i] != UNMATCHED) 
          where[unpack[i]] = rbuffer[i];
      }


      /* Do other stuff */
      gkMPI_Allreduce((void *)visited, (void *)gvisited, matrix.nnzs,
          IDX_T, MPI_MAX, ctrl->comm);
      nvisited = isum(matrix.nnzs, gvisited, 1)/2;
      tnswaps += GlobalSESum(ctrl, nswaps);

      if (iter++ == NGD_PASSES)
        break;
    }

    /* perform serial refinement */
    Mc_ComputeSerialPartitionParams(ctrl, graph, nparts);
    Mc_SerialKWayAdaptRefine(ctrl, graph, nparts, home, ctrl->ubvec, 10);

    /* check for early breakout */
    for (h=0; h<ncon; h++) {
      lbvec[h] = (real_t)(nparts) *
        npwgts[rargmax_strd(nparts,npwgts+h,ncon)*ncon+h];
    }
    lbavg = ravg(ncon, lbvec);

    done = 0;
    if (tnswaps == 0 || lbavg >= oldlbavg || lbavg <= ubavg + 0.035)
      done = 1;

    alldone = GlobalSEMax(ctrl, done);
    if (alldone == 1)
      break;
  }

  /* ensure that all subdomains have at least one vertex */
/*
  iset(nparts, 0, match);
  for (i=0; i<nvtxs; i++)
    match[where[i]]++;

  done = 0;
  while (done == 0) {
    done = 1;

    me = iargmin(nparts, match);  
    if (match[me] == 0) {
      if (ctrl->mype == PE) printf("WARNING: empty subdomain %"PRIDX" in Mc_Diffusion\n", me);
      you = iargmax(nparts, match);  
      for (i=0; i<nvtxs; i++) {
        if (where[i] == you) {
          where[i] = me;
          match[you]--;
          match[me]++;
          done = 0;
          break;
        }
      }
    }
  }
*/
 
  /* now free memory and return */
  gk_free((void **)&workspace, (void **)&graph->ckrinfo, LTERM);
  graph->gnpwgts = NULL;
  graph->ckrinfo = NULL;

  WCOREPOP;

  return 0;
}
Ejemplo n.º 19
0
/**
 * \brief Select format and frame.
 *
 * This method negotiates format and frame with the device. This also
 * implies a frame interval setting, and the bandwith depends on this
 * setting as well. However, selecting the format and frame a priori 
 * does not yet fix the bandwidth, this is a consideration only for
 * isochronous transfers. Therefore this method does not do any bandwidth
 * negotiation, but leaves this to the getFrame method.
 *
 * \param interface	video streaming interface number, not the index in
 *			the videostreaming array.
 * \param format	format number, one larger than the format index
 * \param frame		frame number, equal to the bFrameIndex field of the
 *			frame descriptor
 */
void	UVCCamera::selectFormatAndFrame(uint8_t interface,
		uint8_t format, uint8_t frame) throw(USBError) {
	debug(LOG_DEBUG, DEBUG_LOG, 0,
		"select interface %d, format %d, frame %d",
		interface, format, frame);
	// We want to negotiate use of the a given format and frame.
	// To do this, we send a SET probe
	vs_control_request_t	control_request;
	memset(&control_request, 0, sizeof(control_request));
	control_request.bFormatIndex = format;
	control_request.bFrameIndex = frame;
	control_request.dwFrameInterval
		= minFrameInterval(interface, format, frame);

	// do we have to claim the interface?
	InterfacePtr	interfaceptr = (*device.activeConfig())[interface];
	debug(LOG_DEBUG, DEBUG_LOG, 0, "interface %d with %d alt settings",
		interfaceptr->interfaceNumber(),
		interfaceptr->numAltsettings());
#if 1
	interfaceptr->claim();
#endif
	VideoStreamingProbeControlRequest	rset(interfaceptr, SET_CUR,
							&control_request);
	device.controlRequest(&rset);

	// now probe the same thing, this should return a recommended
	// setting 
	VideoStreamingProbeControlRequest	rget(interfaceptr, GET_CUR);
	device.controlRequest(&rget);
	if (rget.data()->bFormatIndex != format) {
		throw USBError("cannot negotiate format index");
	}
	if (rget.data()->bFrameIndex != frame) {
		throw USBError("cannot negotiate frame index");
	}

	// if we get to this point, then negotiating the format and frame
	// was successful, and we can commit the negotiated paramters
	VideoStreamingCommitControlRequest	rcommit(interfaceptr, SET_CUR,
							rget.data());
	device.controlRequest(&rcommit);

	// we now also have to find out how many bits per pixel we can
	// expect
	USBDescriptorPtr	formatptr
		= getFormatDescriptor(interface, format);
	FormatFrameBasedDescriptor	*fd
		= dynamic_cast<FormatFrameBasedDescriptor *>(&*formatptr);
	if (NULL == fd) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "unknown pixel size");
		bitsPerPixel = 1;
	} else {
		bitsPerPixel = fd->bBitsPerPixel();
		debug(LOG_DEBUG, DEBUG_LOG, 0, "bits per pixel: %d",
			bitsPerPixel);
	}

	// just to be on the safe side, we should ask again what the
	// current settings are
	getCur(interface);
}
Ejemplo n.º 20
0
bool TSmtpMailer::cmdRset()
{
    QByteArray rset("RSET");
    return (cmd(rset) == 250);
}
Ejemplo n.º 21
0
/*************************************************************************
* This function performs an edge-based FM refinement
**************************************************************************/
void RedoMyLink(ctrl_t *ctrl, graph_t *graph, idx_t *home, idx_t me,
                idx_t you, real_t *flows, real_t *sr_cost, real_t *sr_lbavg)
{
    idx_t h, i, r;
    idx_t nvtxs, nedges, ncon;
    idx_t  pass, lastseed, totalv;
    idx_t *xadj, *adjncy, *adjwgt, *where, *vsize;
    idx_t *costwhere, *lbwhere, *selectwhere;
    idx_t *ed, *id, *bndptr, *bndind, *perm;
    real_t *nvwgt, mycost;
    real_t lbavg, *lbvec;
    real_t best_lbavg, other_lbavg = -1.0, bestcost, othercost = -1.0;
    real_t *npwgts, *pwgts, *tpwgts;
    real_t ipc_factor, redist_factor, ftmp;
    idx_t mype;
    gkMPI_Comm_rank(MPI_COMM_WORLD, &mype);


    WCOREPUSH;

    nvtxs  = graph->nvtxs;
    nedges = graph->nedges;
    ncon   = graph->ncon;
    xadj   = graph->xadj;
    nvwgt  = graph->nvwgt;
    vsize  = graph->vsize;
    adjncy = graph->adjncy;
    adjwgt = graph->adjwgt;
    where  = graph->where;

    ipc_factor    = ctrl->ipc_factor;
    redist_factor = ctrl->redist_factor;

    /* set up data structures */
    id     = graph->sendind = iwspacemalloc(ctrl, nvtxs);
    ed     = graph->recvind = iwspacemalloc(ctrl, nvtxs);
    bndptr = graph->sendptr = iwspacemalloc(ctrl, nvtxs);
    bndind = graph->recvptr = iwspacemalloc(ctrl, nvtxs);

    costwhere = iwspacemalloc(ctrl, nvtxs);
    lbwhere   = iwspacemalloc(ctrl, nvtxs);
    perm      = iwspacemalloc(ctrl, nvtxs);

    lbvec  = rwspacemalloc(ctrl, ncon);
    pwgts  = rset(2*ncon, 0.0, rwspacemalloc(ctrl, 2*ncon));
    npwgts = rwspacemalloc(ctrl, 2*ncon);
    tpwgts = rwspacemalloc(ctrl, 2*ncon);

    graph->gnpwgts = npwgts;

    RandomPermute(nvtxs, perm, 1);
    icopy(nvtxs, where, costwhere);
    icopy(nvtxs, where, lbwhere);

    /* compute target pwgts */
    for (h=0; h<ncon; h++) {
        tpwgts[h]      = -1.0*flows[h];
        tpwgts[ncon+h] = flows[h];
    }

    for (i=0; i<nvtxs; i++) {
        if (where[i] == me) {
            for (h=0; h<ncon; h++) {
                tpwgts[h] += nvwgt[i*ncon+h];
                pwgts[h]  += nvwgt[i*ncon+h];
            }
        }
        else {
            ASSERT(where[i] == you);
            for (h=0; h<ncon; h++) {
                tpwgts[ncon+h] += nvwgt[i*ncon+h];
                pwgts[ncon+h]  += nvwgt[i*ncon+h];
            }
        }
    }

    /* we don't want any weights to be less than zero */
    for (h=0; h<ncon; h++) {
        if (tpwgts[h] < 0.0) {
            tpwgts[ncon+h] += tpwgts[h];
            tpwgts[h] = 0.0;
        }

        if (tpwgts[ncon+h] < 0.0) {
            tpwgts[h] += tpwgts[ncon+h];
            tpwgts[ncon+h] = 0.0;
        }
    }


    /* now compute new bisection */
    bestcost = (real_t)isum(nedges, adjwgt, 1)*ipc_factor +
               (real_t)isum(nvtxs, vsize, 1)*redist_factor;
    best_lbavg = 10.0;

    lastseed = 0;
    for (pass=N_MOC_REDO_PASSES; pass>0; pass--) {
        iset(nvtxs, 1, where);

        /* find seed vertices */
        r = perm[lastseed] % nvtxs;
        lastseed = (lastseed+1) % nvtxs;
        where[r] = 0;

        Mc_Serial_Compute2WayPartitionParams(ctrl, graph);
        Mc_Serial_Init2WayBalance(ctrl, graph, tpwgts);
        Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4);
        Mc_Serial_Balance2Way(ctrl, graph, tpwgts, 1.02);
        Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4);

        for (i=0; i<nvtxs; i++)
            where[i] = (where[i] == 0) ? me : you;

        for (i=0; i<ncon; i++) {
            ftmp = (pwgts[i]+pwgts[ncon+i])/2.0;
            if (ftmp != 0.0)
                lbvec[i] = fabs(npwgts[i]-tpwgts[i])/ftmp;
            else
                lbvec[i] = 0.0;
        }
        lbavg = ravg(ncon, lbvec);

        totalv = 0;
        for (i=0; i<nvtxs; i++)
            if (where[i] != home[i])
                totalv += vsize[i];

        mycost = (real_t)(graph->mincut)*ipc_factor + (real_t)totalv*redist_factor;

        if (bestcost >= mycost) {
            bestcost = mycost;
            other_lbavg = lbavg;
            icopy(nvtxs, where, costwhere);
        }

        if (best_lbavg >= lbavg) {
            best_lbavg = lbavg;
            othercost = mycost;
            icopy(nvtxs, where, lbwhere);
        }
    }

    if (other_lbavg <= .05) {
        selectwhere = costwhere;
        *sr_cost = bestcost;
        *sr_lbavg = other_lbavg;
    }
    else {
        selectwhere = lbwhere;
        *sr_cost = othercost;
        *sr_lbavg = best_lbavg;
    }

    icopy(nvtxs, selectwhere, where);

    WCOREPOP;
}
Ejemplo n.º 22
0
Archivo: pcpd.c Proyecto: zixia/nospam
static void mainloop(struct PCP *pcp)
{
	int c;
	struct pcpdtimer inactivity_timeout;
	int my_acl_flags=PCP_ACL_MODIFY|PCP_ACL_CONFLICT|
		PCP_ACL_LIST|PCP_ACL_RETR;

	deleted_eventid=NULL;
	memset(&new_commit, 0, sizeof(new_commit));
	new_commit_times=NULL;
	new_commit_participants=NULL;
	new_commit_participants_buf=NULL;

	termsig=0;

	setsigs();

	inp_ptr=0;
	inp_left=0;
	need_rset=0;

	time(&prev_time);

	pcpdtimer_init(&inactivity_timeout);
	inactivity_timeout.handler=inactive;

	if (proxy_userid)
	{
		struct get_acl ga;

		ga.who=proxy_userid;
		ga.flags=0;
		if (pcp_has_acl(pcp))
		{
			if (pcp_list_acl(pcp, get_acl_callback, &ga) == 0)
			{
				if (ga.flags == 0)
				{
					ga.who="public";
					if (pcp_list_acl(pcp, get_acl_callback,
							 &ga))
						ga.flags=0;
				}
			}
			else ga.flags=0;
		}
		my_acl_flags=ga.flags;
	}

	do
	{
		char *p;

		input_line_len=0;
		pcpdtimer_install(&inactivity_timeout, 30 * 60);

		for (;;)
		{


			c=inputchar(pcp);

			if (termsig || c == '\n')
				break;
			input_buffer[input_line_len++]=c;
		}
		if (termsig)
			break;

		input_buffer[input_line_len]=0;

		for (p=input_buffer; *p; p++)
			if (isspace((int)(unsigned char)*p))
				*p=' ';
		pcpdtimer_triggered(&inactivity_timeout);
		/* Cancel inactivity_timeout for the duration of the command */

	} while (doline(pcp, input_buffer, my_acl_flags) == 0 && !termsig);
	alarm(0);
	free(input_buffer);
	rset(pcp);
}