Пример #1
0
 void run() {
    scan();
    E();
 }
Пример #2
0
void GeneratedKey(char *p_fname, char *q_fname, char *e_fname, char *name)
{
    BigInt P(p_fname, false), Q(q_fname, false), E(e_fname, false);
    BigInt N = P * Q, Fi, FiEl("1"), D("1");
    Fi = (P - BigInt("1")) * (Q - BigInt("1"));
	int amount = 5761456;
	/*std::ifstream num("simpleNum.txt");
	amount = Space(num);
	num.close();*/
	std::ifstream ifst("simpleNum.txt");
	if(!ifst)
	{
		GenetateSimpleList();
		ifst.open("simpleNum.txt");
	}
	int **degree, i;
	char *buf_ch = new char[10];
    BigInt A = BigInt(&Fi), B, buf_bi;
	degree = new int *[2];
	for(i = 0; i < 2; i ++)
		degree[i] = new int [amount];
	memset(degree[0], 0, 4 * amount);
	memset(degree[1], 0, 4 * amount);
	i = 0;
	bool end = true;
	while(end)
	{
		buf_ch = getSimpleNum(ifst);
        if((A % BigInt(buf_ch)) == BigInt("0"))
		{
            A /= BigInt(buf_ch);
			degree[0][i] = charToInt(buf_ch);
			degree[1][i]++;
			i = 0;
			ifst.seekg (0, ifst.beg);
		}
		else
			i++;
        if(A == BigInt("1"))
			end = false;
	}
	ifst.close();
	for(i = 0; i < amount; i++)
	{
		if(degree[0][i] != 0)
		{
            A = B = BigInt(intToChar(degree[0][i]));
            A ^= BigInt(intToChar(degree[1][i]));
            B ^= BigInt(intToChar(degree[1][i] - 1));
			buf_bi = A - B;
			FiEl *= buf_bi;
		}
	}
	FiEl--;
    BigInt DegreeNet[RNet];
	DegreeNet[0] = D * E;
	DegreeNet[0] %= Fi;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= Fi;
	}
    BigInt degreeNum[RNet];
    degreeNum[0] = BigInt("1");
	for(int i = 1; i < RNet; i++)
        degreeNum[i] = degreeNum[i-1] * BigInt("2");
    BigInt I("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(FiEl >= I + degreeNum[j])
		{
			D *= DegreeNet[j];
			D %= Fi;
			I += degreeNum[j];
		}
		else
			j--;
	}
	char fname[32];
	strcpy(fname, name);
	strcat(fname, "N.txt");
	N.TextWrite(fname);
	strcpy(fname, name);
	strcat(fname, "D.txt");
	D.TextWrite(fname);
};
Пример #3
0
IGL_INLINE void igl::simplify_polyhedron(
  const Eigen::MatrixXd & OV,
  const Eigen::MatrixXi & OF,
  Eigen::MatrixXd & V,
  Eigen::MatrixXi & F,
  Eigen::VectorXi & J)
{
  // TODO: to generalize to open meshes, 0-cost should keep all incident
  // boundary edges on their original lines. (for non-manifold meshes,
  // igl::decimate needs to be generalized)

  Eigen::MatrixXd N;
  // Function for computing cost of collapsing edge (0 if at least one
  // direction doesn't change pointset, inf otherwise) and placement (in lowest
  // cost direction).
  const auto & perfect= [&N](
    const int e,
    const Eigen::MatrixXd & V,
    const Eigen::MatrixXi & F,
    const Eigen::MatrixXi & E,
    const Eigen::VectorXi & EMAP,
    const Eigen::MatrixXi & EF,
    const Eigen::MatrixXi & EI,
    double & cost,
    Eigen::RowVectorXd & p)
  {
    // Function for ocmputing cost (0 or inf) of collapsing edge by placing
    // vertex at `positive` end of edge.
    const auto & perfect_directed = [&N](
      const int e,
      const bool positive,
      const Eigen::MatrixXd & V,
      const Eigen::MatrixXi & F,
      const Eigen::MatrixXi & E,
      const Eigen::VectorXi & EMAP,
      const Eigen::MatrixXi & EF,
      const Eigen::MatrixXi & EI,
      double & cost,
      Eigen::RowVectorXd & p)
    {
      const auto vi = E(e,positive);
      const auto vj = E(e,!positive);
      p = V.row(vj);
      std::vector<int> faces = igl::circulation(e,positive,F,E,EMAP,EF,EI);
      cost = 0;
      for(auto f : faces)
      {
        // Skip the faces being collapsed
        if(f == EF(e,0) || f == EF(e,1))
        {
          continue;
        }
        const Eigen::RowVectorXd nbefore = N.row(f);
        // Face with vi replaced with vj
        const Eigen::RowVector3i fafter(
            F(f,0) == vi ? vj : F(f,0),
            F(f,1) == vi ? vj : F(f,1),
            F(f,2) == vi ? vj : F(f,2));
        Eigen::RowVectorXd nafter;
        igl::per_face_normals(V,fafter,nafter);
        const double epsilon = 1e-10;
        // if normal changed then not feasible, break
        if((nbefore-nafter).norm() > epsilon)
        {
          cost = std::numeric_limits<double>::infinity();
          break;
        }
      }
    }; 
    p.resize(3);
    double cost0, cost1;
    Eigen::RowVectorXd p0, p1;
    perfect_directed(e,false,V,F,E,EMAP,EF,EI,cost0,p0);
    perfect_directed(e,true,V,F,E,EMAP,EF,EI,cost1,p1);
    if(cost0 < cost1)
    {
      cost = cost0;
      p = p0;
    }else
    {
      cost = cost1;
      p = p1;
    }
  };
  igl::per_face_normals(OV,OF,N);
  Eigen::VectorXi I;
  igl::decimate(
    OV,OF,
    perfect,
    igl::infinite_cost_stopping_condition(perfect),
    V,F,J,I);
}
Пример #4
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor;
	int count;
	int *values;
	char sval[32];
	char kval[sizeof(int)];

	srandom(time(NULL));

	memset(sval, 0, sizeof(sval));

	count = (random()%384) + 64;
	values = (int *)malloc(count*sizeof(int));

	for(i = 0;i<count;i++) {
		values[i] = random()%1024;
	}

	E(mdb_env_create(&env));
	E(mdb_env_set_mapsize(env, 10485760));
	E(mdb_env_set_maxdbs(env, 4));
	E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
	E(mdb_txn_begin(env, NULL, 0, &txn));
	E(mdb_open(txn, "id2", MDB_CREATE|MDB_DUPSORT, &dbi));

	key.mv_size = sizeof(int);
	key.mv_data = kval;
	data.mv_size = sizeof(sval);
	data.mv_data = sval;

	printf("Adding %d values\n", count);
	for (i=0;i<count;i++) {
		if (!(i & 0x0f))
			sprintf(kval, "%03x", values[i]);
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA)))
			j++;
	}
	if (j) printf("%d duplicates skipped\n", j);
	E(mdb_txn_commit(txn));
	E(mdb_env_stat(env, &mst));

	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %p %.*s, data: %p %.*s\n",
			key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
			data.mv_data, (int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	j=0;

	for (i= count - 1; i > -1; i-= (random()%5)) {
		j++;
		txn=NULL;
		E(mdb_txn_begin(env, NULL, 0, &txn));
		sprintf(kval, "%03x", values[i & ~0x0f]);
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		key.mv_size = sizeof(int);
		key.mv_data = kval;
		data.mv_size = sizeof(sval);
		data.mv_data = sval;
		if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
			j--;
			mdb_txn_abort(txn);
		} else {
			E(mdb_txn_commit(txn));
		}
	}
	free(values);
	printf("Deleted %d values\n", j);

	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	printf("Cursor next\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	printf("Cursor prev\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_close(env, dbi);

	mdb_txn_abort(txn);
	mdb_env_close(env);

	return 0;
}
Пример #5
0
int main() {
  union supp *p;
  if(! HAS_KIND(p, SAFE_KIND)) E(1);

  SUCCESS;
}
Пример #6
0
int cs_routine(int fd, sqlite3 *db)
{
    sockfd_buf_t *rwbuf = sockfd_list[fd];

    if (rwbuf == NULL)
        return -1;
    if (rwbuf->rbuf.data == NULL)
        return -1;
    if (rwbuf->wbuf.data == NULL)
        return -1;

    int n = read(fd, rwbuf->rbuf.data, rwbuf->rbuf.max);
    if (n < 0) {
        E("%s", strerror(errno));
        return -1;
    } else if (n == 0) {
        sockfd_buf_free(rwbuf);
        sockfd_list[fd] = NULL;

        unregister_readfd(fd);
        unregister_writefd(fd);
        unregister_exceptfd(fd);

        close(fd);
        D(GREEN"close %d client success."NO, fd);
        return 0;
    }

    D(GREEN"receive %s %d bytes from %d."NO, 
      rwbuf->rbuf.data, n, fd);
    rwbuf->rbuf.len = n;

    DDBUF(rwbuf->rbuf);
    rwbuf->rbuf.len -= 4;
    strncpy(rwbuf->rbuf.data, rwbuf->rbuf.data + 4, rwbuf->rbuf.len);
    DDSTR(rwbuf->rbuf);

    n = sql_routine(fd, db, rwbuf);
    if (n == -1) {
        E("sql_routine() failed.");
        
        if (rwbuf->wbuf.len == 0) {
            strncpy(rwbuf->wbuf.data, "err", 3);
            rwbuf->wbuf.len = 3;
        }
        //return -1;
    }

    D(GREEN"send %s %d bytes to %d."NO, 
      rwbuf->wbuf.data, rwbuf->wbuf.len, fd);

    //rwbuf->wbuf.data[0] = '\0';
    //rwbuf->wbuf.data[1] = '\0';
    //rwbuf->wbuf.data[2] = '\0';
    //rwbuf->wbuf.data[3] = 8;
    //DDBUF(rwbuf->wbuf);

    n = write(fd, rwbuf->wbuf.data, rwbuf->wbuf.len);
    if (n == -1) {
        E("%s", strerror(errno));
        return -1;
    }

    memset(rwbuf->wbuf.data, 0, rwbuf->wbuf.max);
    rwbuf->wbuf.len = 0;
    memset(rwbuf->rbuf.data, 0, rwbuf->rbuf.max);
    rwbuf->rbuf.len = 0;

    return 0;
}
Пример #7
0
Файл: cont.c Проект: genki/ruby
static void
register_stack_extend(rb_context_t *cont, VALUE *curr_bsp)
{
    if (rb_dummy_false) {
        /* use registers as much as possible */
        E(a) = E(b) = E(c) = E(d) = E(e) =
        E(f) = E(g) = E(h) = E(i) = E(j) =
        E(k) = E(l) = E(m) = E(n) = E(o) =
        E(p) = E(q) = E(r) = E(s) = E(t) = 0;
        E(a) = E(b) = E(c) = E(d) = E(e) =
        E(f) = E(g) = E(h) = E(i) = E(j) =
        E(k) = E(l) = E(m) = E(n) = E(o) =
        E(p) = E(q) = E(r) = E(s) = E(t) = 0;
    }
    if (curr_bsp < cont->machine_register_stack_src+cont->machine_register_stack_size) {
        register_stack_extend(cont, (VALUE*)rb_ia64_bsp());
    }
    cont_restore_1(cont);
}
Пример #8
0
inline void ALM
( const AbstractDistMatrix<F>& MPre, 
        AbstractDistMatrix<F>& LPre, AbstractDistMatrix<F>& SPre, 
  const RPCACtrl<Base<F>>& ctrl )
{
    auto MPtr = ReadProxy<F,MC,MR>( &MPre ); auto& M = *MPtr;
    auto LPtr = WriteProxy<F,MC,MR>( &LPre ); auto& L = *LPtr;
    auto SPtr = WriteProxy<F,MC,MR>( &SPre ); auto& S = *SPtr;

    typedef Base<F> Real;
    const Int m = M.Height();
    const Int n = M.Width();
    const Int commRank = mpi::Rank( M.Grid().Comm() );

    // If tau is unspecified, set it to 1/sqrt(max(m,n))
    const Base<F> tau = 
      ( ctrl.tau <= Real(0) ? Real(1) / sqrt(Real(Max(m,n))) : ctrl.tau );
    if( ctrl.tol <= Real(0) )
        LogicError("tol cannot be non-positive");
    const Base<F> tol = ctrl.tol;

    const double startTime = mpi::Time();

    DistMatrix<F> Y( M );
    NormalizeEntries( Y );
    const Real twoNorm = TwoNorm( Y );
    const Real maxNorm = MaxNorm( Y );
    const Real infNorm = maxNorm / tau; 
    const Real dualNorm = Max( twoNorm, infNorm );
    Scale( F(1)/dualNorm, Y );

    // If beta is unspecified, set it to 1 / 2 || sign(M) ||_2
    Base<F> beta = 
      ( ctrl.beta <= Real(0) ? Real(1) / (2*twoNorm) : ctrl.beta );

    const Real frobM = FrobeniusNorm( M );
    const Real maxM = MaxNorm( M );
    if( ctrl.progress && commRank == 0 )
        cout << "|| M ||_F = " << frobM << "\n"
             << "|| M ||_max = " << maxM << endl;

    Zeros( L, m, n );
    Zeros( S, m, n );

    Int numIts=0, numPrimalIts=0;
    DistMatrix<F> LLast( M.Grid() ), SLast( M.Grid() ), E( M.Grid() );
    while( true )
    {
        ++numIts;
       
        Int rank, numNonzeros;
        while( true )
        {
            ++numPrimalIts;

            LLast = L;
            SLast = S;

            // ST_{tau/beta}(M - L + Y/beta)
            S = M;
            Axpy( F(-1), L, S );
            Axpy( F(1)/beta, Y, S );
            SoftThreshold( S, tau/beta );
            numNonzeros = ZeroNorm( S );

            // SVT_{1/beta}(M - S + Y/beta)
            L = M;
            Axpy( F(-1), S, L );
            Axpy( F(1)/beta, Y, L );
            if( ctrl.usePivQR )
                rank = SVT( L, Real(1)/beta, ctrl.numPivSteps );
            else
                rank = SVT( L, Real(1)/beta );

            Axpy( F(-1), L, LLast );
            Axpy( F(-1), S, SLast );
            const Real frobLDiff = FrobeniusNorm( LLast );
            const Real frobSDiff = FrobeniusNorm( SLast );

            if( frobLDiff/frobM < tol && frobSDiff/frobM < tol )
            {
                if( ctrl.progress && commRank == 0 )
                    cout << "Primal loop converged: " 
                         << mpi::Time()-startTime << " total secs" << endl;
                break;
            }
            else 
            {
                if( ctrl.progress && commRank == 0 )
                    cout << "  " << numPrimalIts 
                         << ": \n"
                         << "   || Delta L ||_F / || M ||_F = " 
                         << frobLDiff/frobM << "\n"
                         << "   || Delta S ||_F / || M ||_F = "
                         << frobSDiff/frobM << "\n"
                         << "   rank=" << rank
                         << ", numNonzeros=" << numNonzeros 
                         << ", " << mpi::Time()-startTime << " total secs" 
                         << endl;
            } 
        }

        // E := M - (L + S)
        E = M;    
        Axpy( F(-1), L, E );
        Axpy( F(-1), S, E );
        const Real frobE = FrobeniusNorm( E );

        if( frobE/frobM <= tol )            
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Converged after " << numIts << " iterations and "
                     << numPrimalIts << " primal iterations with rank=" 
                     << rank << ", numNonzeros=" << numNonzeros << " and "
                     << "|| E ||_F / || M ||_F = " << frobE/frobM
                     << ", " << mpi::Time()-startTime << " total secs"
                     << endl;
            break;
        }
        else if( numIts >= ctrl.maxIts )
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Aborting after " << numIts << " iterations and "
                     << mpi::Time()-startTime << " total secs" << endl;
            break;
        }
        else
        {
            if( ctrl.progress && commRank == 0 )
                cout << numPrimalIts << ": || E ||_F / || M ||_F = " 
                     << frobE/frobM << ", rank=" << rank 
                     << ", numNonzeros=" << numNonzeros << ", "
                     << mpi::Time()-startTime << " total secs" 
                     << endl;
        }
        
        // Y := Y + beta E
        Axpy( beta, E, Y );
        beta *= ctrl.rho;
    }
}
int main()
{

	int i ;
	
  /* Flush Cache*/
  A(0x90A4001C);
  W(0x00000001); 	

  /* Data memory addressing mode (0: not interleaved 1: interleaved) */
  A(0x90A80008);
  W(0x00000000);
  
  /* Data memory access priority (0: Core>BIU>CFU 1: BIU>Core>CFU) */
  A(0x90A8000C);
  W(0x00000000);    
                 
  /* Base Address */
  A(0x90A80004);
  W(0x90A00000);

  /* DBGISR */
  A(0x90A0001C);
  W(0x10000000);

  /* EXCISR */
  A(0x90A00020);
  W(0x10000000);
  
  /* FIQISR */
  A(0x90A00024);
  W(0x10000000);

  /* IRQISR */
  A(0x90A00028);
  W(0x10000000); 
      
  /* Start address to PSCU */
  A(0x90A00000);
  W(0x10000000);
  
  /* Start Address to ICache */
  A(0x90A40008);
  W(0x10000000);
  
  /* Initial program size to ICache */
  A(0x90A4000C);
  W(0x00000B6C); /* Size x 1024bits */

  /* Miss program size to ICache */
  A(0x90A40018);
  W(0x00000003); /* Size x 1024bits */

  /* Configure ICache size*/
  A(0x90A40000);
  W(0x00000000);  
  
  /* Configure ICache to cahce/scratch pad mode*/
  A(0x90A40004);
  W(0x00000000);   
  
  /* Start ICache initialization*/
  A(0x90A40010);
  W(0x00000000); 
  
  /* Start the program operation  */ 
  A(0x90A00004);
  W(0x00000001);

  /* Control vector (two address vector followed by one read/write vector) */
  /* WAIT     = {Bit[11]}												   */
  /* HPROT    = {Bit[10:9], Bit[6:5]}									   */
  /* HLOCK    = {Bit[4]} 										   	 	   */
  /* HsizeGen = {Bit[3:2]}										    	   */
  A(0xC0000000);             
  for (i = 0; i <= 2000; i++) 
    R(0x00000000,All_Mask);  
    
  A(0x25000100); W(0x00000000);
  A(0x25000104); W(0x00000000);
  A(0x25000108); W(0x00000000);
  A(0x2500010C); W(0x00000000);
  /* Result check */
  /* Store        */
  A(0x25000100); R(0x30201000,0xFFFFFFFF);
  A(0x25000104); R(0x70605040,0xFFFFFFFF);
  A(0x25000108); R(0xB0A09080,0xFFFFFFFF);
  A(0x2500010C); R(0xF0E0D0C0,0xFFFFFFFF);
  
  E();
          
  return 0;  
  
} 
int main()
{



  /* Initial DATA */
  /* =================== */

  /* Residual */
  A(0x25000000); W(0x00000000);

  A(0x25000004); W(0x00000000);

  A(0x25000008); W(0x00000000);

  A(0x2500000c); W(0x00000000);

  A(0x25000010); W(0x00000000);

  A(0x25000014); W(0x00000000);

  A(0x25000018); W(0x00000000);

  A(0x2500001c); W(0x00000000);

  A(0x25000020); W(0x00000000);

  A(0x25000024); W(0x00000000);

  A(0x25000028); W(0x00000000);

  A(0x2500002c); W(0x00000000);

  A(0x25000030); W(0x00000000);

  A(0x25000034); W(0x00000000);

  A(0x25000038); W(0x00000000);

  A(0x2500003c); W(0x00000000);

  A(0x25000040); W(0x00000000);

  A(0x25000044); W(0x00000000);

  A(0x25000048); W(0x00000000);

  A(0x2500004c); W(0x00000000);

  A(0x25000050); W(0x00000000);

  A(0x25000054); W(0x00000000);

  A(0x25000058); W(0x00000000);

  A(0x2500005c); W(0x00000000);

  A(0x25000060); W(0x00000000);

  A(0x25000064); W(0x00000000);

  A(0x25000068); W(0x00000000);

  A(0x2500006c); W(0x00000000);

  A(0x25000070); W(0x00000000);

  A(0x25000074); W(0x00000000);

  A(0x25000078); W(0x00000000);

  A(0x2500007c); W(0x00000000);

  A(0x25000080); W(0x00000000);

  A(0x25000084); W(0x00000000);

  A(0x25000088); W(0x00000000);

  A(0x2500008c); W(0x00000000);

  A(0x25000090); W(0x00000000);

  A(0x25000094); W(0x00000000);

  A(0x25000098); W(0x00000000);

  A(0x2500009c); W(0x00000000);

  A(0x250000a0); W(0x00000000);

  A(0x250000a4); W(0x00000000);

  A(0x250000a8); W(0x00000000);

  A(0x250000ac); W(0x00000000);

  A(0x250000b0); W(0x00000000);

  A(0x250000b4); W(0x00000000);

  A(0x250000b8); W(0x00000000);

  A(0x250000bc); W(0x00000000);

  A(0x250000c0); W(0x00000000);

  A(0x250000c4); W(0x00000000);

  A(0x250000c8); W(0x00000000);

  A(0x250000cc); W(0x00000000);

  A(0x250000d0); W(0x00000000);

  A(0x250000d4); W(0x00000000);

  A(0x250000d8); W(0x00000000);

  A(0x250000dc); W(0x00000000);

  A(0x250000e0); W(0x00000000);

  A(0x250000e4); W(0x00000000);

  A(0x250000e8); W(0x00000000);

  A(0x250000ec); W(0x00000000);

  A(0x250000f0); W(0x00000000);

  A(0x250000f4); W(0x00000000);

  A(0x250000f8); W(0x00000000);

  A(0x250000fc); W(0x00000000);

  A(0x25000100); W(0x00000000);

  A(0x25000104); W(0x00000000);

  A(0x25000108); W(0x00000000);

  A(0x2500010c); W(0x00000000);

  A(0x25000110); W(0x00000000);

  A(0x25000114); W(0x00000000);

  A(0x25000118); W(0x00000000);

  A(0x2500011c); W(0x00000000);

  A(0x25000120); W(0x00000000);

  A(0x25000124); W(0x00000000);

  A(0x25000128); W(0x00000000);

  A(0x2500012c); W(0x00000000);

  A(0x25000130); W(0x00000000);

  A(0x25000134); W(0x00000000);

  A(0x25000138); W(0x00000000);

  A(0x2500013c); W(0x00000000);

  A(0x25000140); W(0x00000000);

  A(0x25000144); W(0x00000000);

  A(0x25000148); W(0x00000000);

  A(0x2500014c); W(0x00000000);

  A(0x25000150); W(0x00000000);

  A(0x25000154); W(0x00000000);

  A(0x25000158); W(0x00000000);

  A(0x2500015c); W(0x00000000);

  A(0x25000160); W(0x00000000);

  A(0x25000164); W(0x00000000);

  A(0x25000168); W(0x00000000);

  A(0x2500016c); W(0x00000000);

  A(0x25000170); W(0x00000000);

  A(0x25000174); W(0x00000000);

  A(0x25000178); W(0x00000000);

  A(0x2500017c); W(0x00000000);

  A(0x25000180); W(0x00000000);

  A(0x25000184); W(0x00000000);

  A(0x25000188); W(0x00000000);

  A(0x2500018c); W(0x00000000);

  A(0x25000190); W(0x00000000);

  A(0x25000194); W(0x00000000);

  A(0x25000198); W(0x00000000);

  A(0x2500019c); W(0x00000000);

  A(0x250001a0); W(0x00000000);

  A(0x250001a4); W(0x00000000);

  A(0x250001a8); W(0x00000000);

  A(0x250001ac); W(0x00000000);

  A(0x250001b0); W(0x00000000);

  A(0x250001b4); W(0x00000000);

  A(0x250001b8); W(0x00000000);

  A(0x250001bc); W(0x00000000);

  A(0x250001c0); W(0x00000000);

  A(0x250001c4); W(0x00000000);

  A(0x250001c8); W(0x00000000);

  A(0x250001cc); W(0x00000000);

  A(0x250001d0); W(0x00000000);

  A(0x250001d4); W(0x00000000);

  A(0x250001d8); W(0x00000000);

  A(0x250001dc); W(0x00000000);

  A(0x250001e0); W(0x00000000);

  A(0x250001e4); W(0x00000000);

  A(0x250001e8); W(0x00000000);

  A(0x250001ec); W(0x00000000);

  A(0x250001f0); W(0x00000000);

  A(0x250001f4); W(0x00000000);

  A(0x250001f8); W(0x00000000);

  A(0x250001fc); W(0x00000000);

  /* PreRowPelY */
  A(0x25000200); W(0x0a0a0a0a);

  A(0x25000204); W(0x0a0a0a0a);

  A(0x25000208); W(0x0a0a0a0a);

  A(0x2500020c); W(0x0a0a0a0a);

  /* PreColPelY */
  A(0x25000210); W(0x14141414);

  A(0x25000214); W(0x14141414);

  A(0x25000218); W(0x14141414);

  A(0x2500021c); W(0x14141414);

  A(0x25000220); W(0x00000014);

  /* parameters setting */
  A(0x25000228); W(0x00020300);

  A(0x2500022c); W(0xffff0300);

  A(0x25000230); W(0x02000210);

  A(0x25000234); W(0x00000000);

  /* =================== */
  /* End of initial DATA */


  /* compare result */
  /* Keep reading CBUSY for delaying the result check */
  int i;

  A(0x24050008);
  for (i = 0; i <= 300; i++)
    R(0x00000000,All_Mask);

  /* OutYReconstructed */
  A(0x25000300); R(0x0f0f0f0f,NO_Mask);
  A(0x25000304); R(0x0f0f0f0f,NO_Mask);
  A(0x25000308); R(0x0f0f0f0f,NO_Mask);
  A(0x2500030c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000310); R(0x0f0f0f0f,NO_Mask);
  A(0x25000314); R(0x0f0f0f0f,NO_Mask);
  A(0x25000318); R(0x0f0f0f0f,NO_Mask);
  A(0x2500031c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000320); R(0x0f0f0f0f,NO_Mask);
  A(0x25000324); R(0x0f0f0f0f,NO_Mask);
  A(0x25000328); R(0x0f0f0f0f,NO_Mask);
  A(0x2500032c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000330); R(0x0f0f0f0f,NO_Mask);
  A(0x25000334); R(0x0f0f0f0f,NO_Mask);
  A(0x25000338); R(0x0f0f0f0f,NO_Mask);
  A(0x2500033c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000340); R(0x0f0f0f0f,NO_Mask);
  A(0x25000344); R(0x0f0f0f0f,NO_Mask);
  A(0x25000348); R(0x0f0f0f0f,NO_Mask);
  A(0x2500034c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000350); R(0x0f0f0f0f,NO_Mask);
  A(0x25000354); R(0x0f0f0f0f,NO_Mask);
  A(0x25000358); R(0x0f0f0f0f,NO_Mask);
  A(0x2500035c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000360); R(0x0f0f0f0f,NO_Mask);
  A(0x25000364); R(0x0f0f0f0f,NO_Mask);
  A(0x25000368); R(0x0f0f0f0f,NO_Mask);
  A(0x2500036c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000370); R(0x0f0f0f0f,NO_Mask);
  A(0x25000374); R(0x0f0f0f0f,NO_Mask);
  A(0x25000378); R(0x0f0f0f0f,NO_Mask);
  A(0x2500037c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000380); R(0x0f0f0f0f,NO_Mask);
  A(0x25000384); R(0x0f0f0f0f,NO_Mask);
  A(0x25000388); R(0x0f0f0f0f,NO_Mask);
  A(0x2500038c); R(0x0f0f0f0f,NO_Mask);
  A(0x25000390); R(0x0f0f0f0f,NO_Mask);
  A(0x25000394); R(0x0f0f0f0f,NO_Mask);
  A(0x25000398); R(0x0f0f0f0f,NO_Mask);
  A(0x2500039c); R(0x0f0f0f0f,NO_Mask);
  A(0x250003a0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003a4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003a8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003ac); R(0x0f0f0f0f,NO_Mask);
  A(0x250003b0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003b4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003b8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003bc); R(0x0f0f0f0f,NO_Mask);
  A(0x250003c0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003c4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003c8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003cc); R(0x0f0f0f0f,NO_Mask);
  A(0x250003d0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003d4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003d8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003dc); R(0x0f0f0f0f,NO_Mask);
  A(0x250003e0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003e4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003e8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003ec); R(0x0f0f0f0f,NO_Mask);
  A(0x250003f0); R(0x0f0f0f0f,NO_Mask);
  A(0x250003f4); R(0x0f0f0f0f,NO_Mask);
  A(0x250003f8); R(0x0f0f0f0f,NO_Mask);
  A(0x250003fc); R(0x0f0f0f0f,NO_Mask);


  E();

  return 0;

}
Пример #11
0
inline void ADMM
( const AbstractDistMatrix<F>& MPre, AbstractDistMatrix<F>& LPre, 
        AbstractDistMatrix<F>& SPre, const RPCACtrl<Base<F>>& ctrl )
{
    auto MPtr = ReadProxy<F,MC,MR>( &MPre ); auto& M = *MPtr;
    auto LPtr = WriteProxy<F,MC,MR>( &LPre ); auto& L = *LPtr;
    auto SPtr = WriteProxy<F,MC,MR>( &SPre ); auto& S = *SPtr;

    typedef Base<F> Real;
    const Int m = M.Height();
    const Int n = M.Width();
    const Int commRank = mpi::Rank( M.Grid().Comm() );

    // If tau is not specified, then set it to 1/sqrt(max(m,n))
    const Base<F> tau = 
        ( ctrl.tau <= Real(0) ? Real(1)/sqrt(Real(Max(m,n))) : ctrl.tau );
    if( ctrl.beta <= Real(0) )
        LogicError("beta cannot be non-positive");
    if( ctrl.tol <= Real(0) )
        LogicError("tol cannot be non-positive");
    const Base<F> beta = ctrl.beta;
    const Base<F> tol = ctrl.tol;

    const double startTime = mpi::Time();
    DistMatrix<F> E( M.Grid() ), Y( M.Grid() );
    Zeros( Y, m, n );

    const Real frobM = FrobeniusNorm( M );
    const Real maxM = MaxNorm( M );
    if( ctrl.progress && commRank == 0 )
        cout << "|| M ||_F = " << frobM << "\n"
             << "|| M ||_max = " << maxM << endl;

    Zeros( L, m, n );
    Zeros( S, m, n );

    Int numIts = 0;
    while( true )
    {
        ++numIts;

        // ST_{tau/beta}(M - L + Y/beta)
        S = M;
        Axpy( F(-1), L, S );
        Axpy( F(1)/beta, Y, S );
        SoftThreshold( S, tau/beta );
        const Int numNonzeros = ZeroNorm( S );

        // SVT_{1/beta}(M - S + Y/beta)
        L = M;
        Axpy( F(-1), S, L );
        Axpy( F(1)/beta, Y, L );
        Int rank;
        if( ctrl.usePivQR )
            rank = SVT( L, Real(1)/beta, ctrl.numPivSteps );
        else
            rank = SVT( L, Real(1)/beta );
      
        // E := M - (L + S)
        E = M;    
        Axpy( F(-1), L, E );
        Axpy( F(-1), S, E );
        const Real frobE = FrobeniusNorm( E );

        if( frobE/frobM <= tol )            
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Converged after " << numIts << " iterations "
                     << " with rank=" << rank 
                     << ", numNonzeros=" << numNonzeros << " and "
                     << "|| E ||_F / || M ||_F = " << frobE/frobM
                     << ", and " << mpi::Time()-startTime << " total secs"
                     << endl;
            break;
        }
        else if( numIts >= ctrl.maxIts )
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Aborting after " << numIts << " iterations and "
                     << mpi::Time()-startTime << " total secs" 
                     << endl;
            break;
        }
        else
        {
            if( ctrl.progress && commRank == 0 )
                cout << numIts << ": || E ||_F / || M ||_F = " 
                     << frobE/frobM << ", rank=" << rank 
                     << ", numNonzeros=" << numNonzeros 
                     << ", " << mpi::Time()-startTime << " total secs"
                     << endl;
        }
        
        // Y := Y + beta E
        Axpy( beta, E, Y );
    }
}
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor, *cur2;
	MDB_cursor_op op;
	int count;
	int *values;
	char sval[32] = "";

	srand(time(NULL));

	    count = (rand()%384) + 64;
	    values = (int *)malloc(count*sizeof(int));

	    for(i = 0;i<count;i++) {
			values[i] = rand()%1024;
	    }
    
		E(mdb_env_create(&env));
		E(mdb_env_set_maxreaders(env, 1));
		E(mdb_env_set_mapsize(env, 10485760));
		E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP /*|MDB_NOSYNC*/, 0664));

		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_dbi_open(txn, NULL, 0, &dbi));
   
		key.mv_size = sizeof(int);
		key.mv_data = sval;

		printf("Adding %d values\n", count);
	    for (i=0;i<count;i++) {	
			sprintf(sval, "%03x %d foo bar", values[i], values[i]);
			/* Set <data> in each iteration, since MDB_NOOVERWRITE may modify it */
			data.mv_size = sizeof(sval);
			data.mv_data = sval;
			if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE))) {
				j++;
				data.mv_size = sizeof(sval);
				data.mv_data = sval;
			}
	    }
		if (j) printf("%d duplicates skipped\n", j);
		E(mdb_txn_commit(txn));
		E(mdb_env_stat(env, &mst));

		E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		mdb_cursor_close(cursor);
		mdb_txn_abort(txn);

		j=0;
		key.mv_data = sval;
	    for (i= count - 1; i > -1; i-= (rand()%5)) {
			j++;
			txn=NULL;
			E(mdb_txn_begin(env, NULL, 0, &txn));
			sprintf(sval, "%03x ", values[i]);
			if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, NULL))) {
				j--;
				mdb_txn_abort(txn);
			} else {
				E(mdb_txn_commit(txn));
			}
	    }
	    free(values);
		printf("Deleted %d values\n", j);

		E(mdb_env_stat(env, &mst));
		E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		printf("Cursor next\n");
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		printf("Cursor last\n");
		E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		printf("Cursor prev\n");
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		printf("Cursor last/prev\n");
		E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		E(mdb_cursor_get(cursor, &key, &data, MDB_PREV));
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);

		mdb_cursor_close(cursor);
		mdb_txn_abort(txn);

		printf("Deleting with cursor\n");
		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_cursor_open(txn, dbi, &cur2));
		for (i=0; i<50; i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, MDB_NEXT)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
			E(mdb_del(txn, dbi, &key, NULL));
		}

		printf("Restarting cursor in txn\n");
		for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, op)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		mdb_cursor_close(cur2);
		E(mdb_txn_commit(txn));

		printf("Restarting cursor outside txn\n");
		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cursor, &key, &data, op)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		mdb_cursor_close(cursor);
		mdb_txn_abort(txn);

		mdb_dbi_close(env, dbi);
		mdb_env_close(env);

	return 0;
}
Пример #13
0
int
nmod_poly_mat_inv(nmod_poly_mat_t Ainv, nmod_poly_t den,
                    const nmod_poly_mat_t A)
{
    slong n = nmod_poly_mat_nrows(A);

    if (n == 0)
    {
        nmod_poly_one(den);
        return 1;
    }
    else if (n == 1)
    {
        nmod_poly_set(den, E(A, 0, 0));
        nmod_poly_one(E(Ainv, 0, 0));
        return !nmod_poly_is_zero(den);
    }
    else if (n == 2)
    {
        nmod_poly_mat_det(den, A);

        if (nmod_poly_is_zero(den))
        {
            return 0;
        }
        else if (Ainv == A)
        {
            nmod_poly_swap(E(A, 0, 0), E(A, 1, 1));
            nmod_poly_neg(E(A, 0, 1), E(A, 0, 1));
            nmod_poly_neg(E(A, 1, 0), E(A, 1, 0));
            return 1;
        }
        else
        {
            nmod_poly_set(E(Ainv, 0, 0), E(A, 1, 1));
            nmod_poly_set(E(Ainv, 1, 1), E(A, 0, 0));
            nmod_poly_neg(E(Ainv, 0, 1), E(A, 0, 1));
            nmod_poly_neg(E(Ainv, 1, 0), E(A, 1, 0));
            return 1;
        }
    }
    else
    {
        nmod_poly_mat_t LU, I;
        slong * perm;
        int result;

        perm = _perm_init(n);
        nmod_poly_mat_init_set(LU, A);
        result = (nmod_poly_mat_fflu(LU, den, perm, LU, 1) == n);

        if (result)
        {
            nmod_poly_mat_init(I, n, n, nmod_poly_mat_modulus(A));
            nmod_poly_mat_one(I);
            nmod_poly_mat_solve_fflu_precomp(Ainv, perm, LU, I);
            nmod_poly_mat_clear(I);
        }
        else
            nmod_poly_zero(den);

        if (_perm_parity(perm, n))
        {
            nmod_poly_mat_neg(Ainv, Ainv);
            nmod_poly_neg(den, den);
        }

        _perm_clear(perm);
        nmod_poly_mat_clear(LU);
        return result;
    }
}
/**
 * dri2_query_renderer_integer will call queryInteger with the correct DRI2 enum
 * for each GLX attribute value.
 *
 * \note
 * This test does \b not perform any checking for invalid GLX attribte values.
 * Other unit tests verify that invalid values are filtered before
 * dri2_query_renderer_integer is called.
 */
