Example #1
0
  PRIVDEST ~timetest () {
    ok = 0;
    for (int i = 0; i < 2; i++)
      if (t[i]) {
	timecb_remove (t[i]);
	t[i] = NULL;
      }
    ctr--;
    if (!ctr)
      phase2 ();
    if (ctr < 0)
      panic ("too many callbacks\n");
  }
Example #2
0
void ds_phase_data(int trace, float *in_ptr, float *out_ptr, int fp, int np,
                   double l_phase, double r_phase)
{
  int	dtype, /* phtype,*/ patype;

  dtype = getdatatype(datahead.status);
  if (dtype == HYPERCOMPLEX)
     phase4(in_ptr + (fp*dtype), out_ptr, np, l_phase, r_phase, lp1, rp1,
            fn1/2, trace, revflag);
  else
  {
/*    phtype = get_phase_mode(HORIZ); */
     patype = get_phaseangle_mode(HORIZ);
     if (patype == 1)
        phaseangle2(in_ptr + (fp*dtype), out_ptr, np, COMPLEX, 1, 1, FALSE, l_phase, r_phase);
     else
        phase2(in_ptr + (fp*dtype), out_ptr, np, l_phase, r_phase);
  }
}
Example #3
0
//-------------------------------------------------------------------------------
void MainWindow::replyFinished(QNetworkReply *reply)//ответ от сервера фильмов
{
//окончание запроса на сервер и прием данных
    if (reply->error() != QNetworkReply::NoError)    {

         // обрабатываем ошибку
        QMessageBox *nm=new QMessageBox;
        nm->setText(reply->errorString());
        nm->exec();
        delete nm;
        reply->deleteLater();
        return;
       }
    else     {
      // если нет ошибки Читаем ответ от сервера
     QByteArray bytes = reply->readAll();
     string=(QUrl::fromPercentEncoding(bytes));

    }//переходим ко второй фазе
    emit phase2(string);
 }