TEST_F(dri2_query_renderer_integer_test, valid_attribute_mapping)
{
   struct dri2_screen dsc;
   struct attribute_test_vector valid_attributes[] = {
      E(GLX_RENDERER_VENDOR_ID_MESA,
        __DRI2_RENDERER_VENDOR_ID),
      E(GLX_RENDERER_DEVICE_ID_MESA,
        __DRI2_RENDERER_DEVICE_ID),
      E(GLX_RENDERER_VERSION_MESA,
        __DRI2_RENDERER_VERSION),
      E(GLX_RENDERER_ACCELERATED_MESA,
        __DRI2_RENDERER_ACCELERATED),
      E(GLX_RENDERER_VIDEO_MEMORY_MESA,
        __DRI2_RENDERER_VIDEO_MEMORY),
      E(GLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA,
        __DRI2_RENDERER_UNIFIED_MEMORY_ARCHITECTURE),
      E(GLX_RENDERER_PREFERRED_PROFILE_MESA,
        __DRI2_RENDERER_PREFERRED_PROFILE),
      E(GLX_RENDERER_OPENGL_CORE_PROFILE_VERSION_MESA,
        __DRI2_RENDERER_OPENGL_CORE_PROFILE_VERSION),
      E(GLX_RENDERER_OPENGL_COMPATIBILITY_PROFILE_VERSION_MESA,
        __DRI2_RENDERER_OPENGL_COMPATIBILITY_PROFILE_VERSION),
      E(GLX_RENDERER_OPENGL_ES_PROFILE_VERSION_MESA,
        __DRI2_RENDERER_OPENGL_ES_PROFILE_VERSION),
      E(GLX_RENDERER_OPENGL_ES2_PROFILE_VERSION_MESA,
        __DRI2_RENDERER_OPENGL_ES2_PROFILE_VERSION),
   };

   memset(&dsc, 0, sizeof(dsc));
   dsc.rendererQuery = &rendererQueryExt;

   if (setjmp(jmp) == 0) {
      for (unsigned i = 0; i < ARRAY_SIZE(valid_attributes); i++) {
         unsigned int value = 0xDEADBEEF;
         const int success =
            dri2_query_renderer_integer(&dsc.base,
                                       valid_attributes[i].glx_attribute,
                                       &value);

         EXPECT_EQ(0, success);
         EXPECT_EQ(valid_attributes[i].dri_attribute, queryInteger_attribute)
            << valid_attributes[i].glx_string;
         EXPECT_EQ((unsigned int) ~valid_attributes[i].dri_attribute, value)
            << valid_attributes[i].glx_string;
      }
   } else {
      EXPECT_FALSE(got_sigsegv);
   }
}
Пример #15
0
Vector Rosen34(
	Fun           &F , 
	size_t         M , 
	const Scalar &ti , 
	const Scalar &tf , 
	const Vector &xi ,
	Vector       &e )
{
	// check numeric type specifications
	CheckNumericType<Scalar>();

	// check simple vector class specifications
	CheckSimpleVector<Scalar, Vector>();

	// Parameters for Shampine's Rosenbrock method
	// are static to avoid recalculation on each call and 
	// do not use Vector to avoid possible memory leak
	static Scalar a[3] = {
		Scalar(0),
		Scalar(1),
		Scalar(3)   / Scalar(5)
	};
	static Scalar b[2 * 2] = {
		Scalar(1),
		Scalar(0),
		Scalar(24)  / Scalar(25),
		Scalar(3)   / Scalar(25)
	};
	static Scalar ct[4] = {
		Scalar(1)   / Scalar(2),
		- Scalar(3) / Scalar(2),
		Scalar(121) / Scalar(50),
		Scalar(29)  / Scalar(250)
	};
	static Scalar cg[3 * 3] = {
		- Scalar(4),
		Scalar(0),
		Scalar(0),
		Scalar(186) / Scalar(25),
		Scalar(6)   / Scalar(5),
		Scalar(0),
		- Scalar(56) / Scalar(125),
		- Scalar(27) / Scalar(125),
		- Scalar(1)  / Scalar(5)
	};
	static Scalar d3[3] = {
		Scalar(97) / Scalar(108),
		Scalar(11) / Scalar(72),
		Scalar(25) / Scalar(216)
	};
	static Scalar d4[4] = {
		Scalar(19)  / Scalar(18),
		Scalar(1)   / Scalar(4),
		Scalar(25)  / Scalar(216),
		Scalar(125) / Scalar(216)
	};
	CppADUsageError(
		M >= 1,
		"Error in Rosen34: the number of steps is less than one"
	);
	CppADUsageError(
		e.size() == xi.size(),
		"Error in Rosen34: size of e not equal to size of xi"
	);
	size_t i, j, k, l, m;             // indices

	size_t  n    = xi.size();         // number of components in X(t)
	Scalar  ns   = Scalar(double(M)); // number of steps as Scalar object
	Scalar  h    = (tf - ti) / ns;    // step size 
	Scalar  zero = Scalar(0);         // some constants
	Scalar  one  = Scalar(1);
	Scalar  two  = Scalar(2);

	// permutation vectors needed for LU factorization routine
	CppAD::vector<size_t> ip(n), jp(n);

	// initialize e = 0
	for(i = 0; i < n; i++)
		e[i] = zero;

	// vectors used to store values returned by F
	Vector E(n * n), Eg(n), f_t(n);
	Vector g(n * 3), x3(n), x4(n), xf(n), ftmp(n), xtmp(n);

	xf = xi;           // initialize solution
	for(m = 0; m < M; m++)
	{	// time at beginning of this interval
		Scalar t = ti * (Scalar(int(M - m)) / ns) 
		         + tf * (Scalar(int(m)) / ns);

		// value of x at beginning of this interval
		x3 = x4 = xf;

		// evaluate partial derivatives at beginning of this interval
		F.Ode_ind(t, xf, f_t);
		F.Ode_dep(t, xf, E);    // E = f_x

		// E = I - f_x * h / 2
		for(i = 0; i < n; i++)
		{	for(j = 0; j < n; j++)
				E[i * n + j] = - E[i * n + j] * h / two;
			E[i * n + i] += one;
		}

		// LU factor the matrix E
		int sign = LuFactor(ip, jp, E);
		CppADUsageError(
			sign != 0,
			"Error in Rosen34: I - f_x * h / 2 not invertible"
		);

		// loop over integration steps
		for(k = 0; k < 3; k++)
		{	// set location for next function evaluation
			xtmp = xf; 
			for(l = 0; l < k; l++)
			{	// loop over previous function evaluations
				Scalar bkl = b[(k-1)*2 + l];
				for(i = 0; i < n; i++)
				{	// loop over elements of x
					xtmp[i] += bkl * g[i*3 + l] * h;
				}
			}
			// ftmp = F(t + a[k] * h, xtmp)
			F.Ode(t + a[k] * h, xtmp, ftmp); 

			// Form Eg for this integration step
			for(i = 0; i < n; i++)
				Eg[i] = ftmp[i] + ct[k] * f_t[i] * h;
			for(l = 0; l < k; l++)
			{	for(i = 0; i < n; i++)
					Eg[i] += cg[(k-1)*3 + l] * g[i*3 + l];
			}

			// Solve the equation E * g = Eg
			LuInvert(ip, jp, E, Eg);

			// save solution and advance x3, x4
			for(i = 0; i < n; i++)
			{	g[i*3 + k]  = Eg[i];
				x3[i]      += h * d3[k] * Eg[i];
				x4[i]      += h * d4[k] * Eg[i];
			}
		}
		// Form Eg for last update to x4 only
		for(i = 0; i < n; i++)
			Eg[i] = ftmp[i] + ct[3] * f_t[i] * h;
		for(l = 0; l < 3; l++)
		{	for(i = 0; i < n; i++)
				Eg[i] += cg[2*3 + l] * g[i*3 + l];
		}

		// Solve the equation E * g = Eg
		LuInvert(ip, jp, E, Eg);

		// advance x4 and accumulate error bound
		for(i = 0; i < n; i++)
		{	x4[i] += h * d4[3] * Eg[i];

			// cant use abs because cppad.hpp may not be included
			Scalar diff = x4[i] - x3[i];
			if( diff < zero )
				e[i] -= diff;
			else	e[i] += diff;
		}

		// advance xf for this step using x4
		xf = x4;
	}
	return xf;
}
Пример #16
0
static void magma_dtile_bulge_applyQ(magma_int_t core_id, char side, magma_int_t n_loc, magma_int_t n, magma_int_t nb, magma_int_t Vblksiz,
                                     double *E, magma_int_t lde, double *V, magma_int_t ldv,
                                     double *TAU, double *T, magma_int_t ldt)//, magma_int_t* info)
{
    //%===========================
    //%   local variables
    //%===========================
    magma_int_t firstcolj;
    magma_int_t bg, rownbm;
    magma_int_t st,ed,fst,vlen,vnb,colj;
    magma_int_t vpos,tpos;
    magma_int_t cur_blksiz,avai_blksiz, ncolinvolvd;
    magma_int_t nbgr, colst, coled;

    if(n<=0)
        return ;
    if(n_loc<=0)
        return ;

    //info = 0;
    magma_int_t INFO=0;

    magma_int_t nbGblk  = magma_ceildiv(n-1, Vblksiz);

    /*
     * version v1: for each chunck it apply all the V's then move to
     *                    the other chunck. the locality here inside each
     *                    chunck meaning that thread t apply V_k then move
     *                    to V_k+1 which overlap with V_k meaning that the
     *                    E_k+1 overlap with E_k. so here is the
     *                    locality however thread t had to read V_k+1 and
     *                    T_k+1 at each apply. note that all thread if they
     *                    run at same speed they might reading the same V_k
     *                    and T_k at the same time.
     * */

    magma_int_t nb_loc = 128; //$$$$$$$$

    magma_int_t     lwork = 2*nb_loc*max(Vblksiz,64);
    double *work, *work2;

    magma_dmalloc_cpu(&work, lwork);
    magma_dmalloc_cpu(&work2, lwork);

    magma_int_t nbchunk =  magma_ceildiv(n_loc, nb_loc);

    /* SIDE LEFT  meaning apply E = Q*E = (q_1*q_2*.....*q_n) * E ==> so traverse Vs in reverse order (forward) from q_n to q_1
     *            each q_i consist of applying V to a block of row E(row_i,:) and applies are overlapped meaning
     *            that q_i+1 overlap a portion of the E(row_i, :).
     *            IN parallel E is splitten in vertical block over the threads  */
    /* SIDE RIGHT meaning apply E = E*Q = E * (q_1*q_2*.....*q_n) ==> so tarverse Vs in normal  order (forward) from q_1 to q_n
     *            each q_i consist of applying V to a block of col E(:, col_i,:) and the applies are overlapped meaning
     *            that q_i+1 overlap a portion of the E(:, col_i).
     *            IN parallel E is splitten in horizontal block over the threads  */
    #ifdef ENABLE_DEBUG
    if((core_id==0)||(core_id==1))
        printf("  APPLY Q2_cpu dbulge_back_m   N %d  N_loc %d  nbchunk %d  NB %d  Vblksiz %d  SIDE %c \n", n, n_loc, nbchunk, nb, Vblksiz, side);
    #endif
   
    for (magma_int_t i = 0; i<nbchunk; i++)
    {
        magma_int_t ib_loc = min(nb_loc, (n_loc - i*nb_loc));

        if(side=='L'){
            for (bg = nbGblk; bg>0; bg--)
            {
                firstcolj = (bg-1)*Vblksiz + 1;
                rownbm    = magma_ceildiv((n-(firstcolj+1)),nb);
                if(bg==nbGblk) rownbm    = magma_ceildiv((n-(firstcolj)),nb);  // last blk has size=1 used for real to handle A(N,N-1)
                for (magma_int_t j = rownbm; j>0; j--)
                {
                    vlen = 0;
                    vnb  = 0;
                    colj      = (bg-1)*Vblksiz; // for k=0;I compute the fst and then can remove it from the loop
                    fst       = (rownbm -j)*nb+colj +1;
                    for (magma_int_t k=0; k<Vblksiz; k++)
                    {
                        colj     = (bg-1)*Vblksiz + k;
                        st       = (rownbm -j)*nb+colj +1;
                        ed       = min(st+nb-1,n-1);
                        if(st>ed)
                            break;
                        if((st==ed)&&(colj!=n-2))
                            break;
                        vlen=ed-fst+1;
                        vnb=k+1;
                    }
                    colst     = (bg-1)*Vblksiz;
                    magma_bulge_findVTpos(n, nb, Vblksiz, colst, fst, ldv, ldt, &vpos, &tpos);

                    if((vlen>0)&&(vnb>0)){
                        lapackf77_dlarfb( "L", "N", "F", "C", &vlen, &ib_loc, &vnb, V(vpos), &ldv, T(tpos), &ldt, E(fst,i*nb_loc), &lde, work, &ib_loc);
                    }
                    if(INFO!=0)
                        printf("ERROR DORMQR INFO %d \n", (int) INFO);
                }
            }
        }else if (side=='R'){
            rownbm    = magma_ceildiv((n-1),nb);
            for (magma_int_t k = 1; k<=rownbm; k++)
            {
                ncolinvolvd = min(n-1, k*nb);
                avai_blksiz=min(Vblksiz,ncolinvolvd);
                nbgr = magma_ceildiv(ncolinvolvd,avai_blksiz);
                for (magma_int_t j = 1; j<=nbgr; j++)
                {
                    vlen = 0;
                    vnb  = 0;
                    cur_blksiz = min(ncolinvolvd-(j-1)*avai_blksiz, avai_blksiz);
                    colst = (j-1)*avai_blksiz;
                    coled = colst + cur_blksiz -1;
                    fst   = (rownbm -k)*nb+colst +1;
                    for (colj=colst; colj<=coled; colj++)
                    {
                        st       = (rownbm -k)*nb+colj +1;
                        ed       = min(st+nb-1,n-1);
                        if(st>ed)
                            break;
                        if((st==ed)&&(colj!=n-2))
                            break;
                        vlen=ed-fst+1;
                        vnb=vnb+1;
                    }
                    magma_bulge_findVTpos(n, nb, Vblksiz, colst, fst, ldv, ldt, &vpos, &tpos);
                    if((vlen>0)&&(vnb>0)){
                        lapackf77_dlarfb( "R", "N", "F", "C", &ib_loc, &vlen, &vnb, V(vpos), &ldv, T(tpos), &ldt, E(i*nb_loc,fst), &lde, work, &ib_loc);
                    }
                }
            }
        }else{
            printf("ERROR SIDE %d \n",side);
        }
    } // END loop over the chunks

    magma_free_cpu(work);
    magma_free_cpu(work2);

}
Пример #17
0
void POP06::runProblem()
{
    // Problem 6 (Nataraj)
    // 5 2-D B-splines
    int dim = 4+2;

    // x1,x2,x3,x4,l1,l2
    std::vector<double> costs = {0, 0, 0, 0, 1, 0};
    std::vector<double> lb = {1,0.625,47.5,90,-INF,-INF};
    std::vector<double> ub = {1.1375,1,52.5,112,INF,INF};
    std::vector<double> z0(dim,0);

    // x1,x2,x3,x4,l1,l2,l3,l4,l5
//    std::vector<double> lb = {1,0.625,47.5,90,-INF,-INF,-INF,-INF,-INF};
//    std::vector<double> ub = {1.1375,1,52.5,112,INF,INF,INF,INF,INF};

    std::vector<VariablePtr> vars;
    for (int i = 0; i < dim; i++)
    {
        auto var = std::make_shared<Variable>(costs.at(i), lb.at(i), ub.at(i));
        vars.push_back(var);
    }

    ConstraintSetPtr cs = std::make_shared<ConstraintSet>();

    { // obj = l1

        std::vector<VariablePtr> cvars = {
            vars.at(0),
            vars.at(1),
            vars.at(2),
            vars.at(3),
            vars.at(4)
        };

        std::vector<double> thislb = {
            cvars.at(0)->getLowerBound(),
            cvars.at(1)->getLowerBound(),
            cvars.at(2)->getLowerBound(),
            cvars.at(3)->getLowerBound()
        };

        std::vector<double> thisub = {
            cvars.at(0)->getUpperBound(),
            cvars.at(1)->getUpperBound(),
            cvars.at(2)->getUpperBound(),
            cvars.at(3)->getUpperBound()
        };

        std::vector<unsigned int> deg = {2,1,2,1};

        // Poly coeffs
        DenseVector c(4);
        c.setZero();
        c(0) = 0.6224;
        c(1) = 1.7781;
        c(2) = 3.1661;
        c(3) = 19.84;

        // Poly exponents
        DenseMatrix E(4,4);
        E.setZero();
        E(0,2) = 1; E(0,3) = 1;
        E(1,1) = 1; E(1,2) = 2;
        E(2,0) = 2; E(2,3) = 1;
        E(3,0) = 2; E(3,2) = 1;

        DenseMatrix coeffs = getBSplineBasisCoefficients(c, E, thislb, thisub);

        std::vector< std::vector<double> > knots = getRegularKnotVectors(deg, thislb, thisub);

        BSpline bs(coeffs, knots, deg);

        ConstraintPtr cbs = std::make_shared<ConstraintBSpline>(cvars, bs, true);

        cs->add(cbs);

        //DenseMatrix cpoints = bs.getControlPoints();
        //cout << cpoints << endl;
    }

    { // noncon = l2

        std::vector<VariablePtr> cvars = {
            vars.at(2),
            vars.at(3),
            vars.at(5)
        };

        std::vector<double> thislb = {
            cvars.at(0)->getLowerBound(),
            cvars.at(1)->getLowerBound()
        };

        std::vector<double> thisub = {
            cvars.at(0)->getUpperBound(),
            cvars.at(1)->getUpperBound()
        };

        std::vector<unsigned int> deg = {3,1};

        // Poly coeffs
        DenseVector c(2);
        c.setZero();
        c(0) = -1;
        c(1) = -(4.0/3.0);

        // Poly exponents
        DenseMatrix E(2,2);
        E.setZero();
        E(0,0) = 2; E(0,1) = 1;
        E(1,0) = 3;

        DenseMatrix coeffs = getBSplineBasisCoefficients(c, E, thislb, thisub);

        std::vector< std::vector<double> > knots = getRegularKnotVectors(deg, thislb, thisub);

        BSpline bs(coeffs, knots, deg);

        ConstraintPtr cbs = std::make_shared<ConstraintBSpline>(cvars, bs, true);

        cs->add(cbs);
    }

    { // Linear constraints of auxiliary variables
        DenseMatrix A(4,6);
        A.setZero();
        A(0,0) = -1; A(0,2) = 0.0193;
        A(1,1) = -1; A(1,2) = 0.00954;
        A(2,5) = 1;
        A(3,3) = 1;

        DenseVector b;
        b.setZero(4);
        b(2) = -750.1728/3.14159265359;
        b(3) = 240;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    BB::BranchAndBound bnb(cs);
    Timer timer;
    timer.start();
    SolverResult res = bnb.optimize();
    timer.stop();
    cout << "Time: " << timer.getMilliSeconds() << " (ms)" << endl;
    cout << "Time: " << timer.getMicroSeconds() << " (us)" << endl;

    //1 0.625 47.5 90 6395.50783 -345958.333

    if (res.status == SolverStatus::OPTIMAL)
        fopt_found = res.objectiveValue;
}
Пример #18
0
static LONG
PathWalk(Global_T *g, 
	 UBYTE *FullName,
	 LONG FullNameLen,
	 UBYTE *LinkPath,	/* Buf to get result into, IN/OUTPUT name of LINK */
	 ULONG BufLen,		/* length of buf above */
	 LONG *Res2)		/* OUTPUT */
{
    UBYTE *PComp; /* points to current path component */
    UBYTE *WorkPath = NULL;
    DCEntry *ParDir, *ActDir;
    NEntry *ActNEnt;
    ACEntry *ACE;
    LONG LastElement = 0; /* flag: if set, last element of directory is found */
    /* (init important !) */
    LONG Pos = 0; /* fn_ScanPath needs this as buffer */
    /* (init important !) */
    LONG Res = 1;

    D(DBF_ALWAYS, "\tPathWalk(\"%s\")", FullName);

    WorkPath = StrNDup(FullName, FullNameLen); /* we will modify WorkPath */
    if(!WorkPath)
    {
	*Res2 = ERROR_NO_FREE_STORE;
	Res = 0;
	
    }
    else
    {
	/* get (cached) root handle */
	ParDir = GetDirEntry(g, 
			     NULL, /* no name entry */
			     g->g_MntAttr.fileid,
			     &g->g_MntFh,
			     NULL, /* currently not used */
			     Res2);
	if(ParDir)
	{
	    if(FullNameLen)	/* Filename != "" */
	    {
		do
		{
		    PComp = fn_ScanPath(WorkPath, FullNameLen,
					&Pos, &LastElement);
		    ASSERT(PComp);

		    D(DBF_ALWAYS,"\tPComp = \"%s\"", PComp);
		    if(*PComp == '/') /* goto parent dir, not allowed in this 
					 version, must be unified path ! */
		    {
			    E(DBF_ALWAYS, "FIXME: *** parent dir reference not allowed !!");
			    Res = 0;
			    break;
		    }
		    ActNEnt = GetNameEntry(g, ParDir, PComp, &ACE, Res2);
		    if(!ActNEnt)
		    {
			Res = 0;
			break;
		    }

		    if((ActNEnt->ne_FType != NFDIR)
		       && (ActNEnt->ne_FType != NFLNK))
		    {
			*Res2 = ERROR_INVALID_COMPONENT_NAME;
			Res = 0;
			break;
		    }
		    if(ActNEnt->ne_FType == NFLNK)
		    {
			nfspath u_lpath;
		    
			ASSERT(ACE);
			ASSERT(LinkPath);
			u_lpath = nfs_ReadLink(g->g_NFSClnt,
					       &ACE->ace_NFSFh, Res2);
			if(u_lpath)
			{
			    D(DBF_ALWAYS,"\treadlink returned: %s", u_lpath);
#if 0
			    if(UseUnixLinks(g))
				;
#endif
			    if(fn_InsertLink(LinkPath,
					     BufLen,
					     g->g_VolumeName,
					     FullName,
					     PComp-WorkPath,
					     strlen(PComp),
					     u_lpath,
					     Res2) == NULL)
			    {
				if(*Res2 == ERROR_NO_FREE_STORE)
				    Res = -1;
				else
				    Res = 0;
			    }
			    else
				Res = 2;
			}
			else
			{
			    Res = 0;
			}
			break;
		    }
		    /* note: GetDirEntry will modify ActNEnt if necessary */
		    ActDir = GetDirEntry(g, 
					 ActNEnt,
					 DCE_ID_UNUSED,
					 &ACE->ace_NFSFh,
					 PComp,
					 Res2);
		    ParDir = ActDir;
		} while(!LastElement && ParDir);
	    }
	    else
	    {			/* filename: "" */
		LinkPath[0] = 0;
		Res = 1;
	    }
	}
	else
	    Res = 0;
	fn_Delete(&WorkPath);
    }
    return Res;
}
Пример #19
0
int main(int argc, char *argv[])
{
    sqlite3 *db;
    if (sqlite3_open("db/cs.db", &db) != SQLITE_OK) {
        E("sqlite3_open() failed.");
        return -1;
    }

    int ret = sockfd_list_init(1024);
    if (ret < 0) {
        E("sockfd_list_init() failed.");
        return -1;
    }

    int servfd = socket(AF_INET, SOCK_STREAM, 0);
    if (servfd == -1) {
        E("%s", strerror(errno));
        return -1;
    }

    int optval = 1;
    ret = setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR,
            &optval, sizeof(optval));
    if (ret == -1) {
        E("%s", strerror(errno));
        return -1;
    }

#ifdef SO_REUSEPORT
    optval = 1;
    ret = setsockopt(servfd, SOL_SOCKET, SO_REUSEPORT,
            &optval, sizeof(optval));
    if (ret == -1) {
        E("%s", strerror(errno));
        return -1;
    }
#endif

    struct sockaddr_in addr;
    socklen_t addrlen = sizeof(addr);

    memset(&addr, '\0', addrlen);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;

    ret = bind(servfd, (struct sockaddr *)&addr, addrlen);
    if (ret == -1) {
        E("%s", strerror(errno));
        return -1;
    }

    int backlog = 20;
    ret = listen(servfd, backlog);
    if (ret == -1) {
        E("%s", strerror(errno));
        return -1;
    }

    FD_ZERO(&rfds_g);
    FD_ZERO(&wfds_g);
    FD_ZERO(&efds_g);

    register_readfd(servfd);

    fd_set rfds, wfds, efds;

    struct timeval timeout;

    int n = 0;
    int i = 0;

    //DIP(INADDR_ANY);
    D("cs start 0.0.0.0 %d", PORT);
    while (1) {
        rfds = rfds_g;
        wfds = wfds_g;
        efds = efds_g;

        timeout.tv_sec = 1;
        timeout.tv_usec = 0;

        n = select(maxfd + 1, &rfds, &wfds, &efds, &timeout);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            E("select() faile.");
            break;
        } else if (n == 0) {
            //D("timeout, nothing to be done.");
        } else {
            /* FIXME: while (n--) */
            for (i = 0; i <= maxfd; i++) {
                if (FD_ISSET(i, &rfds)) {
                    if (i == servfd) {
                        ret = cs_accept(i);
                        if (ret == -1) {
                            E("cs_accept() failed.");
                            break;
                        }
                    } else {
                        ret = cs_routine(i, db);
                        if (ret == -1) {
                            E("cs_routine() failed.");
                            break;
                        }
                    }
                } else if (FD_ISSET(i, &wfds)) {
                    D("write occurrence.");
                } else if (FD_ISSET(i, &efds)) {
                    E("except occurrence.");
                } else {
                    //E("undefined occurrence.");
                }
            }
        }
    }

    close(servfd);
    sqlite3_close(db);
    return 0;
}
Пример #20
0
namespace Jack
{
    //utility *********************************************************************************************************
    SERVER_EXPORT int GetHostName(char * name, int size)
    {
        if (gethostname(name, size) == SOCKET_ERROR) {
            jack_error("Can't get 'hostname' : %s", strerror(NET_ERROR_CODE));
            strcpy(name, "default");
            return -1;
        }
        return 0;
    }