Example #4
0
GameProcessor::GameProcessor(YagwScene &ygws)
  : scene(ygws),
    player(0),
    disclaimer(0),
    gia(*this, ygws.width(), ygws.height(), player),
    cfg(ConfManager("config.cfg")),
    playerFire(0)
{
    QObject::connect(&scene, SIGNAL(newEntity(Entity*)), this, SLOT(loadEntity(Entity*)));
    QObject::connect(&scene, SIGNAL(newFire(Entity*)), this, SLOT(loadFire(Entity*)));
    QObject::connect(&scene, SIGNAL(phase2()), this, SLOT(advance()));
    GameProcessor::affDelimiters();
    QObject::connect(&scene, SIGNAL(forwardKeyPressEvent(QKeyEvent*)), this, SLOT(keyPressEvent(QKeyEvent*)));
    GameProcessor::createDisclaimer("Press RETURN to start");


    QGraphicsSimpleTextItem *txt = this->scene.addSimpleText("Lives:");
// attention on perd le pointeur. a changer.
    QFont font;
    QPen pen(Qt::red, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);
    font.setBold(true);
    font.setPointSize(20);
    txt->setFont(font);
    txt->setBrush(Qt::red);
    txt->setPen(pen);
    txt->setPos(WINSIZE_X / 2  + 5,- WINSIZE_Y / 2 + 10);
    QString str("Score:\n");
    str += QString::number(Score::get_instance()->getScore()) + QString::fromAscii("\nMax:\n") + QString::number(Score::get_instance()->getMax());
    txt = this->scene.addSimpleText(str);
    txt->setFont(font);
    txt->setBrush(Qt::red);
    txt->setPen(pen);
    txt->setPos(WINSIZE_X / 2  + 5,- WINSIZE_Y / 2 + 200);
    this->score = txt;
    //GameProcessor::affGrid();
}
Example #5
0
Foam::tmp<Foam::volScalarField> Foam::phasePair::magUr() const
{
    return mag(phase1().U() - phase2().U());
}
void gen_schedule_plan(){	
	
#ifdef DEVELOPING
	numVcore = 8;
	numPcore = 6;
#else
	// get from hypervisor
	// numVcore =;
	// numPcore =;
#endif
	
	vcoreContainer = (VIRT_CORE**)malloc(sizeof(VIRT_CORE*)*numVcore);
	pcoreContainer = (PHYS_CORE**)malloc(sizeof(PHYS_CORE*)*numPcore);

#ifdef DEVELOPING
	VIRT_CORE* temp_c;
	for(int i=0;i<numVcore;i++){
		temp_c = (VIRT_CORE*)malloc(sizeof(VIRT_CORE));
		temp_c->domain = i/4;
		temp_c->num = i%4;
		temp_c->requ = 100000*(i+1);
		temp_c->code = i;
		vcoreContainer[i] = temp_c;
	}

	PHYS_CORE* temp_p;
	for(int i=0;i<numPcore;i++){
		temp_p = (PHYS_CORE*)malloc(sizeof(PHYS_CORE));
		(i<2)?(temp_p->freq = 1200000):(temp_p->freq = 600000);
		(i<2)?(temp_p->type = TYPE_BIG):(temp_p->type = TYPE_LITTLE);
		temp_p->efficient = temp_p->type;
		temp_p->load = 0;
		temp_p->num = i;
		temp_p->workload = (int*)malloc(sizeof(int)*numVcore);
		for(int j=0;j<numVcore;j++){
			temp_p->workload[j] = 0;
		}
		pcoreContainer[i] = temp_p;
	}
#else
	// fetch vcpu and pcpu info
#endif


#ifdef DEVELOPING
	clock_t t;
	t = clock();
	// phase 1
	phase1();
	t = clock() - t;
	fprintf(stderr, "phase 1: %d ticks (%.3lf seconds).\n", t, ((double)t)/CLOCKS_PER_SEC);
	
	t = clock();
	// phase 2
	eSlice.next = NULL;
	phase2();
	t = clock() - t;
	fprintf(stderr, "phase 2: %d ticks (%.3lf seconds).\n", t, ((double)t)/CLOCKS_PER_SEC);

	t = clock();
	// phase 3
	phase3();
	t = clock() - t;
	fprintf(stderr, "phase 3: %d ticks (%.3lf seconds).\n", t, ((double)t)/CLOCKS_PER_SEC);
#else
	// phase 1
	phase1();

	// phase 2
	eSlice.next = NULL;
	phase2();

	// phase 3
	phase3();
#endif

	// clean up
	ExecutionSlice* target;
	while(exePlan.next != NULL){
		target = exePlan.next;
		exePlan.next = exePlan.next->next;
		free(target);
	};

	for(int i=0;i<numPcore;i++){
		free(pcoreContainer[i]);
	}
	free(pcoreContainer);

	for(int i=0;i<numVcore;i++){
		free(vcoreContainer[i]);
	}
	free(vcoreContainer);
}
Example #7
0
int solve_fr(mpfr_t *result, int n0, int m0, mpfr_t **a0, int *ineq0, mpfr_t *c0) {
  int i,j;

  m = m0;   // number of inequations
  n = n0+1; // number of variables

  init(n, m);

  mpfr_t csum;
  mpfr_zinit(csum);

  for(j=0;j<n0+1;j++) {
    mpfr_set(c[j], c0[j], GMP_RNDN);
  }

  for(j=1;j<n0+1;j++) {
    mpfr_add(csum, csum, c0[j], GMP_RNDN);
  }

  mpfr_set(c[n], csum, GMP_RNDN);
  mpfr_neg(c[n], c[n], GMP_RNDN);

  for(i=0;i<m;i++) {
    mpfr_set_d(csum, 0, GMP_RNDN);

    for(j=0;j<n0+1;j++) mpfr_set(a[i+1][j], a0[i][j], GMP_RNDN);
    mpfr_neg(a[i+1][0], a[i+1][0], GMP_RNDN);

    for(j=1;j<n0+1;j++) {
      mpfr_add(csum, csum, a0[i][j], GMP_RNDN);
    }

    mpfr_set(a[i+1][n], csum, GMP_RNDN);
    mpfr_neg(a[i+1][n], a[i+1][n], GMP_RNDN);
    inequality[i+1] = ineq0[i];

    if (mpfr_cmp_d(a[i+1][0], 0) < 0) {
      if      (inequality[i+1] == GEQ) inequality[i+1] = LEQ;
      else if (inequality[i+1] == LEQ) inequality[i+1] = GEQ;
      for (j = 0; j <= n; j++) mpfr_neg(a[i+1][j], a[i+1][j], GMP_RNDN);
    } else if (mpfr_cmp_d(a[i+1][0], 0) == 0 && inequality[i+1] == GEQ) {
      inequality[i+1] = LEQ;
      for (j = 1; j <= n; j++) mpfr_neg(a[i+1][j], a[i+1][j], GMP_RNDN);
    }
  }

  int p1r = 1;

  prepare();
  if (n3 != n2) p1r = phase1();

  if (!p1r) {
    dispose();
    return NOT_FEASIBLE;
  }

  int b = phase2();

  mpfr_t *s = calloc(sizeof(mpfr_t), n);
  for(j=0;j<n;j++) {
    mpfr_zinit(s[j]);
  }

  for (j = 1; j < n; j++) {
    if ((i = row[j]) != 0) {
      tableau(s[j], i, 0);
    }
  }

  mpfr_t cs;
  mpfr_zinit(cs);
  if (row[n] != 0) tableau(cs, row[n], 0);

  for (j = 1; j < n; j++) {
    mpfr_sub(s[j], s[j], cs, GMP_RNDN);
  }

  for(j=0;j<n;j++) {
    mpfr_set(result[j], s[j], GMP_RNDN);
  }

  mpfr_clear(cs);

  for(j=0;j<n;j++) mpfr_clear(s[j]);
  free(s);

  dispose();

  return b ? OK : MAXIMIZABLE_TO_INFINITY;
}
Example #8
0
/*-----------------------------------------------
|						|
|	 	  getdata()/0			|
|						|
|   This function reads the 1D or 2D data in 	|
|   form disk, manipulates it appropriately,	|
|   and moves the ReRe component to the memory	|
|   allocated for the phasefile data.		|
|						|
+----------------------------------------------*/
static int getdata()
{
   char		dsplymes[20],	/* display mode label		*/
		dmg1[5];
   int		npf1=0,		/* number of points along F1	*/
		npf2=0,		/* number of points along F2	*/
		i,
		r,
		found,
		f1phase,
		f2phase,
		quad2,
		quad4,
		complex_1D=0,
                norm_av,
                norm_dir,
                norm_phase,
                norm_phaseangle,
                norm_dbm,
                rev_av=0,
                rev_dir=0,
                rev_phase=0,
                rev_phaseangle=0,
		nplinear,
		npblock;
   float	*f1phasevec=NULL,	/* F1 phasing vector		*/
		*f2phasevec=NULL;	/* F2 phasing vector		*/
   double	rp_norm,
		lp_norm;
   double	rp_rev,
		lp_rev;
   dpointers	datablock;
   hycmplxhead	*tmpblkhead;


/********************************************
*  Get pointer to data in specified block.  *
********************************************/

   if ( (r = D_getbuf(D_DATAFILE, nblocks, c_buffer, &datablock)) )
   {
      D_error(r);
      return(ERROR);
   }
   else if (checkdata(datablock.head))
   {
      return(ERROR);
   }

/**********************
*  Setup for 2D data  *
**********************/

   quad2 = quad4 = FALSE;
   f1phase = f2phase = FALSE;

   if (d2flag)
   {
/************************************
*  Set the flags for the number of  *
*  quadrants.                       *
************************************/

     quad4 = (datahead.status & S_HYPERCOMPLEX);
     if (!quad4)
        quad2 = (datahead.status & S_COMPLEX);

/********************************************
*  Precalculate phasing vectors for the F1  *
*  and F2 dimensions if necessary.          *
********************************************/

      nplinear = pointsperspec;
      npblock = specperblock * nblocks;
      if (quad4)
      {
         npblock *= 2;
         nplinear /= 2;
      }

      if (revflag)
      {
         npf1 = nplinear;
         npf2 = npblock;
      }
      else
      {
         npf2 = nplinear;
         npf1 = npblock;
      }

      f1phasevec = NULL;	/* initialize pointer */
      f2phasevec = NULL;	/* initialize pointer */

/**********************************************
*  If a phase-sensitive display is requested  *
*  along F1, precalculate the F1 phasing      *
*  vector.                                    *
**********************************************/

      rev_dir = get_direction(REVDIR);
      get_phase_pars(rev_dir,&rp_rev,&lp_rev);
      rev_phase = get_phase_mode(rev_dir);
      rev_phaseangle = get_phaseangle_mode(rev_dir);
      rev_av = get_av_mode(rev_dir);
      f1phase = ( ((rev_phase && nonzerophase(rp_rev, lp_rev)) || rev_phaseangle) &&
                  (quad2 || quad4) &&
		  get_axis_freq(rev_dir) );

      if (f1phase)
      {
         f1phasevec = (float *) (allocateWithId( (unsigned) (sizeof(float)
	 			    * npf1), "getdata" ));
         if (f1phasevec == NULL)
         {
            Werrprintf("Unable to allocate memory for F1 phase buffer");
            return(ERROR);
         }
         else
         {
            phasefunc(f1phasevec, npf1/2, lp_rev, rp_rev);
         }
      }

/**********************************************
*  If a phase-sensitive display is requested  *
*  along F2, precalculate the F2 phasing      *
*  vector.                                    *
**********************************************/

      norm_dir = get_direction(NORMDIR);
      get_phase_pars(norm_dir,&rp_norm,&lp_norm);
      norm_phase = get_phase_mode(norm_dir);
      norm_phaseangle = get_phaseangle_mode(norm_dir);
      norm_av = get_av_mode(norm_dir);
      norm_dbm = get_dbm_mode(norm_dir); /* may not be active?? */
      f2phase = ( (norm_phase || norm_phaseangle) && quad4 && nonzerophase(rp_norm, lp_norm) );
		/* (quad4 || quad2)??  (quad4) only?? */

      if (f2phase)
      {
         f2phasevec = (float *) (allocateWithId( (unsigned) (sizeof(float)
	 			    * npf2), "getdata" ));
         if (f2phasevec == NULL)
         {
            Werrprintf("Unable to allocate memory for F2 phase buffer");
            if (f1phase)
               releaseAllWithId("getdata");
            return(ERROR);
         }
         else
         {
            phasefunc(f2phasevec, npf2/2, lp_norm, rp_norm);
         }
      }
   }
   else
   {
      complex_1D = (datablock.head->status & NP_CMPLX);
      norm_dir = HORIZ;
      norm_phase = get_phase_mode(norm_dir);
      norm_phaseangle = get_phaseangle_mode(norm_dir);
      norm_av = get_av_mode(norm_dir);
      norm_dbm = get_dbm_mode(norm_dir); /* may not be active 2 */
   }

/*************************************
*  Readjust "npf1" and "npf2" to be  *
*  per block.                        *
*************************************/

   if (d2flag)
   {
      if (revflag)
      {
         npf2 /= nblocks;
      }
      else
      {
         npf1 /= nblocks;
      }
   }

/**********************************
*  Construct display mode label.  *
**********************************/

   strcpy(dsplymes, ""); 	/* initialization of string */

   if ( d2flag && (quad2 || quad4) )
   {
      char charval;
      char tmp[10];

      get_display_label(rev_dir,&charval);
      if (rev_phase)
      {
         sprintf(tmp, "PH%c ",charval);
      }
      else if (rev_av)
      {
         sprintf(tmp, "AV%c ",charval);
      }
      else if (rev_phaseangle)
      {
         sprintf(tmp, "PA%c ",charval);
      }
      else
      {
         sprintf(tmp, "PW%c ",charval);
      }

      strcpy(dsplymes, tmp);
   }

   if ( (d2flag && quad4) || ((!d2flag) && complex_1D) )
   {
      char charval;
      char tmp[10];

      get_display_label(norm_dir,&charval);
      if (charval == '\0')
         charval = ' ';
      if (norm_phase)
      {
         sprintf(tmp, "PH%c",charval);
      }
      else if (norm_av)
      {
         sprintf(tmp, "AV%c",charval);
      }
      else if (norm_phaseangle)
      {
         sprintf(tmp, "PA%c",charval);
      }
      else
      {
         sprintf(tmp, "PW%c",charval);
      }

      strcat(dsplymes, tmp);
   }

   disp_status(dsplymes);

/*************************************************
*  Manipulate data depending upon the number of  *
*  2D data quadrants and the desired mode of     *
*  display.					 *
*************************************************/

   if (d2flag)
   {
      if (quad4)
      {

/***********************************
*  HYPERCOMPLEX 2D spectral data:  *
*  F2 phase-sensitive display      *
***********************************/

         if (norm_phase)
         {
            if (rev_phase)
            {

	/*****************************
	*  phase for ReRe component  *
	*****************************/
               if (f1phase && f2phase)
               {
                  blockphase4(datablock.data, c_block.data, f1phasevec,
	  		f2phasevec, nblocks, c_buffer, npf1/2, npf2/2);
               }
               else if (f1phase)
               {
                  blockphase2(datablock.data, c_block.data, f1phasevec,
			nblocks, c_buffer, npf1/2, npf2/2, HYPERCOMPLEX,
			COMPLEX, TRUE, FALSE);
               }
               else if (f2phase)
               {
                  blockphase2(datablock.data, c_block.data, f2phasevec,
			nblocks, c_buffer, npf1/2, npf2/2, HYPERCOMPLEX,
			REAL, FALSE, FALSE);
               }
               else
               {
                  movmem((char *)datablock.data, (char *)c_block.data,
			(npf1*npf2*sizeof(float))/4, HYPERCOMPLEX,
			4);
               }
            }
            else
            {
               if (f2phase)
               {

	/***************************
	*  rotate ReRe <---> ReIm  *
	*  rotate ImRe <---> ImIm  *
	***************************/
                  if (rev_av)
                  {

	/********************************
	*  S = sqrt(ReRe**2 + ImRe**2)  *
	********************************/
                     blockphsabs4(datablock.data, c_block.data, f2phasevec,
			   nblocks, c_buffer, npf1/2, npf2/2, REAL, FALSE);
                  }
                  else if (rev_phaseangle)
                  {
                     blockphaseangle2(datablock.data, c_block.data, f1phasevec,
                           nblocks, c_buffer, npf1/2, npf2/2, HYPERCOMPLEX,
                           COMPLEX, TRUE, FALSE);
                  }
                  else
                  {

	/**************************
	*  S = ReRe**2 + ImRe**2  *
	**************************/
                     blockphspwr4(datablock.data, c_block.data, f2phasevec,
			   nblocks, c_buffer, npf1/2, npf2/2, REAL, FALSE);
                  }
               }
               else if (rev_av)	/* no F2 phasing required */
               {

	/********************************
	*  S = sqrt(ReRe**2 + ImRe**2)  *
	********************************/
                  absval2(datablock.data, c_block.data, (npf1*npf2)/4,
                        HYPERCOMPLEX, COMPLEX, REAL, FALSE);
               }
/* else if (rev_phaseangle) {} */
               else			/* no F2 phasing required */
               {

	/**************************
	*  S = ReRe**2 + ImRe**2  *
	**************************/
                  pwrval2(datablock.data, c_block.data, (npf1*npf2)/4,
                        HYPERCOMPLEX, COMPLEX, REAL, FALSE);
               }
            }
         }

/***********************************
*  HYPERCOMPLEX 2D spectral data:  *
*  F2 absolute-value display       *
***********************************/

         else if (norm_av)
         {
            if (rev_phase)
            {
               if (f1phase)
               {

	/********************************
	*  rotate ReRe <---> ImRe       *
	*  rotate ReIm <---> ImIm       *
	*  S = sqrt(ReRe**2 + ReIm**2)  *
	********************************/
                  blockphsabs4(datablock.data, c_block.data, f1phasevec,
			   nblocks, c_buffer, npf1/2, npf2/2, COMPLEX, TRUE);
               }
               else
               {

	/********************************
	*  S = sqrt(ReRe**2 + ReIm**2)  *
	********************************/
                  absval2(datablock.data, c_block.data, (npf1*npf2)/4,
			HYPERCOMPLEX, REAL, REAL, FALSE);
               }
            }
            else if (rev_av)
            {

	/****************************************************
	*  S = sqrt(ReRe**2 + ReIm**2 + ImRe**2 + ImIm**2)  *
	****************************************************/
               absval4(datablock.data, c_block.data, npf1*npf2/4);
            }
/* else if (rev_phaseangle) {} */
            else
            {

	/****************************
	*  S1 = ReRe**2 + ImRe**2   *
	*  S2 = ReIm**2 + ImIm**2   *
        *  S = sqrt(S1**2 + S2**2)  *
	****************************/
               blockpwrabs(datablock.data, c_block.data, (npf1*npf2)/4,
				COMPLEX);
            }
         }

/***********************************
*  HYPERCOMPLEX 2D spectral data:  *
*  F2 phaseangle display           *
***********************************/

         else if (norm_phaseangle)
         {
            Werrprintf("Cannot perform hypercomplex phaseangle");
            return(ERROR);
         }

/***********************************
*  HYPERCOMPLEX 2D spectral data:  *
*  F2 power display                *
***********************************/

         else
         {
            if (rev_phase)
            {
               if (f1phase)
               {

	/***************************
	*  rotate ReRe <---> ImRe  *
	*  rotate ReIm <---> ImIm  *
	*  S = ReRe**2 + ReIm**2   *
	***************************/
                  blockphspwr4(datablock.data, c_block.data, f1phasevec,
			   nblocks, c_buffer, npf1/2, npf2/2, COMPLEX, TRUE);
               }
               else
               {

	/**************************
	*  S = ReRe**2 + ReIm**2  *
	**************************/
                  pwrval2(datablock.data, c_block.data, (npf1*npf2)/4,
			   HYPERCOMPLEX, REAL, REAL, FALSE);
               }
            }
            else if (rev_av)
            {

	/****************************
	*  S1 = ReRe**2 + ReIm**2   *
	*  S2 = ImRe**2 + ImIm**2   *
        *  S = sqrt(S1**2 + S2**2)  *
	****************************/
               blockpwrabs(datablock.data, c_block.data, (npf1*npf2)/4,
				REAL);
            }
/* else if (rev_phaseangle) {} */
            else
            {

	/**********************************************
	*  S = ReRe**2 + ReIm**2 + ImRe**2 + ImIm**2  *
	*  THIS IS NOT QUITE RIGHT!                   *
	**********************************************/
               pwrval4(datablock.data, c_block.data, npf1*npf2/4);
            }
         }

/**********************************************
*  Set the F1 phase constants into the block  *
*  header of the phasefile data.              *
**********************************************/

         if (rev_phase || rev_phaseangle)
         {
            c_block.head->lpval = lp_rev;
            c_block.head->rpval = rp_rev;
         }
         else
         {
            c_block.head->lpval = 0.0;
            c_block.head->rpval = 0.0;
         }

/***************************************************
*  Locate the block header for the "hypercomplex"  *
*  information.  Then set the F2 phase constants   *
*  into the block header of the phasefile data.    *
***************************************************/

         i = 0;
         found = FALSE;

         while (!found)
         {
            if ( (~(datablock.head + i)->status) & MORE_BLOCKS )
            {
               Werrprintf("Block headers inconsistent with hypercomplex data");
               if (f1phase || f2phase)
                  releaseAllWithId("getdata");
               return(ERROR);
            }

            i += 1;
            found = ( (datablock.head + i)->status & U_HYPERCOMPLEX );
         }

         tmpblkhead = (hycmplxhead *) (c_block.head + i);
         if (norm_phase)
         {
            tmpblkhead->lpval1 = lp_norm;
            tmpblkhead->rpval1 = rp_norm;
         }
         else
         {
            tmpblkhead->lpval1 = 0.0;
            tmpblkhead->rpval1 = 0.0;
         }
      }
      else if (quad2)
      {

/*******************************
*  COMPLEX 2D spectral data:   *
*  F1 display selection        *
*******************************/

         if (rev_phase)
         {

       /***************************
       *  rotate ReRe <---> ImRe  *
       ***************************/
            if (f1phase)
            {
               blockphase2(datablock.data, c_block.data, f1phasevec,
			nblocks, c_buffer, npf1/2, npf2, COMPLEX, 1,
			TRUE, FALSE);
            }
            else
            {
               movmem((char *)datablock.data, (char *)c_block.data,
			(npf1*npf2*sizeof(float))/2, COMPLEX, 4);
            }
         }
         else if (rev_phaseangle)
         {
            if (f1phase)
            {
               blockphaseangle2(datablock.data, c_block.data, f1phasevec,
			nblocks, c_buffer, npf1/2, npf2, COMPLEX, 1,
			TRUE, FALSE);
            }
            else
            {
               movmem((char *)datablock.data, (char *)c_block.data,
                        (npf1*npf2*sizeof(float))/2, COMPLEX, 4);
            }
         }
         else if (rev_av)
         {

       /********************************
       *  S = sqrt(ReRe**2 + ImRe**2)  *
       ********************************/
            absval2(datablock.data, c_block.data, (npf1*npf2)/2,
			COMPLEX, 1, 1, FALSE);
         }
         else
         {

       /**************************
       *  S = ReRe**2 + ImRe**2  *
       **************************/
            pwrval2(datablock.data, c_block.data, (npf1*npf2)/2,
			COMPLEX, 1, 1, FALSE);
         }

         if (rev_phase || rev_phaseangle)
         {
            c_block.head->lpval = lp_rev;
            c_block.head->rpval = rp_rev;
         }
         else
         {
            c_block.head->lpval = 0.0;
            c_block.head->rpval = 0.0;
         }
      }
      else
      {

/***************************
*  REAL 2D spectral data   *
***************************/

         movmem((char *)datablock.data, (char *)c_block.data,
			npf1*npf2*sizeof(float), REAL, 4);
         c_block.head->lpval = 0.0;
         c_block.head->rpval = 0.0;
      }
   }

/**********************
*  Setup for 1D data  *
**********************/

   else
   {
    if(bph()>0 && complex_1D && (norm_phase || norm_phaseangle)) {
      // don't use lp, rp, because block is individually phased. 
      c_block.head->lpval=getBph1(c_buffer); 
      c_block.head->rpval=getBph0(c_buffer);
      if (norm_phase)
      {
        phase2(datablock.data, c_block.data, fn/2, c_block.head->lpval, c_block.head->rpval);
      }
      else if (norm_phaseangle)
      {
        phaseangle2(datablock.data, c_block.data, fn/2, COMPLEX,
			1, 1, FALSE, c_block.head->lpval, c_block.head->rpval);
      }
      P_setreal(CURRENT,"bph1",c_block.head->lpval,0);
      P_setreal(CURRENT,"bph0",c_block.head->rpval,0);
    } else { 
      c_block.head->lpval = 0.0;
      c_block.head->rpval = 0.0;

      if (complex_1D)
      {
         if (norm_phase)
         {
            phase2(datablock.data, c_block.data, fn/2, lp, rp);
            c_block.head->lpval = lp;
            c_block.head->rpval = rp;
         }
         else if (norm_phaseangle)
         {
            phaseangle2(datablock.data, c_block.data, fn/2, COMPLEX,
			1, 1, FALSE, lp, rp);
            c_block.head->lpval = lp;
            c_block.head->rpval = rp;
         }
         else if (norm_av)
         {
            absval2(datablock.data, c_block.data, fn/2, COMPLEX,
			1, 1, FALSE);
         }
         else if (norm_dbm)
         {
            dbmval2(datablock.data, c_block.data, fn/2, COMPLEX,
			1, 1, FALSE);
         } 
         else
         {
            pwrval2(datablock.data, c_block.data, fn/2, COMPLEX,
			1, 1, FALSE);
         }
      }
      else
      {
         if (datablock.head->status & S_COMPLEX)
         {
            movmem((char *)datablock.data, (char *)c_block.data,
			(fn/2)*sizeof(float), COMPLEX, 4);
         }
         else
         {
            movmem((char *)datablock.data, (char *)c_block.data,
			(fn/2)*sizeof(float), REAL, 4);
         }
      }
    }
   }

/*************************************
*  Set status word for block header  *
*  of phasefile.                     *
*************************************/

   c_block.head->status = (S_DATA|S_SPEC|S_FLOAT);

/*********************************** 
*  Set mode word for block header  * 
*  of phasefile.                   * 
***********************************/

   c_block.head->mode = get_mode(HORIZ);
   if (d2flag)
      c_block.head->mode |= get_mode(VERT);

/***************************************
*  Set additional words in main block  *
*  header of phasefile.                *
***************************************/

   c_block.head->scale = 0;
   c_block.head->ctcount = 0;
   c_block.head->index = (short)c_buffer;
   c_block.head->lvl = 0.0;
   c_block.head->tlt = 0.0;

/************************************************
*  Set status word in previous block header of  *
*  phasefile to indicate the presence of a      *
*  following block header.                      *
************************************************/

   if (d2flag)
   {
      i = 0;
      while ((datablock.head + i)->status & MORE_BLOCKS)
      {
         (c_block.head + i)->status |= MORE_BLOCKS;
         i += 1;
         if ((datablock.head + i)->status & U_HYPERCOMPLEX)
            (c_block.head + i)->status |= U_HYPERCOMPLEX;
      }
   }


/******************************************
*  Release this DATAFILE buffer with the  *
*  data handler routines.                 *
******************************************/

   if ( (r = D_release(D_DATAFILE, c_buffer)) )
   {
      D_error(r);
      if (f1phase || f2phase)
         releaseAllWithId("getdata");
      return(ERROR);
   }

   if (P_copyvar(CURRENT, PROCESSED, "dmg", "dmg"))
   {
      Werrprintf("dmg:  cannot copy from 'current' to 'processed' tree\n");
      if (f1phase || f2phase)
         releaseAllWithId("getdata");
      return(ERROR);
   }

   if (d2flag)
   {
      if (!P_getstring(CURRENT, "dmg1", dmg1, 1, 5))
      {
         if (P_copyvar(CURRENT, PROCESSED, "dmg1", "dmg1"))
         {
            Werrprintf("dmg1: cannot copy from 'current' to 'processed' tree");
            if (f1phase || f2phase) 
               releaseAllWithId("getdata");
            return(ERROR);
         }
      }
   }

   if (f1phase || f2phase)
      releaseAllWithId("getdata");
   if (!Bnmr)
      disp_status("                 ");
   return(COMPLETE);
}
Example #9
0
int SubdivideExtrudedMesh(GModel *m)
{
  // get all non-recombined extruded regions and vertices; also,
  // create a vector of quadToTri regions that have NOT been meshed
  // yet
  std::vector<GRegion*> regions, regions_quadToTri;
  MVertexRTree pos(CTX::instance()->geom.tolerance * CTX::instance()->lc);
  for(GModel::riter it = m->firstRegion(); it != m->lastRegion(); it++){
    ExtrudeParams *ep = (*it)->meshAttributes.extrude;
    if(ep && ep->mesh.ExtrudeMesh && ep->geo.Mode == EXTRUDED_ENTITY &&
       !ep->mesh.Recombine){
      regions.push_back(*it);
      insertAllVertices(*it, pos);
    }
    // create vector of valid quadToTri regions...not all will necessarily be meshed here.
    if(ep && ep->mesh.ExtrudeMesh && ep->geo.Mode == EXTRUDED_ENTITY &&
       ep->mesh.Recombine && ep->mesh.QuadToTri){
      regions_quadToTri.push_back(*it);
    }
  }

  if(regions.empty()) return 0;
  Msg::Info("Subdividing extruded mesh");

  // create edges on lateral sides of "prisms"
  std::set<std::pair<MVertex*, MVertex*> > edges;
  for(unsigned int i = 0; i < regions.size(); i++)
    phase1(regions[i], pos, edges);

  // swap lateral edges to make them "tet-compatible"
  int j = 0, swap;
  std::set<std::pair<MVertex*, MVertex*> > edges_swap;
  do {
    swap = 0;
    for(unsigned int i = 0; i < regions.size(); i++)
      phase2(regions[i], pos, edges, edges_swap, swap);
    Msg::Info("Swapping %d", swap);
    if(j && j == swap) {
      Msg::Error("Unable to subdivide extruded mesh: change surface mesh or");
      Msg::Error("recombine extrusion instead");
      return -1;
    }
    j = swap;
  } while(swap);

  // delete volume elements and create tetrahedra instead
  for(unsigned int i = 0; i < regions.size(); i++){
    GRegion *gr = regions[i];

    for(unsigned int i = 0; i < gr->tetrahedra.size(); i++)
      delete gr->tetrahedra[i];
    gr->tetrahedra.clear();
    for(unsigned int i = 0; i < gr->hexahedra.size(); i++)
      delete gr->hexahedra[i];
    gr->hexahedra.clear();
    for(unsigned int i = 0; i < gr->prisms.size(); i++)
      delete gr->prisms[i];
    gr->prisms.clear();
    for(unsigned int i = 0; i < gr->pyramids.size(); i++)
      delete gr->pyramids[i];
    gr->pyramids.clear();
    phase3(gr, pos, edges);

    // re-Extrude bounding surfaces using edges as constraint
    std::list<GFace*> faces = gr->faces();
    for(std::list<GFace*>::iterator it = faces.begin(); it != faces.end(); it++){
      ExtrudeParams *ep = (*it)->meshAttributes.extrude;
      if(ep && ep->mesh.ExtrudeMesh && ep->geo.Mode == EXTRUDED_ENTITY &&
        !ep->mesh.Recombine){
        GFace *gf = *it;
        Msg::Info("Remeshing surface %d", gf->tag());
        for(unsigned int i = 0; i < gf->triangles.size(); i++)
          delete gf->triangles[i];
        gf->triangles.clear();
        for(unsigned int i = 0; i < gf->quadrangles.size(); i++)
          delete gf->quadrangles[i];
        gf->quadrangles.clear();
        MeshExtrudedSurface(gf, &edges);
      }
    }
  }

  // now mesh the QuadToTri regions. Everything can be done locally
  // for each quadToTri region, but still use edge set from above just
  // to make sure laterals get remeshed properly (
  // QuadToTriEdgeGenerator detects if the neighbor has been meshed or
  // if a lateral surface should remain static for any other reason).
  // If this function detects allNonGlobalSharedLaterals, it won't
  // mesh the region (should already be done in ExtrudeMesh).
  for(unsigned int i = 0; i < regions_quadToTri.size(); i++){
    GRegion *gr = regions_quadToTri[i];
    MVertexRTree pos_local(CTX::instance()->geom.tolerance * CTX::instance()->lc);
    insertAllVertices(gr, pos_local);
    meshQuadToTriRegionAfterGlobalSubdivide(gr, &edges, pos_local);
  }

  // carve holes if any
  // TODO: update extrusion information
  for(unsigned int i = 0; i < regions.size(); i++){
    GRegion *gr = regions[i];
    ExtrudeParams *ep = gr->meshAttributes.extrude;
    if(ep->mesh.Holes.size()){
      std::map<int, std::pair<double, std::vector<int> > >::iterator it;
      for(it = ep->mesh.Holes.begin(); it != ep->mesh.Holes.end(); it++)
        carveHole(gr, it->first, it->second.first, it->second.second);
    }
  }
  for(unsigned int i = 0; i < regions_quadToTri.size(); i++){
    GRegion *gr = regions_quadToTri[i];
    ExtrudeParams *ep = gr->meshAttributes.extrude;
    if(ep->mesh.Holes.size()){
      std::map<int, std::pair<double, std::vector<int> > >::iterator it;
      for(it = ep->mesh.Holes.begin(); it != ep->mesh.Holes.end(); it++)
        carveHole(gr, it->first, it->second.first, it->second.second);
    }
  }

  return 1;
}
Example #10
0
int main(int argc, char **argv)
{
    if (argc != 4) {
        printf("usage: %s <server-address> <server-port> <phase[-1 - 6]>\n",
                argv[0]);
        return EXIT_FAILURE;
    }
    int start_phase = atoi(argv[3]);

    bool res;

    test_state_t *state = NULL;
    rvm_cfg_t *cfg;
    if(start_phase >= 0) {
        /* Try to recover from server */
        cfg = initialize_rvm(argv[1], argv[2], true,
                create_rmem_layer);

        /* Recover the state (if any) */
        state = (test_state_t*)rvm_get_usr_data(cfg);
    } else {
        /* Starting from scratch */
        cfg = initialize_rvm(argv[1], argv[2], false,
                create_rmem_layer);
        CHECK_ERROR(cfg == NULL, ("Failed to initialize rvm\n"));

        state = NULL;
    }

    rvm_txid_t txid;
    /*====================================================================
     * TX 0 - Allocate and Initialize Arrays
     *===================================================================*/
    /* If state is NULL then we are starting from scratch or recovering from
       an early error */
    if(state == NULL) {
        LOG(1,("Phase 0:\n"));
        TX_START;

        /* Allocate a "state" structure to test pointers */
        state = (test_state_t*)rvm_alloc(cfg, sizeof(test_state_t));
        CHECK_ERROR(state == NULL, ("FAILURE: Couldn't allocate state\n"));

        /* Initialize the arrays */ 
        res = phase0(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 0 Failure\n"));

        if(start_phase == -1) {
            LOG(1, ("SUCCESS: Phase 0, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        /* End of first txn */
        state->phase = PHASE1;
        TX_COMMIT;
    }

    switch(state->phase) {
    case PHASE1:
        /*====================================================================
         * TX 1 Increment arrays, don't mess with LL
         *===================================================================*/
        LOG(1, ("Phase 1:\n"));
        TX_START;
        
        res = phase1(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 1 failed\n"));

        /* Simulate Failure */
        if(start_phase == 0) {
            LOG(1, ("SUCCESS: Phase 1, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE2;
        TX_COMMIT;
    
    case PHASE2: //Fallthrough
        /*====================================================================
         * TX 2 Free Arrays
         *===================================================================*/
        LOG(1, ("Phase 2:\n"));
        TX_START;

        res = phase2(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 2 failed\n"));

        /* Simulate Failure */
        if(start_phase == 1) {
            LOG(1, ("SUCCESS: Phase 2, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE3;
        TX_COMMIT;

    case PHASE3: //Fallthrough
        /*====================================================================
         * TX 3 Fill in Linked list
         *===================================================================*/
        LOG(1, ("Phase 3:\n"));
        TX_START;

        res = phase3(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 3 failed\n"));

        /* Simulate Failure */
        if(start_phase == 2) {
            LOG(1, ("SUCCESS: Phase 3, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE4;
        TX_COMMIT;

    case PHASE4:
        /*====================================================================
         * TX 4 Free Half the linked list
         *===================================================================*/
        LOG(1, ("Phase 4:\n"));
        TX_START;

        res = phase4(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 4 failed\n"));

         /* Simulate Failure */
        if(start_phase == 3) {
            LOG(1, ("SUCCESS: Phase 4, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = PHASE5;
        TX_COMMIT;

    case PHASE5:
        /*====================================================================
         * TX 5 Re-allocate half of the linked list
         *===================================================================*/
        LOG(1, ("Phase 5:\n"));
        TX_START;

        res = phase5(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 5 failed\n"));

         /* Simulate Failure */
        if(start_phase == 4) {
            LOG(1, ("SUCCESS: Phase5, simulating failure\n"));
            return EXIT_SUCCESS;
        }

       state->phase = PHASE6;
        TX_COMMIT;

    case PHASE6:
        /*====================================================================
         * TX 6 Free whole linked list
         *===================================================================*/
        LOG(1, ("Phase 6:\n"));
        TX_START;

        res = phase6(cfg, state);
        CHECK_ERROR(!res, ("FAILURE: Phase 6 failed\n"));

        /* Simulate Failure */
        if(start_phase == 5) {
            LOG(1, ("SUCCESS: Phase 6, simulating failure\n"));
            return EXIT_SUCCESS;
        }

        state->phase = DONE;
        TX_COMMIT;

    case DONE:
        res = rvm_cfg_destroy(cfg);
        CHECK_ERROR(!res, ("FAILURE: Failed to destroy rvm state\n"));

        LOG(1, ("SUCCESS: Got through all phases\n"));
        break;

    default:
        LOG(1, ("FAILURE: Corrupted State, tried phase %d\n", state->phase));
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Example #11
0
Foam::word Foam::phasePair::name() const
{
    word name2(phase2().name());
    name2[0] = toupper(name2[0]);
    return phase1().name() + "And" + name2;
}
Example #12
0
void
psrs(int size, int rank, int nInts, int *toSort, char *fname)
{
	char hname[256];
	double start, end, total = 0, algStart;
	int i, *privateInts, *regularSamples, *collectedSamples, *pivots, 
	    *partitionIndices, *localPartitionSizes, *incomingPartitionSizes, 
	    **partitions, *mergedPartitions, *partitionSizes, *sortedArray; 

	FILE *fptr = NULL;
	if (rank == MASTER) fptr = fopen(fname, "a");
	
	memset (hname, '\0', sizeof(unsigned char)*256);
	gethostname(hname, 255);

	DBPRINT(("%d of %d running on pid %d %s\n", rank, size, getpid(), 
	    hname));

	if (rank == MASTER) {
		collectedSamples = calloc(1, sizeof(int)*size*size);
		if (!collectedSamples) {
			err(1,"Failed to allocate memory for collected samples "
			   "array for master process");
			MPI_Finalize();
			exit(1);
		}				
	}
	MPI_Barrier(MPI_COMM_WORLD);

	if (nInts < VALIDATION_THRESHOLD) validateResults = 1;

	/* 
	 * "Phase 0" in which the array is split into contiguous chunks
	 * distributed amongst the processes.
	 */
	phase0(size, rank, nInts, toSort, &privateInts);

	/* Phase 1 */

	algStart = MPI_Wtime();
	START_TIMER((start));
	phase1(size, rank, nInts, toSort, privateInts, &regularSamples);
	MPI_Barrier(MPI_COMM_WORLD);
	STOP_TIMER((1), (start), (end), (total), (rank), (fptr));

	/* Phase 2 */
	START_TIMER((start));
	phase2(size, rank, regularSamples, &collectedSamples, &pivots);
	MPI_Barrier(MPI_COMM_WORLD);
	STOP_TIMER((2), (start), (end), (total), (rank), (fptr));

	/* Phase 3 */
	START_TIMER((start));
	phase3(size, rank, nInts, privateInts, pivots, &localPartitionSizes,
	    &partitionIndices, &incomingPartitionSizes, &partitions); 
	MPI_Barrier(MPI_COMM_WORLD);
	STOP_TIMER((3), (start), (end), (total), (rank), (fptr));

	/* Phase 4 */
	START_TIMER((start));
	phase4(size, incomingPartitionSizes, partitions, &mergedPartitions);
	MPI_Barrier(MPI_COMM_WORLD);
	STOP_TIMER((4), (start), (end), (total), (rank), (fptr));
	if (rank == MASTER) {
		total = end - algStart;
		fprintf(fptr, "The algorithm took %f seconds in total\n", total);
	}

	if (!validateResults) return;


	/* Run validation test */
	
	/* "Phase 5" concatenate the lists back at the master */
	phase5(size, rank, nInts, incomingPartitionSizes,
	    mergedPartitions, &partitionSizes, &sortedArray);

	/* 
	 * Assert that the array is equivalent to the sorted original array
	 * where we sort the original array using a known, proven, sequential,
	 * method.
	 */
	if (rank == MASTER) {
		qsort(toSort, nInts, sizeof(int), intComp);
	}

	for (i = 0; i < nInts; i++) {
		if (rank == MASTER) {
			if (toSort[i] != sortedArray[i]) {
				printf("OH NO, got %d at pos %d, expected "
				    "%d\n", sortedArray[i], i, toSort[i]);
			}
		}
	}
	
	if (rank == MASTER) fclose(fptr);
}
Example #13
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ArrayInit();

    QFile file;//загрузка jquery и добавление ноу конфликт
    file.setFileName(":/jquery-1.11.3.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();

    ServIP="127.0.0.1";


    QFile htmlF;//подгрузка html
    htmlF.setFileName(":/page.html");
    htmlF.open(QFile::ReadOnly);
    Html = htmlF.readAll();
    htmlF.close();

    QFile styleF;//подгрузка стилей
    styleF.setFileName("://style.qss");
    styleF.open(QFile::ReadOnly);
    QString qssStr = styleF.readAll();
    qApp->setStyleSheet(qssStr);
    styleF.close();

     QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::AutoLoadImages, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);
     connect(ui->webView,SIGNAL(loadFinished(bool)),this,SLOT(UIloadFinished(bool)));
     ui->webView->load(QUrl("http://free-filmy.ru/"));

    connect(this,SIGNAL (phase2(QString)),this ,SLOT(Phase2Do(QString)));
    wb1=new QWebView();
    connect(wb1,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool)));
    connect(wb1,SIGNAL(loadProgress(int)),this, SLOT(changeProgress(int)));
    wb2=new QWebView();
    connect(wb2,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished2(bool)));

    dial=new QDialog;
    wb3=new QWebView();
    pb=new QPushButton();
    pb->setText("OK");
    VBox=new QVBoxLayout;
    VBox->addWidget(wb3);
    VBox->addWidget(pb);
    HBox=new QHBoxLayout;
    HBox->addLayout(VBox);
    dial->setLayout(HBox);

    dial2=new QDialog;
    wb4=new QWebView();
    VBox2=new QVBoxLayout;
    VBox2->addWidget(wb4);
    HBox2=new QHBoxLayout;
    HBox2->addLayout(VBox2);
    dial2->setLayout(HBox2);


  connect(pb,SIGNAL(clicked(bool)),this,SLOT(pb_click(bool)));
  connect(wb3->page()->mainFrame(),SIGNAL(titleChanged(QString)),this,SLOT(img_put(QString)));

  done2=true;

}
Example #14
0
Foam::tmp<Foam::volScalarField> Foam::phasePair::rho() const
{
    return phase1()*phase1().rho() + phase2()*phase2().rho();
}
bool TOCAnalyzer::performTOCLab()
{

    LPOVERLAPPED readOverlapped;
    LPOVERLAPPED writeOverlapped;
    struct TOCData allocation;
    struct TOCData vialInformation;
    struct TOCData sampleInformation;
    struct TOCData sampleInformation2;


    for(int index=0; index<3; index++)
        vialInformation.write[index] = ACKStruct.write[index];

    vialInformation.write[4] = 0X05ab;
    vialInformation.write[5] = 0x07f4;
    vialInformation.write[6] = 0x2804;
    vialInformation.write[7] = 0;
    vialInformation.write[8] = 0;
    vialInformation.write[9] = 0;
    vialInformation.write[10] = 0;
    vialInformation.write[11] = 0x3200;
    vialInformation.size = 12;

    initLab(sampleInformation,sampleData.getSampleInformation().getVialPosition());


    for(int shift=0; shift<59; shift++)
        sampleInformation2.write[shift] = sampleInformation.write[shift+3];
    sampleInformation2.write[1] +=(1<<8);
    sampleInformation2.write[38]+=(1<<8);
    sampleInformation2.write[58] +=(2<<8);
    sampleInformation2.size = 59;
    Sleep(10);
    memset(&vialInformation,0,sizeof(struct TOCData));
	memset(&secWriteBuffer,0,sizeof(struct TOCData));
	memset(&secReadBuffer,0,sizeof(struct TOCData));
	memset(&writeBuffer,0,sizeof(struct TOCData));
	memset(&readBuffer,0,sizeof(struct TOCData));
    initLab(vialInformation,sampleData.getSampleInformation().getVialPosition());
   
    phase(secWriteBuffer);
    phase2(writeBuffer);
    Sleep(300);
    writeOverlapped = sendToTOC(serialPortConfiguration,secWriteBuffer);
    Sleep(250);
    readOverlapped =  readFromTOC(serialPortConfiguration,10,secReadBuffer.write);
    Sleep(400);
    while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    delete writeOverlapped;
    delete readOverlapped;
    Sleep(400);


    writeOverlapped=sendToTOC(serialPortConfiguration,writeBuffer);
    Sleep(650);
    readOverlapped=readACK();
    while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    delete writeOverlapped;
    delete readOverlapped;
    Sleep(4000);
    int index=0;
	cout<<"phase 1 done"<<endl;
    while(1) {

       
        //allocation= new TOCData;
        memset(&allocation,0,sizeof(struct TOCData));

        writeOverlapped=sendToTOC(serialPortConfiguration,ACKStruct);
        Sleep(50);
        readOverlapped=readFromTOC(serialPortConfiguration,12,allocation.write);

        while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
        if(allocation.write[1]==19 && allocation.write[13] ==0)
            break;
        allocation.size = 6;

        delete writeOverlapped;
        delete readOverlapped;
        // delete allocation;
        Sleep(250);

    }
    while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    delete writeOverlapped;
    delete readOverlapped;
	cout<<"phase 2 done"<<endl;

    writeOverlapped=sendToTOC(serialPortConfiguration,sampleInformation);
    Sleep(700);
    readOverlapped=readFromTOC(serialPortConfiguration,8,readBuffer.write);
    while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    delete writeOverlapped;
    delete readOverlapped;
    while(true) {
        memset(&allocation.write,0,sizeof(WORD)*BUFFERSIZE);
        writeOverlapped=sendToTOC(serialPortConfiguration,ACKStruct);
        Sleep(900);

		while(!HasOverlappedIoCompleted(writeOverlapped) &&writing);
		delete writeOverlapped;

        do
		{
        readOverlapped=readFromTOC(serialPortConfiguration,19,allocation.write);
        allocation.size = 7;

		while(!HasOverlappedIoCompleted(readOverlapped)&&writing);
		delete readOverlapped;
		Sleep(200);
		}
		while(inQueue(serialPortConfiguration,1));
        if(allocation.write[1]==23 && allocation.write[13] ==0) {
            
            break;
        }
     

        Sleep(400);
    }

    //while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    //delete writeOverlapped;
    //delete readOverlapped;

    writeOverlapped=sendToTOC(serialPortConfiguration,sampleInformation2);
    Sleep(500);
    readOverlapped=readFromTOC(serialPortConfiguration,8,readBuffer.write);
    while((!HasOverlappedIoCompleted(writeOverlapped) || !HasOverlappedIoCompleted(readOverlapped))||writing);
    delete writeOverlapped;
    delete readOverlapped;
    cout<<"phase 3 done"<<endl;
    int byteID = 0;
	struct TOCData escapeSequence;
	escapeSequence.write[0] = 0x0BA5;
    escapeSequence.write[1] = 0x0AF4;
	escapeSequence.write[2] = 0x2A04;
	escapeSequence.write[3] = 0x00;
    escapeSequence.write[4] = 0x00;
	escapeSequence.write[5] = 0x00;
	escapeSequence.write[6] = 0x3700;
	escapeSequence.write[7] = 0x03A5;
    escapeSequence.write[8] = 0x00FC;
	escapeSequence.write[9] = 0x01;
	escapeSequence.size = 19;
	bool escape = false;
    while(true) {
        memset(&allocation.write,0,sizeof(WORD)*40);
		if(escape)
		{
            writeOverlapped=sendToTOC(serialPortConfiguration,escapeSequence);
			escape = false;

		}
		else
		{
			writeOverlapped=sendToTOC(serialPortConfiguration,ACKStruct);
		}
        Sleep(900);
	
        readOverlapped=readFromTOC(serialPortConfiguration,19,allocation.write);
        allocation.size = 19;
		while(!HasOverlappedIoCompleted(readOverlapped) &&reading);
		delete readOverlapped;
		if(allocation.write[1]==79)
		{
			
			
			sampleData.getSampleResults().addToPeak(allocation.write[14],allocation.write[15]);
		}
        if(allocation.write[1]==23) {
            
            escape = true;
        } 

		if(allocation.write[1]==43)
		{
			break;
		}
		cout<<"concentration so far"<<sampleData.getSampleResults().getAverageConcentration()<<endl;
		Sleep(250);
		
        Sleep(400);
    }

	 while(true) {
        memset(&allocation.write,0,sizeof(WORD)*40);
		if(escape)
		{
            writeOverlapped=sendToTOC(serialPortConfiguration,escapeSequence);
			break;

		}
		else
		{
			writeOverlapped=sendToTOC(serialPortConfiguration,ACKStruct);
		}
        Sleep(900);
	
        readOverlapped=readFromTOC(serialPortConfiguration,19,allocation.write);
        allocation.size = 19;
		while(!HasOverlappedIoCompleted(readOverlapped) &&reading);
		delete readOverlapped;
		if(allocation.write[1]==79)
		{
			
			
			sampleData.getSampleResults().addToPeak(allocation.write[14],allocation.write[15]);
		}
        if(allocation.write[2]==232 && allocation.write[1]==23) {
            
            escape = true;
        } 

		
		Sleep(250);
		
        Sleep(400);
    }


        Sleep(900);
        readOverlapped=readFromTOC(serialPortConfiguration,19,allocation.write);
        cout<<"Area Calculated" <<sampleData.getSampleResults().currentArea()<<endl;
		cout<<"Concentration Calculated"<<sampleData.getSampleResults().currentConcentration()<<endl;
}
Example #16
0
int phase1(){

	/*code extracted from beej guide*/
	int status, sockfd = 0;
	struct addrinfo hints;
	struct addrinfo *res, *p; // will point to the results
	const char *addr = "nunki.usc.edu";
	char s[INET6_ADDRSTRLEN];
	int new_fd = 0;
	struct sockaddr_storage their_addr;
	socklen_t sin_size;
	struct sigaction sa;
	int retVal;
	char buf[256];

	memset(&hints, 0, sizeof hints); // make sure the struct is empty

	hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
	hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
	hints.ai_flags = AI_PASSIVE; // fill in my IP for me

	if ((status = getaddrinfo(addr, HCS_TCP_STATIC_PORT, &hints, &res)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		exit(1);
	}

	/*code extracted from beej guide*/
	p = res;
	void *server_addr;
	struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
	server_addr = &(ipv4->sin_addr);

	/*convert the IP to a string and print it:*/
	inet_ntop(p->ai_family, server_addr, s, sizeof s);
	printf("\nPhase 1: The Health Center Server has port number %s and IP address %s.\n", HCS_TCP_STATIC_PORT, s);

	/*loop through all the results and bind to the first we can*/
	for(p = res; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
			perror("socket");
			continue;
		}
		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("bind");
			continue;
		}
		break; 		/*if we get here, we must have connected successfully*/
	}
	if (p == NULL) {
		/*looped off the end of the list with no successful bind*/
		fprintf(stderr, "failed to bind socket\n");
		exit(2);
	}

	freeaddrinfo(res); 		/*free the linked-list*/

	/*load user.txt file*/
	if((retVal = create_users()) < 0)
		return retVal;

	/*load availabilities.txt file*/
	if((retVal = create_availabilities()) < 0)
		return retVal;

	if(listen(sockfd, BACKLOG) == -1){
		printf("Failed to listen\n");
		return -1;
	}

	/*code extracted from beej guide*/
	sa.sa_handler = sigchld_handler; // reap all dead processes
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1) {
		perror("sigaction");
		exit(1);
	}

	/*code extracted from beej guide*/
	while(1)
	{
		sin_size = sizeof their_addr;
		new_fd = 0;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if (new_fd == -1)
		{
			/*perror("Healthcenterserver Error: accept");*/
			continue;
		}

		inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
		int port = ntohs(((struct sockaddr_in *)&their_addr)->sin_port);
		if (!fork()) // this is the child process
		{
			close(sockfd); // child doesn't need the listener

			int number_of_bytes;
			memset(buf, '0' ,sizeof(buf));
			if ((number_of_bytes = recv(new_fd, buf, MAXBUFLEN-1, 0)) == -1)
			{
				perror("Healthcenterserver Error: when receiving bytes\n");
				exit(1);
			}

			buf[number_of_bytes] = '\0';

			struct users temp_patient;
			retVal = check_authentication((char *)buf, &temp_patient);

			printf("\nPhase 1: The Health Center Server has received request from a patient with username %s and password %s.\n", temp_patient.username, temp_patient.password);

			if(retVal == 1){
				if (send(new_fd, "success", 7, 0) == -1)
				{
					perror("Healthcenterserver Error: while sending\n");
					exit(1);
				}
				printf("\nPhase 1: The Health Center Server sends the response success to patient with username %s.\n", temp_patient.username);

				/*start of phase2 stage1*/
				retVal = phase2(&new_fd, &port, s);

				printf("\nPhase 2: The Health Center Server sends available time slots to patient with username %s.\n", temp_patient.username);

				memset(buf, '\0' ,sizeof(buf));
				if ((number_of_bytes = recv(new_fd, buf, MAXBUFLEN-1, 0)) == -1)
				{
					perror("Healthcenterserver Error: when receiving bytes\n");
					exit(1);
				}

				buf[number_of_bytes] = '\0';

				printf("\nPhase 2: The Health Center Server receives a request for appointment %c from patient with port number %d and username %s.\n", buf[10], port, temp_patient.username);
				/*end of phase2 stage1*/

				/*start of phase2 stage2*/
				char sendBuf[256];
				memset(sendBuf, '\0' ,sizeof(sendBuf));
				retVal = check_availability(buf, sendBuf);

				if(retVal == 1){
					printf("\nPhase 2: The Health Center Server confirms the following appointment %c to patient with username %s.\n", buf[10], temp_patient.username);
					if (send(new_fd, sendBuf, sizeof(sendBuf), 0) == -1)
					{
						perror("Healthcenterserver Error: while sending\n");
						exit(1);
					}
				}
				else{
					printf("\nPhase 2: The Health Center Server rejects the following appointment %c to patient with username %s.\n", buf[10], temp_patient.username);
					if (send(new_fd, "notavailable", 12, 0) == -1)
					{
						perror("Healthcenterserver Error: while sending\n");
						exit(1);
					}
				}
				memset(sendBuf, '\0' ,sizeof(sendBuf));
				/*end of phase2 stage2*/
			}
			else{
				if (send(new_fd, "failure", 7, 0) == -1)
				{
					perror("Healthcenterserver Error: while sending\n");
					exit(1);
				}
				printf("\nPhase 1: The Health Center Server sends the response failure to patient with username %s.\n", temp_patient.username);
			}
			close(new_fd);
			exit(0);
		}
		else
			close(new_fd);  /*parent doesn't need this*/
		/*while(wait(NULL) > 0);*/
	}
	while(wait(NULL) > 0);
	close(sockfd);
	return 0;
}
Example #17
0
/****************************************************************
 * Name    : main                                               *
 * Function: main function                                      *
 * Input   : argc, argv                                         *
 * Output  : void                                               *
 *           The usage of the rock program should be of the     *
 *           form:                                              *
 *             chameleon N fileName stopClusterNO               *
 *           Each parameter's meanning is :                     *
 *           chameleon -- program's name                        *
 *           int N    -- how many data points does the file has *
 *           string fileName -- indicate the data file          *
 *                              name which                      *
 *                               contains all the data vectors. *
 *           int stopClusterNO -- number of remaining clusters  *
 *                                at the end of clustering.     *
 ****************************************************************/
int main(int argc, char * argv[]) {
  struct node * left;
  struct node * right;

  int i;

  if(gettimeofday(&time_start, NULL)<0)
    {
      printf("time error \n");
      return -1;
    }

  printf("ALPHA is %f \n", ALPHA);

  /* parse the command line */
 if (parsingInput(argc, argv)<0)
   {
     return -1;
   }

  /* read in data file */
 if ( readData()<0 )
   {
      fclose(fp);
      return -1;
   }

 /* close read in data file */
 fclose(fp);

 /* for debugging purpose */
 /* printData(); */

 /* initialize data structure */
 if ( initialize()<0 )
   {
     return -1;
   }

 /* establish hyperGraph */
 if (establish_hyperGraph()<0)
   {
     return -1;
   }


 /* Now begin partition */
 left = (struct node *)calloc(1, sizeof(struct node));
 if(left == NULL)
   {
     printf("cannot allocate memory for left! \n");
     return -1;
   }
 right = (struct node *)calloc(1, sizeof(struct node));
 if(right == NULL)
   {
     printf("cannot allocate memory for right! \n");
     return -1;
   }

 /* begin partitionning, this is a recursive program */
 if(partition(root, left, right)<0)
   {
     printf("partition error! \n");
     return -1;
   }

 if(phase2()<0)
   {
     printf("phase2 error! \n");
     return -1;
   }

 if(clusterResult()<0)
   {
     fclose(out_fp);
     printf("clusterResult error! \n");
     return -1;
   }
 fclose(out_fp);

 for(i=0; i<groupIndex; i++)
   {
     free(groups[i]);
     groups[i] = NULL;
   }

 if(gettimeofday(&time_end, NULL)<0){
   printf("time error \n");
   return -1;
 }
 
  /* Now compute the time for sequential sorting */
 time_period = compute_time(time_start, time_end);
  
 printf("time spend is : %d \n", time_period);

 return 1;
}/* end main */