    win_net_error_t NetErrorList[] =
    {
        E(0,                  "No error"),
        E(WSAEINTR,           "Interrupted system call"),
        E(WSAEBADF,           "Bad file number"),
        E(WSAEACCES,          "Permission denied"),
        E(WSAEFAULT,          "Bad address"),
        E(WSAEINVAL,          "Invalid argument"),
        E(WSAEMFILE,          "Too many open sockets"),
        E(WSAEWOULDBLOCK,     "Operation would block"),
        E(WSAEINPROGRESS,     "Operation now in progress"),
        E(WSAEALREADY,        "Operation already in progress"),
        E(WSAENOTSOCK,        "Socket operation on non-socket"),
        E(WSAEDESTADDRREQ,    "Destination address required"),
        E(WSAEMSGSIZE,        "Message too long"),
        E(WSAEPROTOTYPE,      "Protocol wrong type for socket"),
        E(WSAENOPROTOOPT,     "Bad protocol option"),
        E(WSAEPROTONOSUPPORT, "Protocol not supported"),
        E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
        E(WSAEOPNOTSUPP,      "Operation not supported on socket"),
        E(WSAEPFNOSUPPORT,    "Protocol family not supported"),
        E(WSAEAFNOSUPPORT,    "Address family not supported"),
        E(WSAEADDRINUSE,      "Address already in use"),
        E(WSAEADDRNOTAVAIL,   "Can't assign requested address"),
        E(WSAENETDOWN,        "Network is down"),
        E(WSAENETUNREACH,     "Network is unreachable"),
        E(WSAENETRESET,       "Net connection reset"),
        E(WSAECONNABORTED,    "Software caused connection abort"),
        E(WSAECONNRESET,      "Connection reset by peer"),
        E(WSAENOBUFS,         "No buffer space available"),
        E(WSAEISCONN,         "Socket is already connected"),
        E(WSAENOTCONN,        "Socket is not connected"),
        E(WSAESHUTDOWN,       "Can't send after socket shutdown"),
        E(WSAETOOMANYREFS,    "Too many references, can't splice"),
        E(WSAETIMEDOUT,       "Connection timed out"),
        E(WSAECONNREFUSED,    "Connection refused"),
        E(WSAELOOP,           "Too many levels of symbolic links"),
        E(WSAENAMETOOLONG,    "File name too long"),
        E(WSAEHOSTDOWN,       "Host is down"),
        E(WSAEHOSTUNREACH,    "No route to host"),
        E(WSAENOTEMPTY,       "Directory not empty"),
        E(WSAEPROCLIM,        "Too many processes"),
        E(WSAEUSERS,          "Too many users"),
        E(WSAEDQUOT,          "Disc quota exceeded"),
        E(WSAESTALE,          "Stale NFS file handle"),
        E(WSAEREMOTE,         "Too many levels of remote in path"),
        E(WSASYSNOTREADY,     "Network system is unavailable"),
        E(WSAVERNOTSUPPORTED, "Winsock version out of range"),
        E(WSANOTINITIALISED,  "WSAStartup not yet called"),
        E(WSAEDISCON,         "Graceful shutdown in progress"),
        E(WSAHOST_NOT_FOUND,  "Host not found"),
        E(WSANO_DATA,         "No host data of that type was found"),
        { -1, NULL },
    };

    SERVER_EXPORT const char* PrintError(int error)
    {
        int i;
        for (i = 0; NetErrorList[i].code >= 0; ++i) {
            if (error == NetErrorList[i].code)
                return NetErrorList[i].msg;
        }
        return strerror(error);
    }

    //construct/destruct***********************************************************************************************
    JackNetWinSocket::JackNetWinSocket()
    {
        fSockfd = 0;
        fSendAddr.sin_family = AF_INET;
        fSendAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&fSendAddr.sin_zero, 0, 8);
        fRecvAddr.sin_family = AF_INET;
        fRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&fRecvAddr.sin_zero, 0, 8);
    }

    JackNetWinSocket::JackNetWinSocket(const char* ip, int port)
    {
        fSockfd = 0;
        fPort = port;
        fSendAddr.sin_family = AF_INET;
        fSendAddr.sin_port = htons(port);
        fSendAddr.sin_addr.s_addr = inet_addr(ip);
        memset(&fSendAddr.sin_zero, 0, 8);
        fRecvAddr.sin_family = AF_INET;
        fRecvAddr.sin_port = htons(port);
        fRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&fRecvAddr.sin_zero, 0, 8);
    }

    JackNetWinSocket::JackNetWinSocket(const JackNetWinSocket& socket)
    {
        fSockfd = 0;
        fPort = socket.fPort;
        fSendAddr = socket.fSendAddr;
        fRecvAddr = socket.fRecvAddr;
    }

    JackNetWinSocket::~JackNetWinSocket()
    {
        Close();
    }

    JackNetWinSocket& JackNetWinSocket::operator=(const JackNetWinSocket& socket)
    {
        if (this != &socket) {
            fSockfd = 0;
            fPort = socket.fPort;
            fSendAddr = socket.fSendAddr;
            fRecvAddr = socket.fRecvAddr;
        }
        return *this;
    }

    //socket***********************************************************************************************************
    int JackNetWinSocket::NewSocket()
    {
        if (fSockfd) {
            Close();
            Reset();
        }
        fSockfd = socket(AF_INET, SOCK_DGRAM, 0);
        return fSockfd;
    }

    bool JackNetWinSocket::IsLocal(char* ip)
    {
        if (strcmp(ip, "127.0.0.1") == 0) {
            return true;
        }

        char host_name[32];
        gethostname(host_name, sizeof(host_name));

        struct hostent* host = gethostbyname(host_name);
        if (host) {
            for (int i = 0; host->h_addr_list[i] != 0; ++i) {
                struct in_addr addr;
                memcpy(&addr, host->h_addr_list[i], sizeof(struct in_addr));
                if (strcmp(inet_ntoa(addr), ip) == 0) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    int JackNetWinSocket::Bind()
    {
        return bind(fSockfd, reinterpret_cast<SOCKADDR*>(&fRecvAddr), sizeof(SOCKADDR));
    }

    int JackNetWinSocket::BindWith(const char* ip)
    {
        fRecvAddr.sin_addr.s_addr = inet_addr(ip);
        return Bind();
    }

    int JackNetWinSocket::BindWith(int port)
    {
        fRecvAddr.sin_port = htons(port);
        return Bind();
    }

    int JackNetWinSocket::Connect()
    {
        return connect(fSockfd, reinterpret_cast<SOCKADDR*>(&fSendAddr), sizeof(SOCKADDR));
    }

    int JackNetWinSocket::ConnectTo(const char* ip)
    {
        fSendAddr.sin_addr.s_addr = inet_addr(ip);
        return Connect();
    }

    void JackNetWinSocket::Close()
    {
        if (fSockfd)
            closesocket(fSockfd);
        fSockfd = 0;
    }

    void JackNetWinSocket::Reset()
    {
        fSendAddr.sin_family = AF_INET;
        fSendAddr.sin_port = htons(fPort);
        fSendAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&fSendAddr.sin_zero, 0, 8);
        fRecvAddr.sin_family = AF_INET;
        fRecvAddr.sin_port = htons(fPort);
        fRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&fRecvAddr.sin_zero, 0, 8);
    }

    bool JackNetWinSocket::IsSocket()
    {
        return(fSockfd) ? true : false;
    }

    //IP/PORT***********************************************************************************************************
    void JackNetWinSocket::SetPort(int port)
    {
        fPort = port;
        fSendAddr.sin_port = htons(port);
        fRecvAddr.sin_port = htons(port);
    }

    int JackNetWinSocket::GetPort()
    {
        return fPort;
    }

    //address***********************************************************************************************************
    int JackNetWinSocket::SetAddress(const char* ip, int port)
    {
        fSendAddr.sin_addr.s_addr = inet_addr(ip);
        fSendAddr.sin_port = htons(port);
        return 0;
    }

    char* JackNetWinSocket::GetSendIP()
    {
        return inet_ntoa(fSendAddr.sin_addr);
    }

    char* JackNetWinSocket::GetRecvIP()
    {
        return inet_ntoa(fRecvAddr.sin_addr);
    }

    //utility************************************************************************************************************
    int JackNetWinSocket::GetName(char* name)
    {
        return gethostname(name, 255);
    }

    int JackNetWinSocket::JoinMCastGroup(const char* ip)
    {
        struct ip_mreq multicast_req;
        multicast_req.imr_multiaddr.s_addr = inet_addr(ip);
        multicast_req.imr_interface.s_addr = htonl(INADDR_ANY);
        //12 is IP_ADD_MEMBERSHIP in winsock2 (differs from winsock1...)
        return SetOption(IPPROTO_IP, 12, &multicast_req, sizeof(multicast_req));
    }

    //options************************************************************************************************************
    int JackNetWinSocket::SetOption(int level, int optname, const void* optval, SOCKLEN optlen)
    {
        return setsockopt(fSockfd, level, optname, static_cast<const char*>(optval), optlen);
    }

    int JackNetWinSocket::GetOption(int level, int optname, void* optval, SOCKLEN* optlen)
    {
        return getsockopt(fSockfd, level, optname, static_cast<char*>(optval), optlen);
    }

    //tiemout************************************************************************************************************
    int JackNetWinSocket::SetTimeOut(int usec)
    {
        jack_log("JackNetWinSocket::SetTimeout %d usec", usec);
        int millisec = usec / 1000;
        return SetOption(SOL_SOCKET, SO_RCVTIMEO, &millisec, sizeof(millisec));
    }

    //local loop*********************************************************************************************************
    int JackNetWinSocket::SetLocalLoop()
    {
        //char disable = 0;
        /*
        see http://msdn.microsoft.com/en-us/library/aa916098.aspx
        Default value is TRUE. When TRUE, data that is sent from the local interface to the multicast group to
        which the socket is joined, including data sent from the same socket, will be echoed to its receive buffer.
        */
        char disable = 1;
        return SetOption(IPPROTO_IP, IP_MULTICAST_LOOP, &disable, sizeof(disable));
    }

    //network operations*************************************************************************************************
    int JackNetWinSocket::SendTo(const void* buffer, size_t nbytes, int flags)
    {
        return sendto(fSockfd, reinterpret_cast<const char*>(buffer), nbytes, flags, reinterpret_cast<SOCKADDR*>(&fSendAddr), sizeof(SOCKADDR));
    }

    int JackNetWinSocket::SendTo(const void* buffer, size_t nbytes, int flags, const char* ip)
    {
        fSendAddr.sin_addr.s_addr = inet_addr(ip);
        fSendAddr.sin_port = htons(fPort);
        return SendTo(buffer, nbytes, flags);
    }

    int JackNetWinSocket::Send(const void* buffer, size_t nbytes, int flags)
    {
        return send(fSockfd, reinterpret_cast<const char*>(buffer), nbytes, flags);
    }

    int JackNetWinSocket::RecvFrom(void* buffer, size_t nbytes, int flags)
    {
        SOCKLEN addr_len = sizeof(SOCKADDR);
        return recvfrom(fSockfd, reinterpret_cast<char*>(buffer), nbytes, flags, reinterpret_cast<SOCKADDR*>(&fRecvAddr), &addr_len);
    }

    int JackNetWinSocket::Recv(void* buffer, size_t nbytes, int flags)
    {
        return recv(fSockfd, reinterpret_cast<char*>(buffer), nbytes, flags);
    }

    int JackNetWinSocket::CatchHost(void* buffer, size_t nbytes, int flags)
    {
        SOCKLEN addr_len = sizeof(SOCKADDR);
        return recvfrom(fSockfd, reinterpret_cast<char*>(buffer), nbytes, flags, reinterpret_cast<SOCKADDR*>(&fSendAddr), &addr_len);
    }

    net_error_t JackNetWinSocket::GetError()
    {
        switch (NET_ERROR_CODE)
        {
            case WSABASEERR:
                return NET_NO_ERROR;
            case WSAETIMEDOUT:
                return NET_NO_DATA;
            case WSAEWOULDBLOCK:
                return NET_NO_DATA;
            case WSAECONNREFUSED:
                return NET_CONN_ERROR;
            case WSAECONNRESET:
                return NET_CONN_ERROR;
            case WSAEACCES:
                return NET_CONN_ERROR;
            case WSAECONNABORTED:
                return NET_CONN_ERROR;
            case WSAEHOSTDOWN:
                return NET_CONN_ERROR;
            case WSAEHOSTUNREACH:
                return NET_CONN_ERROR;
            default:
                return NET_OP_ERROR;
        }
    }
}
Пример #21
0
void testprob()
{
   int      count, graph, i, iter, j, min_n_stations, n_stations, *stations, sum, t_sum, upper_bound;
   int      n_explored, n_generated, n_states;
   double   best_first_cpu, bfs_bbr_cpu, best_hoffman_cpu, hoffman_cpu, total_cpu;
   clock_t  start_time;

	sum = 0;
	printf("%s\n",prob_file);
	read_problem(prob_file);

	close_pred();

	if (run_forward == -1)
	{
	  std::vector<int> E(n_tasks + 1);
	  std::vector<int> L(n_tasks + 1);

	  // Determine whether to run in forward or reverse
	  for (int j = 1; j <= n_tasks; ++j)
	  {
		  double ftime = t[j];
		  double rtime = t[j];
		  for (int i = 1; i <= n_tasks; ++i)
		  {
			  if (closed_predecessor_matrix[i][j]) ftime += t[i];       // If task i precedes task j
			  if (closed_predecessor_matrix[j][i]) rtime += t[i];       // If task j precedes task i
		  }

		  E[j] = ceil(ftime/cycle);
		  L[j] = ceil(rtime/cycle);
	  }

	  unsigned int f = 1;			//changed by AS 2013/06/10
	  unsigned int r = 1;			//changed by AS 2013/06/10
	  for (int m = 1; m <= 5; ++m)
	  {
		  unsigned int fcount = 0;      //changed by AS 2013/06/08
		  unsigned int rcount = 0;		//changed by AS 2013/06/08
		  for (int j = 1; j <= n_tasks; ++j)
		  {
			  if (E[j] <= m) ++fcount;
			  if (L[j] <= m) ++rcount;
		  }

		  f *= fcount;
		  r *= rcount;
	  }

	  if (r < f)
	  {
		  printf("running in reverse %d %d\n", f, r);
		  reverse_pred();
		  for (int j = 1; j <= n_tasks; ++j)
			  free(closed_predecessor_matrix[j]);
		  free(closed_predecessor_matrix);
		  close_pred();
	  }
	  else printf("running forward %d %d\n", f, r);
	}
	else if (run_forward == 0)
	{
	  printf("running in reverse\n");
	  reverse_pred();
	  for (int j = 1; j <= n_tasks; ++j)
		  free(closed_predecessor_matrix[j]);
	  free(closed_predecessor_matrix);
	  close_pred();
	}

	  find_successors();
	  //prn_successors();
	  compute_potentially_dominates();
	  //prn_pred(potentially_dominates);
	  compute_positional_weights();
	  //prn_vec(n_predecessors, n_tasks); prn_vec(n_successors, n_tasks); prn_vec(positional_weight, n_tasks);
	  compute_descending_order();

	  MALLOC(root_degrees, n_tasks+1, char);
	  t_sum = 0;
	  for(i = 1; i <= n_tasks; i++) {
		 t_sum += t[i];
		 count = 0;
		 for(j = 1; j <= n_tasks; j++) {
			if(predecessor_matrix[j][i] == 1) count++;
		 }
		 root_degrees[i] = count;
	  }

	  MALLOC(stations, n_tasks+1, int);
	  MALLOC(states, STATE_SPACE+1, state);

		 search_info.start_time = clock();
		 //cycle = 1000;

		 // Use Hoffman type heuristic to find a reasonably good upper bound.

		 start_time = clock();
		 best_hoffman_cpu = 0.0;
		 initialize_hoffman();

		 min_n_stations = BIG_INT;
		 for (alpha = 0.000; alpha <= 0.02; alpha += 0.005) 
		 {
			for (beta = 0.000; beta <= 0.02; beta += 0.005) 
			{
			   for (gimmel = 0; gimmel <= 0.03; gimmel += 0.01) 
			   {
				  n_stations = hoffman(root_degrees, 1000, 1, 5000);
				  if(n_stations < min_n_stations) 
				  {
					 min_n_stations = n_stations;
					 best_hoffman_cpu = (double) (clock() - start_time) / CLOCKS_PER_SEC;
				  }
			   }
			}
		 }
		 
		 upper_bound = min_n_stations;
		 UB = min_n_stations;
		 free_hoffman();
		 hoffman_cpu = (double) (clock() - start_time) / CLOCKS_PER_SEC;
		 printf("MHH upper bound: %d (%0.2fs)\n", UB, hoffman_cpu);

		 compute_LB2_values();
		 compute_LB3_values();
		 best_first_cpu = 0.0;
		 bfs_bbr_cpu = 0.0;
		 n_explored = 0;
		 n_generated = 0;
		 n_states = 0;

		 printf("First lower bound: %d\n", (int)ceil((double)t_sum / (double)cycle));
		 global_start_time = clock();

		 if (ceil((double) t_sum / (double) cycle) < upper_bound) 
		 {
			start_time = clock();
			initialize_best_first_bbr();

			if (bin_pack_lb == 1) 
				initialize_bin_packing();
			best_first_bbr(upper_bound);

			n_explored = search_info.n_explored;
			n_generated = search_info.n_generated;
			n_states = search_info.n_states;
			search_info.n_explored = 0;
			search_info.n_generated = 0;
			search_info.n_states = 0;
			free_heaps();
			free_best_first_bbr();
			reinitialize_states();
			if ((verified_optimality != 0) && (bin_pack_lb == 1)) 
				free_bin_packing();
			best_first_cpu = (double) (clock() - start_time) / CLOCKS_PER_SEC;

			if (verified_optimality == 0) 
			{
		   verified_optimality = 1;
			   start_time = clock();
			   initialize_bfs_bbr();
			   bfs_bbr(UB);
			   free_bfs_bbr();
			   if (bin_pack_lb == 1) 
				   free_bin_packing();
			   bfs_bbr_cpu = (double) (clock() - start_time) / CLOCKS_PER_SEC;
			}
		 }
		 else printf("Optimality proved by LB1\n");
	
		 total_cpu = (double) (clock() - search_info.start_time) / CLOCKS_PER_SEC;

	  printf("Solution with %d stations\n ",optimalsolution[0]);  //added by AS 2013/06/06
 	  for(j = 1; j <= n_tasks; j++) 
	  {
		printf("%d\t%d\n", j,optimalsolution[j]);
	  }
	  write_solution(prob_file);		//added by AS 2013/06/06

	  free(stations);

	  for(j = 1; j <= n_tasks; j++) 
	  {
		 free(predecessor_matrix[j]);
		 free(closed_predecessor_matrix[j]);
		 free(potentially_dominates[j]);
		 free(successors[j]);
		 free(predecessors[j]);
	  }

	  free(predecessor_matrix);
	  free(closed_predecessor_matrix);
	  free(potentially_dominates);
	  free(predecessors);
	  free(successors);
	  free(t);
	  free(n_successors);
	  free(n_predecessors);
	  free(positional_weight);
	  free(hash_values);
	  free(LB2_values);
	  free(LB3_values);
	  free(sorted_task_times);
	  free(descending_order);
	  free(states);

   free(root_degrees);
}
Пример #22
0
/* Subroutine */ int dptsv_(integer *n, integer *nrhs, doublereal *d, 
	doublereal *e, doublereal *b, integer *ldb, integer *info)
{
/*  -- LAPACK routine (version 2.0) --   
       Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,   
       Courant Institute, Argonne National Lab, and Rice University   
       March 31, 1993   


    Purpose   
    =======   

    DPTSV computes the solution to a real system of linear equations   
    A*X = B, where A is an N-by-N symmetric positive definite tridiagonal 
  
    matrix, and X and B are N-by-NRHS matrices.   

    A is factored as A = L*D*L**T, and the factored form of A is then   
    used to solve the system of equations.   

    Arguments   
    =========   

    N       (input) INTEGER   
            The order of the matrix A.  N >= 0.   

    NRHS    (input) INTEGER   
            The number of right hand sides, i.e., the number of columns   
            of the matrix B.  NRHS >= 0.   

    D       (input/output) DOUBLE PRECISION array, dimension (N)   
            On entry, the n diagonal elements of the tridiagonal matrix   
            A.  On exit, the n diagonal elements of the diagonal matrix   
            D from the factorization A = L*D*L**T.   

    E       (input/output) DOUBLE PRECISION array, dimension (N-1)   
            On entry, the (n-1) subdiagonal elements of the tridiagonal   
            matrix A.  On exit, the (n-1) subdiagonal elements of the   
            unit bidiagonal factor L from the L*D*L**T factorization of   
            A.  (E can also be regarded as the superdiagonal of the unit 
  
            bidiagonal factor U from the U**T*D*U factorization of A.)   

    B       (input/output) DOUBLE PRECISION array, dimension (LDB,N)   
            On entry, the N-by-NRHS right hand side matrix B.   
            On exit, if INFO = 0, the N-by-NRHS solution matrix X.   

    LDB     (input) INTEGER   
            The leading dimension of the array B.  LDB >= max(1,N).   

    INFO    (output) INTEGER   
            = 0:  successful exit   
            < 0:  if INFO = -i, the i-th argument had an illegal value   
            > 0:  if INFO = i, the leading minor of order i is not   
                  positive definite, and the solution has not been   
                  computed.  The factorization has not been completed   
                  unless i = N.   

    ===================================================================== 
  


       Test the input parameters.   

    
   Parameter adjustments   
       Function Body */
    /* System generated locals */
    integer b_dim1, b_offset, i__1;
    /* Local variables */
    extern /* Subroutine */ int xerbla_(char *, integer *), dpttrf_(
	    integer *, doublereal *, doublereal *, integer *), dpttrs_(
	    integer *, integer *, doublereal *, doublereal *, doublereal *, 
	    integer *, integer *);


#define D(I) d[(I)-1]
#define E(I) e[(I)-1]

#define B(I,J) b[(I)-1 + ((J)-1)* ( *ldb)]

    *info = 0;
    if (*n < 0) {
	*info = -1;
    } else if (*nrhs < 0) {
	*info = -2;
    } else if (*ldb < max(1,*n)) {
	*info = -6;
    }
    if (*info != 0) {
	i__1 = -(*info);
	xerbla_("DPTSV ", &i__1);
	return 0;
    }

/*     Compute the L*D*L' (or U'*D*U) factorization of A. */

    dpttrf_(n, &D(1), &E(1), info);
    if (*info == 0) {

/*        Solve the system A*X = B, overwriting B with X. */

	dpttrs_(n, nrhs, &D(1), &E(1), &B(1,1), ldb, info);
    }
    return 0;

/*     End of DPTSV */

} /* dptsv_ */
Пример #23
0
void VideoDisplay::Render() try {
	if (!con->videoController->IsLoaded() || !InitContext() || (!videoOut && !pending_frame))
		return;

	if (!videoOut)
		videoOut = agi::util::make_unique<VideoOutGL>();

	if (!tool)
		cmd::call("video/tool/cross", con);

	try {
		if (pending_frame) {
			videoOut->UploadFrameData(*pending_frame);
			pending_frame.reset();
		}
	}
	catch (const VideoOutInitException& err) {
		wxLogError(
			"Failed to initialize video display. Closing other running "
			"programs and updating your video card drivers may fix this.\n"
			"Error message reported: %s",
			err.GetMessage());
		con->videoController->SetVideo("");
		return;
	}
	catch (const VideoOutRenderException& err) {
		wxLogError(
			"Could not upload video frame to graphics card.\n"
			"Error message reported: %s",
			err.GetMessage());
		return;
	}

	if (videoSize.GetWidth() == 0) videoSize.SetWidth(1);
	if (videoSize.GetHeight() == 0) videoSize.SetHeight(1);

	if (!viewport_height || !viewport_width)
		PositionVideo();

	videoOut->Render(viewport_left, viewport_bottom, viewport_width, viewport_height);
	E(glViewport(0, std::min(viewport_bottom, 0), videoSize.GetWidth(), videoSize.GetHeight()));

	E(glMatrixMode(GL_PROJECTION));
	E(glLoadIdentity());
	E(glOrtho(0.0f, videoSize.GetWidth() / scale_factor, videoSize.GetHeight() / scale_factor, 0.0f, -1000.0f, 1000.0f));

	if (OPT_GET("Video/Overscan Mask")->GetBool()) {
		double ar = con->videoController->GetAspectRatioValue();

		// Based on BBC's guidelines: http://www.bbc.co.uk/guidelines/dq/pdf/tv/tv_standards_london.pdf
		// 16:9 or wider
		if (ar > 1.75) {
			DrawOverscanMask(.1f, .05f);
			DrawOverscanMask(0.035f, 0.035f);
		}
		// Less wide than 16:9 (use 4:3 standard)
		else {
			DrawOverscanMask(.067f, .05f);
			DrawOverscanMask(0.033f, 0.035f);
		}
	}

	if ((mouse_pos || !autohideTools->GetBool()) && tool)
		tool->Draw();

	SwapBuffers();
}
catch (const agi::Exception &err) {
	wxLogError(
		"An error occurred trying to render the video frame on the screen.\n"
		"Error message reported: %s",
		err.GetChainedMessage());
	con->videoController->SetVideo("");
}
Пример #24
0
int main(int argc, char **argv) {
	struct epoll_event events[1024];
	int pending;
	int i, n, r;

	(void) argc;

	if (argv[1] == NULL || (n_conns = atoi(argv[1])) == 0)
		n_conns = 100;

	/* x2 for both ends of streams, +2 for server and timerfd conn_rec */
	E(conns = calloc(n_conns * 2 + 2, sizeof(*conns)));
	E(client_conns = calloc(n_conns, sizeof(**client_conns)));
	E(server_conns = calloc(n_conns, sizeof(**server_conns)));

	E(epfd = epoll_create1(0));
	E(svfd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0));
	{
		int yes = 1;
		E(setsockopt(svfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes));
	}
	{
		struct sockaddr_in s;
		s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
		s.sin_family = AF_INET;
		s.sin_port = htons(PORT);
		E(bind(svfd, (struct sockaddr *) &s, sizeof s));
	}
	E(listen(svfd, 1024));
	fd_add(svfd, EPOLLIN);

	for (pending = i = 0; i < n_conns; i++) {
		struct sockaddr_in s;
		conn_rec *c;
		int fd;

		E(fd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0));
		s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
		s.sin_family = AF_INET;
		s.sin_port = htons(PORT);

		if (connect(fd, (struct sockaddr *) &s, sizeof s) == 0)
			c = fd_add(fd, EPOLLIN);
		else if (errno != EINPROGRESS)
			report_error("connect", errno);
		else {
			c = fd_add(fd, EPOLLOUT);
			pending++;
		}

		client_conns[n_client_conns++] = c;
	}

	while (pending) {
		E(n = epoll_wait(epfd, events, ARRAY_SIZE(events), -1));

		for (i = 0; i < n; i++) {
			conn_rec *c = events[i].data.ptr;

			if (c->fd == svfd) {
				struct sockaddr_in s;
				socklen_t len;
				int fd;

				len = sizeof s;
				E(fd = accept4(svfd, (struct sockaddr *) &s, &len, SOCK_NONBLOCK));
				server_conns[n_server_conns++] = fd_add(fd, EPOLLIN);
			}
			else {
				socklen_t len;
				int status;

				len = sizeof status;
				E(getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &status, &len));

				if (status)
					report_error("getsockopt(SO_ERROR)", EINVAL);

				fd_mod(c, EPOLLIN);
				pending--;
			}
		}
	}

	//assert(n_client_conns == n_server_conns);

	for (i = 0; i < n_client_conns; i++) {
		conn_rec *c = client_conns[i];
		r = write(c->fd, "PING", 4);
		//assert(r == 4);
		fd_mod(c, EPOLLIN|EPOLLOUT);
		c->events = EPOLLIN;
	}

	for (i = 0; i < n_server_conns; i++) {
		conn_rec *c = server_conns[i];
		do_write(c->fd, "PONG", 4);
		fd_mod(c, EPOLLIN|EPOLLOUT);
		c->events = EPOLLIN;
	}

	fd_add(make_timer_fd(2000), EPOLLIN);

	while (1) {
		E(n = epoll_wait(epfd, events, ARRAY_SIZE(events), -1));

		for (i = 0; i < n; i++) {
			conn_rec *c = events[i].data.ptr;

			if (c->fd == tmfd) {
				do_read(c->fd);
        do_report();
				continue;
			}

			if ((events[i].events & EPOLLIN) & (c->events & EPOLLIN)) {
				do_read(c->fd);
        c->events = EPOLLOUT;
        continue;
			}

			if ((events[i].events & EPOLLOUT) & (c->events & EPOLLOUT)) {
				do_write(c->fd, "PING", 4);
        c->events = EPOLLIN;
        continue;
			}
		}
	}

	return 0;
}
Пример #25
0
void EDSRSA(char *M_fname, char *n_fname, char *e_fname, char *d_fname)
{
	std::ifstream in(M_fname);
	int *M_hash = (int*)md5(&in), i;
    BigInt M(intToChar(M_hash[3])), N(n_fname, false), E(e_fname, false), D(d_fname, false);
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[2]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[1]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[0]));
    BigInt Signature("1"), Encode("1");
    BigInt DegreeNet[RNet];
	DegreeNet[0] = M;
	DegreeNet[0] %= N;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= N;
	}
    BigInt degreeNum[RNet];
    degreeNum[0] = BigInt("1");
	for(int i = 1; i < RNet; i++)
        degreeNum[i] = degreeNum[i-1] * BigInt("2");
    BigInt I("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(D >= I + degreeNum[j])
		{
			Signature *= DegreeNet[j];
			Signature %= N;
			I += degreeNum[j];
		}
		else
			j--;
	}
	/////////////////////////////
	DegreeNet[0] = Signature;
	DegreeNet[0] %= N;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= N;
	}
    I = BigInt("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(E >= I + degreeNum[j])
		{
			Encode *= DegreeNet[j];
			Encode %= N;
			I += degreeNum[j];
		}
		else
			j--;
	}
	/////////////////////////////
	M.TextWrite("hash.txt");
	Signature.TextWrite("signature.txt");
	Encode.TextWrite("encode.txt");
	if( M % N == Encode)
		std::cout<<"OK\n";
	else
		std::cout<<"NOT OK\n";
}
Пример #26
0
int main(int argc, char *argv[]) {
    try {
        utility::thread_number_range threads(get_default_num_threads);
        utility::parse_cli_arguments(argc, argv,
                                     utility::cli_argument_pack()
                                     //"-h" option for for displaying help is present implicitly
                                     .positional_arg(threads,"#threads","  number of threads to use; a range of the "
                                                     "form low[:high]\n              where low and optional high are "
                                                     "non-negative integers,\n              or 'auto' for the TBB "
                                                     "default")
                                     .arg(verbose,"verbose","   print diagnostic output to screen")
                                     .arg(silent,"silent","    limits output to timing info; overrides verbose")
        );

        if (silent) verbose = false;  // make silent override verbose

        tick_count start = tick_count::now();
        for(int p = threads.first; p <= threads.last; ++p ) {
            task_scheduler_init init(p);
            if (!silent)  cout << "graph test running on " << p << " threads.\n";
            
            graph g;

            { // test buffer: 0, 1
                buffer b(g);
                toggle input(g);
                led output(g, "OUTPUT", false); // false means we will explicitly call display to see LED
                
                make_edge(input.get_out(), b.get_in(0));
                make_edge(b.get_out(), output.get_in());
                
                if (!silent) printf("Testing buffer...\n");
                input.activate(); // 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input.flip(); // 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
            }

            { // test not_gate: 0, 1
                not_gate n(g);
                toggle input(g);
                led output(g, "OUTPUT", false);
                
                make_edge(input.get_out(), n.get_in(0));
                make_edge(n.get_out(), output.get_in());
                
                if (!silent) printf("Testing not_gate...\n");
                input.activate(); // 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input.flip(); // 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
            }

            { // test two-input and_gate: 00, 01, 10, 11
                and_gate<two_input> a(g);
                toggle input0(g);
                toggle input1(g);
                led output(g, "OUTPUT", false);
                
                make_edge(input0.get_out(), a.get_in(0));
                make_edge(input1.get_out(), a.get_in(1));
                make_edge(a.get_out(), output.get_in());
                
                if (!silent) printf("Testing and_gate...\n");
                input1.activate();  input0.activate();  // 0 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input0.flip();  // 0 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input1.flip(); input0.flip();  // 1 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input0.flip();  // 1 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
            }

            { // test three-input or_gate: 000, 001, 010, 100, 011, 101, 110, 111
                or_gate<three_input> o(g);
                toggle input0(g);
                toggle input1(g);
                toggle input2(g);
                led output(g, "OUTPUT", false);
                
                make_edge(input0.get_out(), o.get_in(0));
                make_edge(input1.get_out(), o.get_in(1));
                make_edge(input2.get_out(), o.get_in(2));
                make_edge(o.get_out(), output.get_in());
                
                if (!silent) printf("Testing or_gate...\n");
                input2.activate();  input1.activate();  input0.activate();  // 0 0 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input0.flip();  // 0 0 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input1.flip(); input0.flip();  // 0 1 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input2.flip();  input1.flip();  // 1 0 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input2.flip();  input1.flip();  input0.flip();  // 0 1 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input2.flip();  input1.flip();  // 1 0 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input1.flip();  input0.flip();  // 1 1 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input0.flip();  // 1 1 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
            }

            { // test two-input xor_gate: 00, 01, 10, 11
                xor_gate<two_input> x(g);
                toggle input0(g);
                toggle input1(g);
                led output(g, "OUTPUT", false);
                
                make_edge(input0.get_out(), x.get_in(0));
                make_edge(input1.get_out(), x.get_in(1));
                make_edge(x.get_out(), output.get_in());
                
                if (!silent) printf("Testing xor_gate...\n");
                input1.activate();  input0.activate();  // 0 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input0.flip();  // 0 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input1.flip();  input0.flip();  // 1 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input0.flip();  // 1 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
            }


            { // test two-input nor_gate: 00, 01, 10, 11
                nor_gate<two_input> n(g);
                toggle input0(g);
                toggle input1(g);
                led output(g, "OUTPUT", false);
                
                make_edge(input0.get_out(), n.get_in(0));
                make_edge(input1.get_out(), n.get_in(1));
                make_edge(n.get_out(), output.get_in());
                
                if (!silent) printf("Testing nor_gate...\n");
                input1.activate();  input0.activate();  // 0 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == high);
                input0.flip();  // 0 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input1.flip();  input0.flip();  // 1 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
                input0.flip();  // 1 1
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == low);
            }

            { // test steady_signal and digit
                steady_signal input0(g, high);
                steady_signal input1(g, low);
                and_gate<two_input> a(g);
                or_gate<two_input> o(g);
                xor_gate<two_input> x(g);
                nor_gate<two_input> n(g);
                digit output(g, "OUTPUT", false);
                
                make_edge(input0.get_out(), a.get_in(0));
                make_edge(input1.get_out(), a.get_in(1));
                make_edge(a.get_out(), output.get_in(0));

                make_edge(input0.get_out(), o.get_in(0));
                make_edge(input1.get_out(), o.get_in(1));
                make_edge(o.get_out(), output.get_in(1));

                make_edge(input0.get_out(), x.get_in(0));
                make_edge(input1.get_out(), x.get_in(1));
                make_edge(x.get_out(), output.get_in(2));

                make_edge(input0.get_out(), n.get_in(0));
                make_edge(input1.get_out(), n.get_in(1));
                make_edge(n.get_out(), output.get_in(3));
                
                if (!silent) printf("Testing steady_signal...\n");
                input0.activate();  // 1
                input1.activate();  // 0
                g.wait_for_all();
                if (!silent) output.display();
                assert(output.get_value() == 6);
            }

            { // test push_button
                push_button p(g);
                buffer b(g);
                led output(g, "OUTPUT", !silent); // true means print all LED state changes

                make_edge(p.get_out(), b.get_in(0));
                make_edge(b.get_out(), output.get_in());

                if (!silent) printf("Testing push_button...\n");
                p.press();
                p.release();
                p.press();
                p.release();
                g.wait_for_all();
            }

            { // test one_bit_adder
                one_bit_adder my_adder(g);
                toggle A(g);
                toggle B(g);
                toggle CarryIN(g);
                led Sum(g, "SUM");
                led CarryOUT(g, "CarryOUT");
                
                make_edge(A.get_out(), my_adder.get_A());
                make_edge(B.get_out(), my_adder.get_B());
                make_edge(CarryIN.get_out(), my_adder.get_CI());
                make_edge(my_adder.get_out(), Sum.get_in());
                make_edge(my_adder.get_CO(), CarryOUT.get_in());
                
                A.activate();
                B.activate();
                CarryIN.activate();
                
                if (!silent) printf("A on\n");
                A.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == high) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("A off\n");
                A.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("B on\n");
                B.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == high) && (CarryOUT.get_value() == low));
                if (!silent) printf("B off\n");
                B.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("CarryIN on\n");
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == high) && (CarryOUT.get_value() == low));
                if (!silent) printf("CarryIN off\n");
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("A&B on\n");
                A.flip();
                B.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == high));
                if (!silent) printf("A&B off\n");
                A.flip();
                B.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("A&CarryIN on\n");
                A.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == high));
                if (!silent) printf("A&CarryIN off\n");
                A.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("B&CarryIN on\n");
                B.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == high));
                if (!silent) printf("B&CarryIN off\n");
                B.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("A&B&CarryIN on\n");
                A.flip();
                B.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == high) && (CarryOUT.get_value() == high));
                if (!silent) printf("A&B&CarryIN off\n");
                A.flip();
                B.flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == low) && (CarryOUT.get_value() == low));
            }

            { // test four_bit_adder
                four_bit_adder four_adder(g);
                std::vector<toggle> A(4, toggle(g));
                std::vector<toggle> B(4, toggle(g));
                toggle CarryIN(g);
                digit Sum(g, "SUM");
                led CarryOUT(g, "CarryOUT");
                
                for (int i=0; i<4; ++i) {
                    make_edge(A[i].get_out(), four_adder.get_A(i));
                    make_edge(B[i].get_out(), four_adder.get_B(i));
                    make_edge(four_adder.get_out(i), Sum.get_in(i));
                }
                make_edge(CarryIN.get_out(), four_adder.get_CI());
                make_edge(four_adder.get_CO(), CarryOUT.get_in());
                
                // Activate all switches at low state
                for (int i=0; i<4; ++i) {
                    A[i].activate();
                    B[i].activate();
                }
                CarryIN.activate();
                
                if (!silent) printf("1+0\n");
                A[0].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 1) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("0+1\n");
                A[0].flip();
                B[0].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 1) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("3+4\n");
                A[0].flip();
                A[1].flip();
                B[0].flip();
                B[2].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 7) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("6+1\n");
                A[0].flip();
                A[2].flip();
                B[0].flip();
                B[2].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 7) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("0+0+carry\n");
                A[1].flip();
                A[2].flip();
                B[0].flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 1) && (CarryOUT.get_value() == low));
                
                if (!silent) printf("15+15+carry\n");
                A[0].flip();
                A[1].flip();
                A[2].flip();
                A[3].flip();
                B[0].flip();
                B[1].flip();
                B[2].flip();
                B[3].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 0xf) && (CarryOUT.get_value() == high));
                
                if (!silent) printf("8+8\n");
                A[0].flip();
                A[1].flip();
                A[2].flip();
                B[0].flip();
                B[1].flip();
                B[2].flip();
                CarryIN.flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 0) && (CarryOUT.get_value() == high));
                
                if (!silent) printf("0+0\n");
                A[3].flip();
                B[3].flip();
                g.wait_for_all();
                if (!silent) Sum.display();
                if (!silent) CarryOUT.display();
                assert((Sum.get_value() == 0) && (CarryOUT.get_value() == low));
            }

            { // test D_latch
                D_latch my_d_latch(g);
                toggle D(g);
                pulse E(g, 500, 4); // clock changes every 500ms; stops after 4 changes
                led Q(g, " Q", verbose); // if true, LEDs print at every state change
                led notQ(g, "~Q", verbose);
                
                make_edge(D.get_out(), my_d_latch.get_D());
                make_edge(E.get_out(), my_d_latch.get_E());
                make_edge(my_d_latch.get_Q(), Q.get_in());
                make_edge(my_d_latch.get_notQ(), notQ.get_in());
                
                D.activate();
                
                if (!silent) printf("Toggling D\n");
                E.activate();
                D.flip();
                g.wait_for_all();
                if (!silent && !verbose) { Q.display(); notQ.display(); }
                assert((Q.get_value() == high) && (notQ.get_value() == low));
                E.reset();
                
                if (!silent) printf("Toggling D\n");
                E.activate();
                D.flip();
                g.wait_for_all();
                if (!silent && !verbose) { Q.display(); notQ.display(); }
                assert((Q.get_value() == low) && (notQ.get_value() == high));
                E.reset();
                
                if (!silent) printf("Toggling D\n");
                E.activate();
                D.flip();
                g.wait_for_all();
                if (!silent && !verbose) { Q.display(); notQ.display(); }
                assert((Q.get_value() == high) && (notQ.get_value() == low));
                E.reset();
                
                if (!silent) printf("Toggling D\n");
                E.activate();
                D.flip();
                g.wait_for_all();
                if (!silent && !verbose) { Q.display(); notQ.display(); }
                assert((Q.get_value() == low) && (notQ.get_value() == high));
                E.reset();
                
                if (!silent) printf("Toggling D\n");
                E.activate();
                D.flip();
                g.wait_for_all();
                if (!silent && !verbose) { Q.display(); notQ.display(); }
                assert((Q.get_value() == high) && (notQ.get_value() == low));
            }
        }
        utility::report_elapsed_time((tbb::tick_count::now() - start).seconds());
        return 0;
    } catch(std::exception& e) {
        cerr<<"error occurred. error text is :\"" <<e.what()<<"\"\n";
        return 1;
    }
}
Пример #27
0
Файл: t.c Проект: vogth/chandler
int
main(int argc, char *argv[])
{
    int ret;

    E(db_env_set_func_close, close, "close");
    E(db_env_set_func_dirfree, dirfree, "dirfree");
    E(db_env_set_func_dirlist, dirlist, "dirlist");
    E(db_env_set_func_exists, exists, "exists");
    E(db_env_set_func_free, free, "free");
    E(db_env_set_func_fsync, fsync, "fsync");
    E(db_env_set_func_ftruncate, ftruncate, "ftruncate");
    E(db_env_set_func_ioinfo, ioinfo, "ioinfo");
    E(db_env_set_func_malloc, malloc, "malloc");
    E(db_env_set_func_map, map, "map");
    E(db_env_set_func_open, open, "open");
    E(db_env_set_func_pread, pread, "pread");
    E(db_env_set_func_pwrite, pwrite, "pwrite");
    E(db_env_set_func_read, read, "read");
    E(db_env_set_func_realloc, realloc, "realloc");
    E(db_env_set_func_rename, rename, "rename");
    E(db_env_set_func_seek, seek, "seek");
    E(db_env_set_func_sleep, local_sleep, "sleep");
    E(db_env_set_func_unlink, unlink, "unlink");
    E(db_env_set_func_unmap, unmap, "unmap");
    E(db_env_set_func_write, write, "write");
    E(db_env_set_func_yield, sched_yield, "yield");

    return (0);
}
Пример #28
0
namespace swift {

/// This helper function is typically used by the parser to
/// map a type name to a corresponding layout constraint if possible.
LayoutConstraint getLayoutConstraint(Identifier ID, ASTContext &Ctx) {
  if (ID == Ctx.Id_TrivialLayout)
    return LayoutConstraint::getLayoutConstraint(
        LayoutConstraintKind::TrivialOfExactSize, 0, 0, Ctx);

  if (ID == Ctx.Id_TrivialAtMostLayout)
    return LayoutConstraint::getLayoutConstraint(
        LayoutConstraintKind::TrivialOfAtMostSize, 0, 0, Ctx);

  if (ID == Ctx.Id_RefCountedObjectLayout)
    return LayoutConstraint::getLayoutConstraint(
        LayoutConstraintKind::RefCountedObject, Ctx);

  if (ID == Ctx.Id_NativeRefCountedObjectLayout)
    return LayoutConstraint::getLayoutConstraint(
        LayoutConstraintKind::NativeRefCountedObject, Ctx);

  if (ID == Ctx.Id_ClassLayout)
    return LayoutConstraint::getLayoutConstraint(
      LayoutConstraintKind::Class, Ctx);

  if (ID == Ctx.Id_NativeClassLayout)
    return LayoutConstraint::getLayoutConstraint(
      LayoutConstraintKind::NativeClass, Ctx);

  return LayoutConstraint::getLayoutConstraint(
      LayoutConstraintKind::UnknownLayout, Ctx);
}

StringRef LayoutConstraintInfo::getName() const {
  return getName(getKind());
}

StringRef LayoutConstraintInfo::getName(LayoutConstraintKind Kind) {
  switch (Kind) {
  case LayoutConstraintKind::UnknownLayout:
    return "_UnknownLayout";
  case LayoutConstraintKind::Class:
    return "AnyObject";
  case LayoutConstraintKind::NativeClass:
    return "_NativeClass";
  case LayoutConstraintKind::RefCountedObject:
    return "_RefCountedObject";
  case LayoutConstraintKind::NativeRefCountedObject:
    return "_NativeRefCountedObject";
  case LayoutConstraintKind::Trivial:
    return "_Trivial";
  case LayoutConstraintKind::TrivialOfAtMostSize:
    return "_TrivialAtMost";
  case LayoutConstraintKind::TrivialOfExactSize:
    return "_Trivial";
  }

  llvm_unreachable("Unhandled LayoutConstraintKind in switch.");
}

/// Uniquing for the LayoutConstraintInfo.
void LayoutConstraintInfo::Profile(llvm::FoldingSetNodeID &ID,
                                   LayoutConstraintKind Kind,
                                   unsigned SizeInBits,
                                   unsigned Alignment) {
  ID.AddInteger((unsigned)Kind);
  ID.AddInteger(SizeInBits);
  ID.AddInteger(Alignment);
}

bool LayoutConstraintInfo::isKnownLayout(LayoutConstraintKind Kind) {
  return Kind != LayoutConstraintKind::UnknownLayout;
}

bool LayoutConstraintInfo::isFixedSizeTrivial(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::TrivialOfExactSize;
}

bool LayoutConstraintInfo::isKnownSizeTrivial(LayoutConstraintKind Kind) {
  return Kind > LayoutConstraintKind::UnknownLayout &&
         Kind < LayoutConstraintKind::Trivial;
}

bool LayoutConstraintInfo::isAddressOnlyTrivial(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::Trivial;
}

bool LayoutConstraintInfo::isTrivial(LayoutConstraintKind Kind) {
  return Kind > LayoutConstraintKind::UnknownLayout &&
         Kind <= LayoutConstraintKind::Trivial;
}

bool LayoutConstraintInfo::isRefCountedObject(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::RefCountedObject;
}

bool LayoutConstraintInfo::isNativeRefCountedObject(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::NativeRefCountedObject;
}

bool LayoutConstraintInfo::isAnyRefCountedObject(LayoutConstraintKind Kind) {
  return isRefCountedObject(Kind) || isNativeRefCountedObject(Kind);
}

bool LayoutConstraintInfo::isClass(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::Class ||
         Kind == LayoutConstraintKind::NativeClass;
}

bool LayoutConstraintInfo::isNativeClass(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::NativeClass;
}

bool LayoutConstraintInfo::isRefCounted(LayoutConstraintKind Kind) {
  return isAnyRefCountedObject(Kind) || isClass(Kind);
}

bool LayoutConstraintInfo::isNativeRefCounted(LayoutConstraintKind Kind) {
  return Kind == LayoutConstraintKind::NativeRefCountedObject ||
         Kind == LayoutConstraintKind::NativeClass;
}

void *LayoutConstraintInfo::operator new(size_t bytes, const ASTContext &ctx,
                                         AllocationArena arena,
                                         unsigned alignment) {
  return ctx.Allocate(bytes, alignment, arena);
}

SourceRange LayoutConstraintLoc::getSourceRange() const { return getLoc(); }

#define MERGE_LOOKUP(lhs, rhs)                                                 \
  mergeTable[int(lhs)][int(rhs)]

// Shortcut for spelling the whole enumerator.
#define E(X) LayoutConstraintKind::X
#define MERGE_CONFLICT LayoutConstraintKind::UnknownLayout

/// This is a 2-D table defining the merging rules for layout constraints.
/// It is indexed by means of LayoutConstraintKind.
/// mergeTable[i][j] tells the kind of a layout constraint is the result
/// of merging layout constraints of kinds 'i' and 'j'.
///
/// Some of the properties of the merge table, where C is any type of layout
/// constraint:
///   UnknownLayout x C -> C
///   C x UnknownLayout -> C
///   C x C -> C
///   mergeTable[i][j] == mergeTable[j][i], i.e. the table is symmetric.
///   mergeTable[i][j] == UnknownLayout if merging layout constraints of kinds i
///   and j would result in a conflict.
static LayoutConstraintKind mergeTable[unsigned(E(LastLayout)) +
                                       1][unsigned(E(LastLayout)) + 1] = {
    // Initialize the row for UnknownLayout.
    {E(/* UnknownLayout */ UnknownLayout),
     E(/* TrivialOfExactSize */ TrivialOfExactSize),
     E(/* TrivialOfAtMostSize */ TrivialOfAtMostSize), E(/* Trivial */ Trivial),
     E(/* Class */ Class), E(/* NativeClass */ NativeClass),
     E(/* RefCountedObject*/ RefCountedObject),
     E(/* NativeRefCountedObject */ NativeRefCountedObject)},

    // Initialize the row for TrivialOfExactSize.
    {E(/* UnknownLayout */ TrivialOfExactSize),
     E(/* TrivialOfExactSize */ TrivialOfExactSize), MERGE_CONFLICT,
     E(/* Trivial */ TrivialOfExactSize), MERGE_CONFLICT, MERGE_CONFLICT,
     MERGE_CONFLICT, MERGE_CONFLICT},

    // Initialize the row for TrivialOfAtMostSize.
    {E(/* UnknownLayout */ TrivialOfAtMostSize), MERGE_CONFLICT,
     E(/* TrivialOfAtMostSize */ TrivialOfAtMostSize),
     E(/* Trivial */ TrivialOfAtMostSize), MERGE_CONFLICT, MERGE_CONFLICT,
     MERGE_CONFLICT, MERGE_CONFLICT},

    // Initialize the row for Trivial.
    {E(/* UnknownLayout */ Trivial),
     E(/* TrivialOfExactSize */ TrivialOfExactSize),
     E(/* TrivialOfAtMostSize */ TrivialOfAtMostSize), E(/* Trivial */ Trivial),
     MERGE_CONFLICT, MERGE_CONFLICT, MERGE_CONFLICT, MERGE_CONFLICT},

    // Initialize the row for Class.
    {E(/* UnknownLayout*/ Class), MERGE_CONFLICT, MERGE_CONFLICT,
     MERGE_CONFLICT, E(/* Class */ Class), E(/* NativeClass */ NativeClass),
     E(/* RefCountedObject */ Class),
     E(/* NativeRefCountedObject */ NativeClass)},

    // Initialize the row for NativeClass.
    {E(/* UnknownLayout */ NativeClass), MERGE_CONFLICT, MERGE_CONFLICT,
     MERGE_CONFLICT, E(/* Class */ NativeClass),
     E(/* NativeClass */ NativeClass), E(/* RefCountedObject */ NativeClass),
     E(/* NativeRefCountedObject */ NativeClass)},

    // Initialize the row for RefCountedObject.
    {E(/* UnknownLayout */ RefCountedObject), MERGE_CONFLICT, MERGE_CONFLICT,
     MERGE_CONFLICT, E(/* Class */ Class), E(/* NativeClass */ NativeClass),
     E(/* RefCountedObject */ RefCountedObject),
     E(/* NativeRefCountedObject */ NativeRefCountedObject)},

    // Initialize the row for NativeRefCountedObject.
    {E(/* UnknownLayout */ NativeRefCountedObject), MERGE_CONFLICT,
     MERGE_CONFLICT, MERGE_CONFLICT, E(/* Class */ NativeClass),
     E(/* NativeClass */ NativeClass),
     E(/* RefCountedObject */ NativeRefCountedObject),
     E(/* NativeRefCountedObject*/ NativeRefCountedObject)},
};

#undef E

// Fixed-size trivial constraint can be combined with AtMostSize trivial
// constraint into a fixed-size trivial constraint, if
// fixed_size_layout.size <= at_most_size_layout.size and
// their alignment requirements are not contradicting.
//
// Only merges if LHS would become the result of the merge.
static LayoutConstraint
mergeKnownSizeTrivialConstraints(LayoutConstraint LHS, LayoutConstraint RHS) {
  assert(LHS->isKnownSizeTrivial() && RHS->isKnownSizeTrivial());

  // LHS should be fixed-size.
  if (!LHS->isFixedSizeTrivial())
    return LayoutConstraint::getUnknownLayout();

  // RHS should be at-most-size.
  if (RHS->isFixedSizeTrivial())
    return LayoutConstraint::getUnknownLayout();

  // Check that sizes are compatible, i.e.
  // fixed_size_layout.size <= at_most_size_layout.size
  if (LHS->getMaxTrivialSizeInBits() > RHS->getMaxTrivialSizeInBits())
    return LayoutConstraint::getUnknownLayout();

  // Check alignments

  // Quick exit if at_most_size_layout does not care about the alignment.
  if (!RHS->getAlignmentInBits())
    return LHS;

  // Check if fixed_size_layout.alignment is a multiple of
  // at_most_size_layout.alignment.
  if (LHS->getAlignmentInBits() &&
      LHS->getAlignmentInBits() % RHS->getAlignmentInBits() == 0)
    return LHS;

  return LayoutConstraint::getUnknownLayout();
}

LayoutConstraint
LayoutConstraint::merge(LayoutConstraint Other) {
  auto Self = *this;

  // If both constraints are the same, they are always equal.
  if (Self == Other)
    return Self;

  // TrivialOfExactSize and TrivialOfAtMostSize are a special case,
  // because not only their kind, but their parameters need to be compared as
  // well.
  if (Self->isKnownSizeTrivial() && Other->isKnownSizeTrivial()) {
    // If we got here, it means that the Self == Other check above has failed.
    // And that could only happen if either the kinds are different or
    // size/alignment parameters are different.

    // Try to merge fixed-size constraint with an at-most-size constraint,
    // if possible.
    LayoutConstraint MergedKnownSizeTrivial;
    MergedKnownSizeTrivial = mergeKnownSizeTrivialConstraints(Self, Other);
    if (MergedKnownSizeTrivial->isKnownLayout())
      return MergedKnownSizeTrivial;

    MergedKnownSizeTrivial = mergeKnownSizeTrivialConstraints(Other, Self);
    if (MergedKnownSizeTrivial->isKnownLayout())
      return MergedKnownSizeTrivial;

    return LayoutConstraint::getUnknownLayout();
  }

  // Lookup in the mergeTable if this combination of layouts can be merged.
  auto mergeKind = MERGE_LOOKUP(Self->getKind(), Other->getKind());
  // The merge table should be symmetric.
  assert(mergeKind == MERGE_LOOKUP(Other->getKind(), Self->getKind()));

  // Merge is not possible, report a conflict.
  if (mergeKind == LayoutConstraintKind::UnknownLayout)
    return LayoutConstraint::getUnknownLayout();

  if (Self->getKind() == mergeKind)
    return Self;

  if (Other->getKind() == mergeKind)
    return Other;

  // The result of the merge is not equal to any of the input constraints, e.g.
  // Class x NativeRefCountedObject -> NativeClass.
  return LayoutConstraint::getLayoutConstraint(mergeKind);
}

LayoutConstraint
LayoutConstraint::getLayoutConstraint(LayoutConstraintKind Kind) {
  assert(!LayoutConstraintInfo::isKnownSizeTrivial(Kind));
  switch(Kind) {
  case LayoutConstraintKind::Trivial:
    return LayoutConstraint(&LayoutConstraintInfo::TrivialConstraintInfo);
  case LayoutConstraintKind::NativeClass:
    return LayoutConstraint(&LayoutConstraintInfo::NativeClassConstraintInfo);
  case LayoutConstraintKind::Class:
    return LayoutConstraint(&LayoutConstraintInfo::ClassConstraintInfo);
  case LayoutConstraintKind::NativeRefCountedObject:
    return LayoutConstraint(
        &LayoutConstraintInfo::NativeRefCountedObjectConstraintInfo);
  case LayoutConstraintKind::RefCountedObject:
    return LayoutConstraint(
        &LayoutConstraintInfo::RefCountedObjectConstraintInfo);
  case LayoutConstraintKind::UnknownLayout:
    return LayoutConstraint(&LayoutConstraintInfo::UnknownLayoutConstraintInfo);
  case LayoutConstraintKind::TrivialOfAtMostSize:
  case LayoutConstraintKind::TrivialOfExactSize:
    llvm_unreachable("Wrong layout constraint kind");
  }
}

LayoutConstraint LayoutConstraint::getUnknownLayout() {
  return LayoutConstraint(&LayoutConstraintInfo::UnknownLayoutConstraintInfo);
}

LayoutConstraintInfo LayoutConstraintInfo::UnknownLayoutConstraintInfo;

LayoutConstraintInfo LayoutConstraintInfo::RefCountedObjectConstraintInfo(
    LayoutConstraintKind::RefCountedObject);

LayoutConstraintInfo LayoutConstraintInfo::NativeRefCountedObjectConstraintInfo(
    LayoutConstraintKind::NativeRefCountedObject);

LayoutConstraintInfo LayoutConstraintInfo::ClassConstraintInfo(
    LayoutConstraintKind::Class);

LayoutConstraintInfo LayoutConstraintInfo::NativeClassConstraintInfo(
    LayoutConstraintKind::NativeClass);

LayoutConstraintInfo LayoutConstraintInfo::TrivialConstraintInfo(
    LayoutConstraintKind::Trivial);

} // end namespace swift
void CompressibleExponentialLaw<DIM>::ComputeStressAndStressDerivative(c_matrix<double,DIM,DIM>& rC,
                                                                       c_matrix<double,DIM,DIM>& rInvC,
                                                                       double                pressure /* not used */,
                                                                       c_matrix<double,DIM,DIM>& rT,
                                                                       FourthOrderTensor<DIM,DIM,DIM,DIM>& rDTdE,
                                                                       bool                  computeDTdE)
{
    static c_matrix<double,DIM,DIM> C_transformed;
    static c_matrix<double,DIM,DIM> invC_transformed;

    // The material law parameters are set up assuming the fibre direction is (1,0,0)
    // and sheet direction is (0,1,0), so we have to transform C,inv(C),and T.
    // Let P be the change-of-basis matrix P = (\mathbf{m}_f, \mathbf{m}_s, \mathbf{m}_n).
    // The transformed C for the fibre/sheet basis is C* = P^T C P.
    // We then compute T* = T*(C*), and then compute T = P T* P^T.

    this->ComputeTransformedDeformationTensor(rC, rInvC, C_transformed, invC_transformed);

    // Compute T*

    c_matrix<double,DIM,DIM> E = 0.5*(C_transformed - mIdentity);

    double QQ = 0;
    for (unsigned M=0; M<DIM; M++)
    {
        for (unsigned N=0; N<DIM; N++)
        {
            QQ += mB[M][N]*E(M,N)*E(M,N);
        }
    }
    assert(QQ < 10.0);///\todo #2193 This line is to trap for large deformations which lead to blow up in the exponential Uysk model
    double multiplier = mA*exp(QQ);
    rDTdE.Zero();

    double J = sqrt(Determinant(rC));

    for (unsigned M=0; M<DIM; M++)
    {
        for (unsigned N=0; N<DIM; N++)
        {
            rT(M,N) = multiplier*mB[M][N]*E(M,N) + mCompressibilityParam * J*log(J)*invC_transformed(M,N);

            if (computeDTdE)
            {
                for (unsigned P=0; P<DIM; P++)
                {
                    for (unsigned Q=0; Q<DIM; Q++)
                    {
                        rDTdE(M,N,P,Q) =    multiplier * mB[M][N] * (M==P)*(N==Q)
                                         +  2*multiplier*mB[M][N]*mB[P][Q]*E(M,N)*E(P,Q)
                                         +  mCompressibilityParam * (J*log(J) + J) * invC_transformed(M,N) * invC_transformed(P,Q)
                                         -  mCompressibilityParam * 2*J*log(J) * invC_transformed(M,P) * invC_transformed(Q,N);
                    }
                }
            }
        }
    }

    // Now do:   T = P T* P^T   and   dTdE_{MNPQ}  =  P_{Mm}P_{Nn}P_{Pp}P_{Qq} dT*dE*_{mnpq}
    this->TransformStressAndStressDerivative(rT, rDTdE, computeDTdE);
}
Пример #30
0
int
main (int argc, char *argv[])
{
    const int n_nodes = ('g' - 'a' + 1);

    dijkstra_graph_t *graph = dijkstra_create (n_nodes, 0);

	for (int i=0; i<n_nodes; i++) {
        char *name = calloc (4, sizeof(*name));
        sprintf (name, "%c", 'a' + i);
        dijkstra_set_user (graph, i, name);
    }

#define E(a, b, c) dijkstra_add_edge_undir (graph, (a - 'a'), (b - 'a'), c)
	E('a', 'b', 4);	 E('a', 'c', 9);  E('a', 'f', 14);
	E('b', 'c', 10); E('b', 'd', 15);
    E('c', 'd', 11); E('c', 'f', 2);
    E('d', 'e', 6);
    E('e', 'f', 9);
#undef E

    for (int i=0; i<n_nodes; i++) {

        printf ("\nsrc=%d, dest=%d\n", i, 3);
        printf ("------------------------------\n");
        dijkstra_calc_dest (graph, i, 3);
        dijkstra_print_path (graph, i, 3);

        printf ("\n\nsrc=%d, dest=all\n", i);
        printf ("------------------------------\n");
        dijkstra_calc_all (graph, i);
        for (int j=0; j<n_nodes; j++) {
            dijkstra_print_path (graph, i, j);
            printf ("\n");
        }

        #if 1
        printf ("\n");
        for (int j=0; j<n_nodes; j++) {
            int *path;
            double *dist;
            int path_len = dijkstra_get_path (graph, i, j, &path, &dist);
            if (path_len < 0) {
                const char *name = dijkstra_get_user (graph, j);
                printf ("%s(unreached)", name);
            }

            for (int k=0; k < path_len; k++) {
                const char *name = dijkstra_get_user (graph, path[k]);

                if (k==0)
                    printf ("%s(%g)", name, dist[k]);
                else
                    printf ("-> %s(%g)", name, dist[k]);
            }
            printf ("\n");
        }
        #endif
    }

    // clean up
    for (int i=0; i<dijkstra_n_nodes (graph); i++)
        free (dijkstra_get_user (graph, i));
    dijkstra_destroy (graph);
}