Ejemplo n.º 1
0
 Vector3D operator * (float multiplier)
 {
     Vector3D other(*this);
     other.scale(multiplier);
     return other;
 }
Ejemplo n.º 2
0
void
ArpackSolver::myMv(int n, double *v, double *result)
{
  Vector x(v, n);
  Vector y(result,n);
    
  bool mDiagonal = theArpackSOE->mDiagonal;

  if (mDiagonal == true) {

    int Msize = theArpackSOE->Msize;
    double *M = theArpackSOE->M;

    /* for output
    DataFileStream dataStream("M.txt");
    dataStream.open();
    for (int i=0; i<n; i++)
      dataStream << M[i] << endln;
    dataStream.close();
    */

    if (n <= Msize) {
      for (int i=0; i<n; i++)
	result[i] = M[i]*v[i];
    } else {
      opserr << "ArpackSolver::myMv() n > Msize!\n";
      return;
    }

  } else {

    y.Zero();

    AnalysisModel *theAnalysisModel = theArpackSOE->theModel;
    
    // loop over the FE_Elements
    FE_Element *elePtr;
    FE_EleIter &theEles = theAnalysisModel->getFEs();    
    while((elePtr = theEles()) != 0) {
      const Vector &b = elePtr->getM_Force(x, 1.0);
      y.Assemble(b, elePtr->getID(), 1.0);

    }

    // loop over the DOF_Groups
    DOF_Group *dofPtr;
    DOF_GrpIter &theDofs = theAnalysisModel->getDOFs();
    while ((dofPtr = theDofs()) != 0) {
      const Vector &a = dofPtr->getM_Force(x,1.0);      
      y.Assemble(a, dofPtr->getID(), 1.0);
    }
  }

  // if paallel we have to merge the results
  int processID = theArpackSOE->processID;
  if (processID != -1) {
    Channel **theChannels = theArpackSOE->theChannels;
    int numChannels = theArpackSOE->numChannels;
    if (processID != 0) {
      theChannels[0]->sendVector(0, 0, y);
      theChannels[0]->recvVector(0, 0, y);
    } else {
      Vector other(workArea, n);
      // recv contribution from remote & add
      for (int i=0; i<numChannels; i++) {
	theChannels[i]->recvVector(0,0,other);
	y += other;
      }
      // send result back
      for (int i=0; i<numChannels; i++) {
	theChannels[i]->sendVector(0,0,y);
      }
    }
  }
}
Ejemplo n.º 3
0
 INTERNAL_CATCH_INLINE TestCase TestCase::withName( std::string const& _newName ) const {
     TestCase other( *this );
     other.name = _newName;
     return other;
 }
Ejemplo n.º 4
0
 constant_iterator operator+(Difference off) const
 {
    constant_iterator other(*this);
    other.advance(off);
    return other;
 }
Ejemplo n.º 5
0
int _tmain(int argc, _TCHAR* argv[])
{

	FILE *fpin,*fpout,*fperror;
	int c;
	//判断字母的值
	int is_what;
	/**
	存放字符串的 变量 
	*/
	//    char character;    
	char ch[17];
	ch[0]='\0';
	char result[20];
	int i=0;
	int ch_index=0;
	int len;
	int is_end=0;
	//用来计算行号
	int line_number=0;
	/**
	打开输入输出文件 
	*/
	char fpin_name[80],fpout_name[80],fperror_name[80];
	printf("请输入要进行词法分析的文件名:\n");
	scanf("%s",fpin_name);
	error_out_name(fpin_name, fpout_name, fperror_name);
	fpin=fopen(fpin_name,"r");
	fpout=fopen(fpout_name,"w");
	fperror=fopen(fperror_name,"w");
	if(fpin==NULL||fpout==NULL||fperror==NULL)
	{
		puts("打开文件失败");
		puts("\n");
		puts("请确认输入的文件名是否合法,文件是否真实存在!");
		exit(0);
	}
	else{
		while((c=getc(fpin))!=END	)
		{
			is_what=word_type(c);
			if(is_what==BLACK)continue;
			//进行字母数字的判断

			if(is_what==LETTER)
			{
				//判断字符的长度  不能超过16 
				len=strlen(ch);
				if(len>=16){
					more_than_16(line_number, fpin, fperror);
				}
				ch_index=0;
				ch[ch_index++]=c;//加入字符串
				ch[ch_index]='\0'; //加入结束符
				while((c=getc(fpin))!=ONECHAR)
				{
					//判断字符的长度  不能超过16 
					len=strlen(ch);
					if(len>=16){
						more_than_16(line_number, fpin, fperror);
						break; 
					}

					//-1的时候  是行的末尾
					is_what=word_type(c);
					if(is_what==BLACK||is_what==OTHER){
						//如果是空格   那么一个字母的字符串结束
						//把result写到文件里面去
						to_result(ch,result,fpout,ONECHAR);
						break;//停止这一次的运行 
					}
					else  if(is_what==END){
						is_end=1;
						to_result(ch,result,fpout,END);
						break;//停止这一次的运行 
					} 
					//写到ch里面
					else{
						ch[ch_index]=c;

						ch[++ch_index]='\0';
					}
				}
			}
			//如果当前的是空格或者是回车  或者是换行  那么结束这次
			if(is_what==BLACK)continue;
			//如果当前的是其他的字符
			if(is_what==OTHER){
				ch[0]=c;
				ch[1]='\0';
				int sign=c;
				//不是文件的末尾
				other( ch, result, sign, fpout,fpin,fperror, OTHER);
				//查看是不是文件的末尾操作
				if((c=getc(fpin))!=-1)
				{
					is_what=word_type(c);
					//判断读取的字符  是不是为'\n' ' '
					if(is_what!=BLACK){
						//文件指针回退
						int index=ftell(fpin);
						fseek(fpin,index-1,0);
						is_what=BLACK;//重新开始读取
					}

				}
				else{
					endfile( result, fpout);
					break;
				}
			}
			if(is_what==NUMBER){
				//如果读取到的是数字的话
				ch_index=0;
				ch[ch_index]=c;
				ch[++ch_index]='\0';
				while((c=getc(fpin))!=-1){
					is_what=word_type(c);
					if(is_what==LETTER)
					{
						number_error(line_number, fpin, fperror);
						break;
					}
					else   if(is_what==BLACK||is_what==OTHER){
						//做一些数据的处理  读取空格或者是其他的字符
						to_result(ch,result,fpout,ONECHAR);
						if(is_what!=BLACK){
							//文件指针回退
							int index=ftell(fpin);
							fseek(fpin,index-1,0);
						}				
						break;
					}
					else if(is_what==NUMBER){
						ch[ch_index]=c;
						ch[++ch_index]='\0';
					}
				}
				if(c==END){
					is_end=1;
					toNextLine(result, fpout);

					endfile( result, fpout);

					break;
				}
			}
			//初始化这两个数组
			ch[0]='\0';
			result[0]='\0';
		}
		//进行文件末尾的
	}
	if(is_end==0){
		endfile( result, fpout);
	}
	//关闭打开的流    释放资源 
	fclose(fpin);
	fclose(fpout);
	fclose(fperror);
	return 0;
}
Ejemplo n.º 6
0
bool
Warp::accelerated_cairorender(Context context, cairo_t *cr, int quality, const RendDesc &renddesc_, ProgressCallback *cb)const
{
	Point src_tl=param_src_tl.get(Point());
	Point src_br=param_src_br.get(Point());
	Point dest_tl=param_dest_tl.get(Point());
	Point dest_tr=param_dest_tr.get(Point());
	Point dest_bl=param_dest_bl.get(Point());
	Point dest_br=param_dest_br.get(Point());
	Real horizon=param_horizon.get(Real());
	bool clip=param_clip.get(bool());

	SuperCallback stageone(cb,0,9000,10000);
	SuperCallback stagetwo(cb,9000,10000,10000);
	
	
	RendDesc renddesc(renddesc_);
	// Untransform the render desc
	if(!cairo_renddesc_untransform(cr, renddesc))
		return false;
	
	Real pw=(renddesc.get_w())/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
	Real ph=(renddesc.get_h())/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
	
	if(cb && !cb->amount_complete(0,10000))
		return false;
	
	Point tl(renddesc.get_tl());
	Point br(renddesc.get_br());
	
	Rect bounding_rect;
	
	Rect render_rect(tl,br);
	Rect clip_rect(Rect::full_plane());
	Rect dest_rect(dest_tl,dest_br); dest_rect.expand(dest_tr).expand(dest_bl);
	
	Real zoom_factor(1.0);
	
	// Quick exclusion clip, if necessary
	if(clip && !intersect(render_rect,dest_rect))
	{
		cairo_save(cr);
		cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
		cairo_paint(cr);
		cairo_restore(cr);
		return true;
	}
	
	{
		Rect other(render_rect);
		if(clip)
			other&=dest_rect;
		
		Point min(other.get_min());
		Point max(other.get_max());
		
		bool init_point_set=false;
		
		// Point trans_point[4];
		Point p;
		// Real trans_z[4];
		Real z,minz(10000000000000.0f),maxz(0);
		
		//! \todo checking the 4 corners for 0<=z<horizon*2 and using
		//! only 4 corners which satisfy this condition isn't the
		//! right thing to do.  It's possible that none of the 4
		//! corners fall within that range, and yet content of the
		//! tile does.
		p=transform_forward(min);
		z=transform_backward_z(p);
		if(z>0 && z<horizon*2)
		{
			if(init_point_set)
				bounding_rect.expand(p);
			else
				bounding_rect=Rect(p);
			init_point_set=true;
			maxz=std::max(maxz,z);
			minz=std::min(minz,z);
		}
		
		p=transform_forward(max);
		z=transform_backward_z(p);
		if(z>0 && z<horizon*2)
		{
			if(init_point_set)
				bounding_rect.expand(p);
			else
				bounding_rect=Rect(p);
			init_point_set=true;
			maxz=std::max(maxz,z);
			minz=std::min(minz,z);
		}
		
		swap(min[1],max[1]);
		
		p=transform_forward(min);
		z=transform_backward_z(p);
		if(z>0 && z<horizon*2)
		{
			if(init_point_set)
				bounding_rect.expand(p);
			else
				bounding_rect=Rect(p);
			init_point_set=true;
			maxz=std::max(maxz,z);
			minz=std::min(minz,z);
		}
		
		p=transform_forward(max);
		z=transform_backward_z(p);
		if(z>0 && z<horizon*2)
		{
			if(init_point_set)
				bounding_rect.expand(p);
			else
				bounding_rect=Rect(p);
			init_point_set=true;
			maxz=std::max(maxz,z);
			minz=std::min(minz,z);
		}
		
		if(!init_point_set)
		{
			cairo_save(cr);
			cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
			cairo_paint(cr);
			cairo_restore(cr);
			return true;
		}
		zoom_factor=(1+(maxz-minz));
		
	}
	
#ifdef ACCEL_WARP_IS_BROKEN
	return Layer::accelerated_cairorender(context,cr,quality,renddesc, cb);
#else
	
	/*swap(tl[1],br[1]);
	 bounding_rect
	 .expand(transform_forward(tl))
	 .expand(transform_forward(br))
	 ;
	 swap(tl[1],br[1]);*/
	
	//synfig::warning("given window: [%f,%f]-[%f,%f] %dx%d",tl[0],tl[1],br[0],br[1],renddesc.get_w(),renddesc.get_h());
	//synfig::warning("Projected: [%f,%f]-[%f,%f]",bounding_rect.get_min()[0],bounding_rect.get_min()[1],bounding_rect.get_max()[0],bounding_rect.get_max()[1]);
	
	// If we are clipping, then go ahead and clip to the
	// source rectangle
	if(clip)
		clip_rect&=Rect(src_tl,src_br);
	
	// Bound ourselves to the bounding rectangle of
	// what is under us
	clip_rect&=context.get_full_bounding_rect();//.expand_x(abs(zoom_factor/pw)).expand_y(abs(zoom_factor/ph));
	
	bounding_rect&=clip_rect;
	
	Point min_point(bounding_rect.get_min());
	Point max_point(bounding_rect.get_max());
	
	// we're going to divide by the difference of these pairs soon;
	// if they're the same, we'll be dividing by zero, and we don't
	// want to do that!
	// \todo what should we do in this case?
	if (min_point[0] == max_point[0]) max_point[0] += 0.001;
	if (min_point[1] == max_point[1]) max_point[1] += 0.001;
	
	if(tl[0]>br[0])
	{
		tl[0]=max_point[0];
		br[0]=min_point[0];
	}
	else
	{
		br[0]=max_point[0];
		tl[0]=min_point[0];
	}
	if(tl[1]>br[1])
	{
		tl[1]=max_point[1];
		br[1]=min_point[1];
	}
	else
	{
		br[1]=max_point[1];
		tl[1]=min_point[1];
	}
	
	const int tmp_d(max(renddesc.get_w(),renddesc.get_h()));
	Real src_pw=(tmp_d*zoom_factor)/(br[0]-tl[0]);
	Real src_ph=(tmp_d*zoom_factor)/(br[1]-tl[1]);
	
	
	RendDesc desc(renddesc);
	desc.clear_flags();
	//desc.set_flags(RendDesc::PX_ASPECT);
	desc.set_tl(tl);
	desc.set_br(br);
	desc.set_wh(ceil_to_int(src_pw*(br[0]-tl[0])),ceil_to_int(src_ph*(br[1]-tl[1])));
	
	//synfig::warning("surface to render: [%f,%f]-[%f,%f] %dx%d",desc.get_tl()[0],desc.get_tl()[1],desc.get_br()[0],desc.get_br()[1],desc.get_w(),desc.get_h());
	if(desc.get_w()==0 && desc.get_h()==0)
	{
		cairo_save(cr);
		cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
		cairo_paint(cr);
		cairo_restore(cr);
		return true;
	}
	
	// Recalculate the pixel widths for the src renddesc
	src_pw=(desc.get_w())/(desc.get_br()[0]-desc.get_tl()[0]);
	src_ph=(desc.get_h())/(desc.get_br()[1]-desc.get_tl()[1]);
	
	cairo_surface_t* source=cairo_surface_create_similar(cairo_get_target(cr), CAIRO_CONTENT_COLOR_ALPHA, desc.get_w(),desc.get_h());
	cairo_surface_t* surface=cairo_surface_create_similar(cairo_get_target(cr), CAIRO_CONTENT_COLOR_ALPHA,renddesc.get_w(), renddesc.get_h());
	cairo_t* subcr=cairo_create(source);
	cairo_scale(subcr, 1/desc.get_pw(), 1/desc.get_ph());
	cairo_translate(subcr, -desc.get_tl()[0], -desc.get_tl()[1]);

	if(!context.accelerated_cairorender(subcr,quality,desc,&stageone))
		return false;
	
	cairo_destroy(subcr);
		
	int surfacew, surfaceh, sourcew, sourceh;
	
	CairoSurface csurface(surface);
	CairoSurface csource(source);
	
	csurface.map_cairo_image();
	csource.map_cairo_image();
	
	surfacew=csurface.get_w();
	surfaceh=csurface.get_h();
	sourcew=csource.get_w();
	sourceh=csource.get_h();
	
	CairoSurface::pen pen(csurface.begin());
	
	// Do the warp
	{
		int x,y;
		float u,v;
		Point point,tmp;
		for(y=0,point[1]=renddesc.get_tl()[1];y<surfaceh;y++,pen.inc_y(),pen.dec_x(x),point[1]+=1.0/ph)
		{
			for(x=0,point[0]=renddesc.get_tl()[0];x<surfacew;x++,pen.inc_x(),point[0]+=1.0/pw)
			{
				tmp=transform_forward(point);
				const float z(transform_backward_z(tmp));
				if(!clip_rect.is_inside(tmp) || !(z>0 && z<horizon))
				{
					csurface[y][x]=Color::alpha();
					continue;
				}
				
				u=(tmp[0]-tl[0])*src_pw;
				v=(tmp[1]-tl[1])*src_ph;
				
				if(u<0 || v<0 || u>=sourcew || v>=sourceh || isnan(u) || isnan(v))
					csurface[y][x]=context.get_cairocolor(tmp);
				else
				{
					// CUBIC
					if(quality<=4)
						csurface[y][x]=csource.cubic_sample_cooked(u,v);
					// INTEPOLATION_LINEAR
					else if(quality<=6)
						csurface[y][x]=csource.linear_sample_cooked(u,v);
					else
						// NEAREST_NEIGHBOR
						csurface[y][x]=csource[floor_to_int(v)][floor_to_int(u)];
				}
			}
			if((y&31)==0 && cb)
			{
				if(!stagetwo.amount_complete(y,surfaceh))
					return false;
			}
		}
	}
	
#endif
	
	if(cb && !cb->amount_complete(10000,10000)) return false;
	
	csurface.unmap_cairo_image();
	csource.unmap_cairo_image();
	cairo_surface_destroy(source);
	
	cairo_save(cr);
	
	cairo_translate(cr, renddesc.get_tl()[0], renddesc.get_tl()[1]);
	cairo_scale(cr, renddesc.get_pw(), renddesc.get_ph());
	cairo_set_source_surface(cr, surface, 0, 0);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_paint(cr);
	
	cairo_restore(cr);
	
	cairo_surface_destroy(surface);
	return true;
}
Ejemplo n.º 7
0
 this_type operator+(Difference off) const
 {
    this_type other(*this);
    other.advance(off);
    return other;
 }
Ejemplo n.º 8
0
 transform_iterator operator+(typename std::iterator_traits<Iterator>::difference_type off) const
 {
     transform_iterator other(*this);
     other.advance(off);
     return other;
 }
Ejemplo n.º 9
0
/**
 * Called only by render_picture().
 */
static bool render_picture_internal(const SkString& inputPath, const SkString* outputDir,
                                    sk_tools::PictureRenderer& renderer,
                                    SkBitmap** out) {
    SkString inputFilename;
    sk_tools::get_basename(&inputFilename, inputPath);
    SkString outputDirString;
    if (NULL != outputDir && outputDir->size() > 0 && !FLAGS_writeEncodedImages) {
        outputDirString.set(*outputDir);
    }

    SkFILEStream inputStream;
    inputStream.setPath(inputPath.c_str());
    if (!inputStream.isValid()) {
        SkDebugf("Could not open file %s\n", inputPath.c_str());
        return false;
    }

    SkPicture::InstallPixelRefProc proc;
    if (FLAGS_deferImageDecoding) {
        proc = &sk_tools::LazyDecodeBitmap;
    } else if (FLAGS_writeEncodedImages) {
        SkASSERT(!FLAGS_writePath.isEmpty());
        reset_image_file_base_name(inputFilename);
        proc = &write_image_to_file;
    } else {
        proc = &SkImageDecoder::DecodeMemory;
    }

    SkDebugf("deserializing... %s\n", inputPath.c_str());

    SkPicture* picture = SkPicture::CreateFromStream(&inputStream, proc);

    if (NULL == picture) {
        SkDebugf("Could not read an SkPicture from %s\n", inputPath.c_str());
        return false;
    }

    while (FLAGS_bench_record) {
        SkPictureRecorder recorder;
        picture->draw(recorder.beginRecording(picture->width(), picture->height(), NULL, 0));
        SkAutoTUnref<SkPicture> other(recorder.endRecording());
    }

    for (int i = 0; i < FLAGS_clone; ++i) {
        SkPicture* clone = picture->clone();
        SkDELETE(picture);
        picture = clone;
    }

    SkDebugf("drawing... [%i %i] %s\n", picture->width(), picture->height(),
             inputPath.c_str());

    renderer.init(picture, &outputDirString, &inputFilename, FLAGS_writeChecksumBasedFilenames);

    if (FLAGS_preprocess) {
        if (NULL != renderer.getCanvas()) {
            renderer.getCanvas()->EXPERIMENTAL_optimize(renderer.getPicture());
        }
    }

    renderer.setup();

    bool success = renderer.render(out);
    if (!success) {
        SkDebugf("Failed to render %s\n", inputFilename.c_str());
    }

    renderer.end();

    SkDELETE(picture);
    return success;
}
Ejemplo n.º 10
0
// Perform a Monte-Carlo Tree Search
void g3_mcts(const struct connect4 *game, g3_MCnode *root) {
    // For concision
    const char me = game->whoseTurn;
    //const int winCondition = me == PLAYERONE ? X_WINS : O_WINS;

    // Memory to do scratch-work in
    struct connect4 tempGame;

    g3_MCnode *nodeStack[g3_NUM_MOVES];
    int moveStack[g3_NUM_MOVES];
    int s = 0; // Stack pointer

    static int runs = 0;
    int numSims = g3_max(g3_SIMULATIONS / 26 * (26 - runs), g3_FAST_SIMULATIONS);
    runs++;

    //puts("g");
    //printf("Running %d simulations\n", numSims);

    int t; // current number of simulations
    for (t = 0; t < numSims; t++) {
        // Make a fresh copy of the game
        memcpy(&tempGame, game, sizeof(struct connect4));

        // Temp pointer to the current node in the tree
        g3_MCnode *current = root;

        // Reset stack pointer
        s = 0;

        // Play moves until the hypothetical game ends
        char winner = 0;
        while (winner == 0 && g3_movesAvailable(&tempGame)) {
            if (s >= 26)
                puts("Something's gone horribly wrong.");

            double probabilities[NUM_COLS];
            //const char currPlayer = tempGame.whoseTurn;

            // Assume both players will go for special cases
            int nextMove = g3_handleSpecialCase(&tempGame);
            if (nextMove == -1) {
                // Weight current player's path based on past success
                if (tempGame.whoseTurn == me)
                    g3_computeWeightedProbs(probabilities, current->scores, t);
                    // If there was no immediate win, give all opponent paths an equal chance
                else
                    g3_computeUniformProbs(probabilities);

                // Use probabilities to select the next node
                while (not_valid(&tempGame, nextMove))
                    nextMove = g3_chooseMove(probabilities);
            }

            // Push the move onto the stack if this is our move
            if (tempGame.whoseTurn == me) {
                //printf("Stack pointer at %d\n", s);
                //print_board(&tempGame);
                moveStack[s] = nextMove;
                nodeStack[s++] = current;
            }

            // If the move would result in a winner or the game is CATS, break the loop
            int validRow = get_row(&tempGame, nextMove);
            if (g3_is3Win(&tempGame, validRow, nextMove, tempGame.whoseTurn)) {
                winner = tempGame.whoseTurn;
            } else {
                // Otherwise, play the move and keep playing
                tempGame.board[get_row(&tempGame, nextMove)][nextMove] = tempGame.whoseTurn;
                tempGame.whoseTurn = other(tempGame.whoseTurn);
                current = g3_getNextNode(current, nextMove);
            }
        }

        // Determine if we won
        int w = (winner == me);
        // Backprop the result of the game
        g3_backpropogate(nodeStack, moveStack, s - 1, w);
    }

    return;
}
Ejemplo n.º 11
0
int g3_handleSpecialCase(const struct connect4 *game) {
    // Play the center if there are no other moves
    if (!not_valid(game, g3_CENTER)) {
        //isCrazy checks if there are moves in other columns;
        if (!g3_isCrazy(game)) return g3_CENTER;
    }

    //Continue to checking for 3wins and 2wins if you shouldn't play the center

    int col;
    int didTheyWin = -1;

    //determines who is who for each of the pieces based on whose turn it is
    char us = game->whoseTurn;

    //they have to be the opposite of our piece, so set them to the opposite of us
    char them = other(us);

    //Check all of the columns for if we win by playing in the column or if we block their win
    for (col = 0; col < NUM_COLS; col++) {
        //finds the row you will be playing in if you select that column
        int validRow = get_row(game, col);
        //If you can win there, play there!
        if (g3_is3Win(game, validRow, col, us)) {
            return col;
        }
        //Otherwise, keep track of where to block the opponent if they have a 3win
        if (g3_is3Win(game, validRow, col, them)) didTheyWin = col;
    }

    //If you found a column you have to block, block it.
    if (didTheyWin != -1) return didTheyWin;

    //If there are no 3wins, check for 2wins

    int enemy2Wins[NUM_COLS];
    memset(enemy2Wins, 0, sizeof(enemy2Wins));

    //Check in each col if there is a 2win
    for (col = 0; col < NUM_COLS; col++) {
        int validRow = get_row(game, col);

        //if you have a 2win and you don't cause a 3win for the opponent, you should play there
        if (g3_is2Win(game, validRow, col, us)) {
            if (g3_isSafe(game, validRow, col, us)) {
                return col;
            }
        }
/*
		//If your opponent has a 2win and its safe to block them, do it
		if (g3_is2Win(game, validRow, col, them) && g3_isSafe(game, validRow, col, us)) {
			enemy2Wins[col] = 1;
		}
*/
    }

/*
    for (col = 0; col < NUM_COLS; col++) {
        if (enemy2Wins[col] ==  1)
            return g3_fastMove(game, enemy2Wins);
    }
*/
    return -1;
}
Ejemplo n.º 12
0
int32_t PluralFormat::findSubMessage(const MessagePattern& pattern, int32_t partIndex,
                                     const PluralSelector& selector, void *context,
                                     double number, UErrorCode& ec) {
    if (U_FAILURE(ec)) {
        return 0;
    }
    int32_t count=pattern.countParts();
    double offset;
    const MessagePattern::Part* part=&pattern.getPart(partIndex);
    if (MessagePattern::Part::hasNumericValue(part->getType())) {
        offset=pattern.getNumericValue(*part);
        ++partIndex;
    } else {
        offset=0;
    }
    // The keyword is empty until we need to match against a non-explicit, not-"other" value.
    // Then we get the keyword from the selector.
    // (In other words, we never call the selector if we match against an explicit value,
    // or if the only non-explicit keyword is "other".)
    UnicodeString keyword;
    UnicodeString other(FALSE, OTHER_STRING, 5);
    // When we find a match, we set msgStart>0 and also set this boolean to true
    // to avoid matching the keyword again (duplicates are allowed)
    // while we continue to look for an explicit-value match.
    UBool haveKeywordMatch=FALSE;
    // msgStart is 0 until we find any appropriate sub-message.
    // We remember the first "other" sub-message if we have not seen any
    // appropriate sub-message before.
    // We remember the first matching-keyword sub-message if we have not seen
    // one of those before.
    // (The parser allows [does not check for] duplicate keywords.
    // We just have to make sure to take the first one.)
    // We avoid matching the keyword twice by also setting haveKeywordMatch=true
    // at the first keyword match.
    // We keep going until we find an explicit-value match or reach the end of the plural style.
    int32_t msgStart=0;
    // Iterate over (ARG_SELECTOR [ARG_INT|ARG_DOUBLE] message) tuples
    // until ARG_LIMIT or end of plural-only pattern.
    do {
        part=&pattern.getPart(partIndex++);
        const UMessagePatternPartType type = part->getType();
        if(type==UMSGPAT_PART_TYPE_ARG_LIMIT) {
            break;
        }
        U_ASSERT (type==UMSGPAT_PART_TYPE_ARG_SELECTOR);
        // part is an ARG_SELECTOR followed by an optional explicit value, and then a message
        if(MessagePattern::Part::hasNumericValue(pattern.getPartType(partIndex))) {
            // explicit value like "=2"
            part=&pattern.getPart(partIndex++);
            if(number==pattern.getNumericValue(*part)) {
                // matches explicit value
                return partIndex;
            }
        } else if(!haveKeywordMatch) {
            // plural keyword like "few" or "other"
            // Compare "other" first and call the selector if this is not "other".
            if(pattern.partSubstringMatches(*part, other)) {
                if(msgStart==0) {
                    msgStart=partIndex;
                    if(0 == keyword.compare(other)) {
                        // This is the first "other" sub-message,
                        // and the selected keyword is also "other".
                        // Do not match "other" again.
                        haveKeywordMatch=TRUE;
                    }
                }
            } else {
                if(keyword.isEmpty()) {
                    keyword=selector.select(context, number-offset, ec);
                    if(msgStart!=0 && (0 == keyword.compare(other))) {
                        // We have already seen an "other" sub-message.
                        // Do not match "other" again.
                        haveKeywordMatch=TRUE;
                        // Skip keyword matching but do getLimitPartIndex().
                    }
                }
                if(!haveKeywordMatch && pattern.partSubstringMatches(*part, keyword)) {
                    // keyword matches
                    msgStart=partIndex;
                    // Do not match this keyword again.
                    haveKeywordMatch=TRUE;
                }
            }
        }
        partIndex=pattern.getLimitPartIndex(partIndex);
    } while(++partIndex<count);
    return msgStart;
}
Ejemplo n.º 13
0
BeatsPointer BeatGrid::clone() const {
    QMutexLocker locker(&m_mutex);
    BeatsPointer other(new BeatGrid(*this));
    return other;
}
Ejemplo n.º 14
0
/** Returns the amount of prestige added
 *
 * \note Assumes that the Mis Structure is Loaded
 */
int PrestCheck(char plr)
{
    int i, total = 0;
    char prg, tm;

    prg = Mis.mEq;

    for (i = 0; i < 5; i++) { // Sum all first/second Nation Bonuses
        tm = Mis.PCat[i];

        if (tm != -1 && Data->Prestige[tm].Goal[plr] == 0) { // First Mission Bonus
            if (Data->Prestige[tm].Goal[other(plr)] == 0 && tm < 27) {
                total += Data->Prestige[tm].Add[0];    // you're first
            } else {
                total += Data->Prestige[tm].Add[1];    // you're second
            }
        }
    }

    if (Mis.Doc == 1 && Data->Prestige[Prestige_MannedDocking].Goal[plr] == 0) {
        if (Data->Prestige[Prestige_MannedDocking].Goal[other(plr)] == 0) {
            total += Data->Prestige[Prestige_MannedDocking].Add[0];    // you're first
        } else {
            total += Data->Prestige[Prestige_MannedDocking].Add[1];    // you're second
        }
    }

    if (Mis.EVA == 1 && Data->Prestige[Prestige_Spacewalk].Goal[plr] == 0) {
        if (Data->Prestige[Prestige_Spacewalk].Goal[other(plr)] == 0) {
            total += Data->Prestige[Prestige_Spacewalk].Add[0];    // you're first
        } else {
            total += Data->Prestige[Prestige_Spacewalk].Add[1];    // you're second
        }
    }

    if (Mis.Days > 1 && Data->P[plr].DurationLevel < Mis.Days) {
        if (Mis.Days == 6 && Data->Prestige[Prestige_Duration_Calc - Mis.Days].Goal[plr] == 0) {
            total += Data->Prestige[Prestige_Duration_Calc - Mis.Days].Add[0];
        } else if (Mis.Days == 5 && Data->Prestige[Prestige_Duration_Calc - Mis.Days].Goal[plr] == 0) {
            total += Data->Prestige[Prestige_Duration_Calc - Mis.Days].Add[0];
        } else if (Mis.Days == 4 && Data->Prestige[Prestige_Duration_Calc - Mis.Days].Goal[plr] == 0) {
            total += Data->Prestige[Prestige_Duration_Calc - Mis.Days].Add[0];
        } else if (Mis.Days == 3 && Data->Prestige[Prestige_Duration_Calc - Mis.Days].Goal[plr] == 0) {
            total += Data->Prestige[Prestige_Duration_Calc - Mis.Days].Add[0];
        } else if (Mis.Days == 2 && Data->Prestige[Prestige_Duration_Calc - Mis.Days].Goal[plr] == 0) {
            total += Data->Prestige[Prestige_Duration_Calc - Mis.Days].Add[0];
        }
    }

    // Hardware Checks
    if (Mis.Days > 1 && Data->Prestige[Prestige_Duration_B + prg].Goal[plr] == 0) {
        if (Data->Prestige[Prestige_Duration_B + prg].Goal[other(plr)] == 0) {
            total += Data->Prestige[Prestige_Duration_B + prg].Add[0];    // you're first
        } else {
            total += Data->Prestige[Prestige_Duration_B + prg].Add[1];    // you're second
        }
    }

    if (total != 0) {
        return total;
    }

    // Other mission bonus

    // Sum all additional Mission Bonuses
    for (i = 0; i < 5; i++) {
        if (Mis.PCat[i] != -1) {
            total += Data->Prestige[Mis.PCat[i]].Add[2];
        }
    }

    if (Mis.Doc == 1 && Data->Prestige[Prestige_MannedDocking].Goal[plr] == 0) {
        total += Data->Prestige[Prestige_MannedDocking].Add[2];
    }

    if (Mis.EVA == 1 && Data->Prestige[Prestige_Spacewalk].Goal[plr] == 0) {
        total += Data->Prestige[Prestige_Spacewalk].Add[2];
    }

    return total;
}
TEST( TestVTableHeaderOnlySBOCOWFooable, CopyConstruction_LargeObject )
{
    Fooable fooable = MockLargeFooable();
    Fooable other( fooable );
    test_copies( other, fooable, Mock::other_value );
}
Ejemplo n.º 16
0
int
main(int ac, char *av[])
{
	bool	restore;

	/* Revoke setgid privileges */
	setgid(getgid());

	if (strcmp(av[0], "a.out") == 0) {
		outf = fopen("q", "w");
		setbuf(outf, NULL);
		Debug = TRUE;
	}
	restore = FALSE;
	switch (ac) {
	  case 2:
		rest_f(av[1]);
		restore = TRUE;
	  case 1:
		break;
	  default:
		usage();
		/* NOTREACHED */
	}
	Play = PLAYER;
	initscr();
	delwin(stdscr);
	stdscr = Board = newwin(BOARD_Y, BOARD_X, 0, 0);
	Score = newwin(SCORE_Y, SCORE_X, 0, 40);
	Miles = newwin(MILES_Y, MILES_X, 17, 0);
#ifdef attron
	idlok(Board, TRUE);
	idlok(Score, TRUE);
	idlok(Miles, TRUE);
#endif
	leaveok(Score, TRUE);
	leaveok(Miles, TRUE);
	clearok(curscr, TRUE);
	srandomdev();
	cbreak();
	noecho();
	signal(SIGINT, rub);
	for (;;) {
		if (!restore || (Player[PLAYER].total >= 5000
		    || Player[COMP].total >= 5000)) {
			if (Player[COMP].total < Player[PLAYER].total)
				Player[PLAYER].games++;
			else if (Player[COMP].total > Player[PLAYER].total)
				Player[COMP].games++;
			Player[COMP].total = 0;
			Player[PLAYER].total = 0;
		}
		do {
			if (!restore)
				Handstart = Play = other(Handstart);
			if (!restore || On_exit) {
				shuffle();
				init();
			}
			newboard();
			if (restore)
				mvwaddstr(Score, ERR_Y, ERR_X, Initstr);
			prboard();
			do {
				domove();
				if (Finished)
					newscore();
				prboard();
			} while (!Finished);
			check_more();
			restore = On_exit = FALSE;
		} while (Player[COMP].total < 5000
		    && Player[PLAYER].total < 5000);
	}
}
Ejemplo n.º 17
0
Matrix4x4 Matrix4x4::copy() const {
  Matrix4x4 other(this);
  return other;
}
Ejemplo n.º 18
0
void QualifiedName::setPrefix(const AtomicString& prefix)
{
    QualifiedName other(prefix, localName(), namespaceURI());
    *this = other;
}
Ejemplo n.º 19
0
 default_construct_iterator operator+(Difference off) const
 {
    default_construct_iterator other(*this);
    other.advance(off);
    return other;
 }
int getOptimalModulePlacement( PCB_EDIT_FRAME* aFrame, MODULE* aModule, wxDC* aDC )
{
    int     error = 1;
    wxPoint LastPosOK;
    double  min_cost, curr_cost, Score;
    bool    TstOtherSide;
    DISPLAY_OPTIONS* displ_opts = (DISPLAY_OPTIONS*)aFrame->GetDisplayOptions();
    BOARD*  brd = aFrame->GetBoard();

    aModule->CalculateBoundingBox();

    bool showRats = displ_opts->m_Show_Module_Ratsnest;
    displ_opts->m_Show_Module_Ratsnest = false;

    brd->m_Status_Pcb &= ~RATSNEST_ITEM_LOCAL_OK;
    aFrame->SetMsgPanel( aModule );

    LastPosOK = RoutingMatrix.m_BrdBox.GetOrigin();

    wxPoint     mod_pos = aModule->GetPosition();
    EDA_RECT    fpBBox  = aModule->GetFootprintRect();

    // Move fpBBox to have the footprint position at (0,0)
    fpBBox.Move( -mod_pos );
    wxPoint fpBBoxOrg = fpBBox.GetOrigin();

    // Calculate the limit of the footprint position, relative
    // to the routing matrix area
    wxPoint xylimit = RoutingMatrix.m_BrdBox.GetEnd() - fpBBox.GetEnd();

    wxPoint initialPos = RoutingMatrix.m_BrdBox.GetOrigin() - fpBBoxOrg;

    // Stay on grid.
    initialPos.x    -= initialPos.x % RoutingMatrix.m_GridRouting;
    initialPos.y    -= initialPos.y % RoutingMatrix.m_GridRouting;

    CurrPosition = initialPos;

    // Undraw the current footprint
    aModule->DrawOutlinesWhenMoving( aFrame->GetCanvas(), aDC, wxPoint( 0, 0 ) );

    g_Offset_Module = mod_pos - CurrPosition;

    /* Examine pads, and set TstOtherSide to true if a footprint
     * has at least 1 pad through.
     */
    TstOtherSide = false;

    if( RoutingMatrix.m_RoutingLayersCount > 1 )
    {
        LSET    other( aModule->GetLayer() == B_Cu  ? F_Cu : B_Cu );

        for( D_PAD* pad = aModule->Pads(); pad; pad = pad->Next() )
        {
            if( !( pad->GetLayerSet() & other ).any() )
                continue;

            TstOtherSide = true;
            break;
        }
    }

    // Draw the initial bounding box position
    EDA_COLOR_T color = BROWN;
    fpBBox.SetOrigin( fpBBoxOrg + CurrPosition );
    draw_FootprintRect(aFrame->GetCanvas()->GetClipBox(), aDC, fpBBox, color);

    min_cost = -1.0;
    aFrame->SetStatusText( wxT( "Score ??, pos ??" ) );

    for( ; CurrPosition.x < xylimit.x; CurrPosition.x += RoutingMatrix.m_GridRouting )
    {
        wxYield();

        if( aFrame->GetCanvas()->GetAbortRequest() )
        {
            if( IsOK( aFrame, _( "OK to abort?" ) ) )
            {
                displ_opts->m_Show_Module_Ratsnest = showRats;
                return ESC;
            }
            else
                aFrame->GetCanvas()->SetAbortRequest( false );
        }

        CurrPosition.y = initialPos.y;

        for( ; CurrPosition.y < xylimit.y; CurrPosition.y += RoutingMatrix.m_GridRouting )
        {
            // Erase traces.
            draw_FootprintRect( aFrame->GetCanvas()->GetClipBox(), aDC, fpBBox, color );

            fpBBox.SetOrigin( fpBBoxOrg + CurrPosition );
            g_Offset_Module = mod_pos - CurrPosition;
            int keepOutCost = TstModuleOnBoard( brd, aModule, TstOtherSide );

            // Draw at new place
            color = keepOutCost >= 0 ? BROWN : RED;
            draw_FootprintRect( aFrame->GetCanvas()->GetClipBox(), aDC, fpBBox, color );

            if( keepOutCost >= 0 )    // i.e. if the module can be put here
            {
                error = 0;
                aFrame->build_ratsnest_module( aModule );
                curr_cost   = compute_Ratsnest_PlaceModule( brd );
                Score       = curr_cost + keepOutCost;

                if( (min_cost >= Score ) || (min_cost < 0 ) )
                {
                    LastPosOK   = CurrPosition;
                    min_cost    = Score;
                    wxString msg;
                    msg.Printf( wxT( "Score %g, pos %s, %s" ),
                                min_cost,
                                GetChars( ::CoordinateToString( LastPosOK.x ) ),
                                GetChars( ::CoordinateToString( LastPosOK.y ) ) );
                    aFrame->SetStatusText( msg );
                }
            }
        }
    }

    // erasing the last traces
    GRRect( aFrame->GetCanvas()->GetClipBox(), aDC, fpBBox, 0, BROWN );

    displ_opts->m_Show_Module_Ratsnest = showRats;

    // Regeneration of the modified variable.
    CurrPosition = LastPosOK;

    brd->m_Status_Pcb &= ~( RATSNEST_ITEM_LOCAL_OK | LISTE_PAD_OK );

    MinCout = min_cost;
    return error;
}
Ejemplo n.º 21
0
 this_type operator+(std::ptrdiff_t off) const
 {
    this_type other(*this);
    other.advance(off);
    return other;
 }
 transform_iterator operator+(typename Iterator::difference_type off) const
 {
    transform_iterator other(*this);
    other.advance(off);
    return other;
 }
Ejemplo n.º 23
0
void BattleInput::dealWithCommandInfo(DataStream &in, uchar command, int spot)
{
    switch (command)
    {
    case BC::SendOut:
    {
        bool silent;
        quint8 prevIndex;
        auto poke = mk<ShallowBattlePoke>();
        in >> silent;
        in >> prevIndex;
        in >> *poke;
        output<BattleEnum::SendOut>(spot, prevIndex, &poke, silent);
        break;
    }
    case BC::SendBack:
    {
        bool silent;
        in >> silent;
        output<BattleEnum::SendBack>(spot, silent);
        break;
    }
    case BC::UseAttack:
    {
        qint16 attack;
        bool silent;
        bool special;
        in >> attack >> silent >> special;
        output<BattleEnum::UseAttack>(spot, attack, silent, special);
        break;
    }
    case BC::UsePP:
    {
        qint16 attack;
        quint8 ppsum;
        in >> attack >> ppsum;
        output<BattleEnum::UsePP>(spot, attack, ppsum);
        break;
    }
    case BC::BeginTurn:
    {
        int turn;
        in >> turn;
        output<BattleEnum::Turn>(turn);
        break;
    }
    case BC::ChangeHp:
    {
        quint16 newHp;
        in >> newHp;
        output<BattleEnum::NewHp>(spot, newHp);
        break;
    }
    case BC::Ko:
        output<BattleEnum::Ko>(spot);
        break;
    case BC::Hit:
    {
        quint8 number;
        in >> number;
        output<BattleEnum::Hits>(spot, number);
        break;
    }
    case BC::Effective:
    {
        quint8 eff;
        in >> eff;

        output<BattleEnum::Effectiveness>(spot, eff);
        break;
    }
    case BC::CriticalHit:
        output<BattleEnum::CriticalHit>(spot);
        break;
    case BC::Miss:
    {
        output<BattleEnum::Miss>(spot);
        break;
    }
    case BC::Avoid:
    {
        output<BattleEnum::Avoid>(spot);
        break;
    }
    case BC::StatChange:
    {
        qint8 stat, boost;
        bool silent;
        in >> stat >> boost >> silent;
        output<BattleEnum::StatChange>(spot, stat, boost, silent);
        break;
    }
    case BC::CappedStat:
    {
        qint8 stat;
        bool maxi;
        in >> stat >> maxi;
        output<BattleEnum::CappedStat>(spot, stat, maxi);
        break;
    }
    case BC::StatusChange:
    {
        qint8 status;
        in >> status;
        bool multipleTurns, silent;
        in >> multipleTurns >> silent;

        output<BattleEnum::ClassicStatusChange>(spot, status, multipleTurns, silent);
        break;
    }
    case BC::AbsStatusChange:
    {
        qint8 poke, status;
        in >> poke >> status;

        if (poke < 0 || poke >= 6)
            break;

        output<BattleEnum::AbsoluteStatusChange>(spot,poke,status);
        break;
    }
    case BC::AlreadyStatusMessage:
    {
        quint8 status;
        in >> status;
        output<BattleEnum::AlreadyStatusMessage>(spot,status);
        break;
    }
    case BC::StatusMessage:
    {
        qint8 status;
        in >> status;
        static const QPair<BattleEnum, int> corr[]= {
            QPair<BattleEnum, int>(BattleEnum::StatusFeel, Pokemon::Confused),
            QPair<BattleEnum, int>(BattleEnum::StatusHurt, Pokemon::Confused),
            QPair<BattleEnum, int>(BattleEnum::StatusFree, Pokemon::Confused),
            QPair<BattleEnum, int>(BattleEnum::StatusFeel, Pokemon::Paralysed),
            QPair<BattleEnum, int>(BattleEnum::StatusFeel, Pokemon::Frozen),
            QPair<BattleEnum, int>(BattleEnum::StatusFree, Pokemon::Frozen),
            QPair<BattleEnum, int>(BattleEnum::StatusFeel, Pokemon::Asleep),
            QPair<BattleEnum, int>(BattleEnum::StatusFree, Pokemon::Asleep),
            QPair<BattleEnum, int>(BattleEnum::StatusHurt, Pokemon::Burnt),
            QPair<BattleEnum, int>(BattleEnum::StatusHurt, Pokemon::Poisoned)
        };
        static const int num = sizeof(corr)/sizeof(*corr);

        if (status >= 0 && status < num) {
            switch (corr[status].first) {
            case BattleEnum::StatusFeel:
                output<BattleEnum::StatusFeel>(spot, corr[status].second);
                break;
            case BattleEnum::StatusFree:
                output<BattleEnum::StatusFree>(spot, corr[status].second);
                break;
            case BattleEnum::StatusHurt:
                output<BattleEnum::StatusHurt>(spot, corr[status].second);
            default:
                break;
            }
        }
        break;
    }
    case BC::Failed:
    {
        bool silent;
        in >> silent;
        output<BattleEnum::Fail>(spot, silent);
        break;
    }
    case BC::BattleChat:
    {
        auto message = mk<QString>();
        in >> *message;
        output<BattleEnum::PlayerMessage>(spot, &message, false);
        break;
    }
    case BC::EndMessage:
    {
        auto message = mk<QString>();
        in >> *message;
        output<BattleEnum::PlayerMessage>(spot, &message, true);
        break;
    }
    case BC::Spectating:
    {
        bool come;
        qint32 id;
        in >> come >> id;

        if (conf && conf->isInBattle(id)) {
            if (come) {
                output<BattleEnum::Reconnect>(id);
            } else {
                output<BattleEnum::Disconnect>(id);
            }
        } else {
            if (come) {
                auto name = mk<QString>();
                in >> *name;
                output<BattleEnum::SpectatorEnter>(id, &name);
            } else {
                output<BattleEnum::SpectatorLeave>(id);
            }
        }
        break;
    }
    case BC::SpectatorChat:
    {
        qint32 id;
        auto message = mk<QString>();
        in >> id >> *message;
        output<BattleEnum::SpectatorMessage>(id, &message);
        break;
    }
    case BC::MoveMessage:
    {
        quint16 move=0;
        uchar part=0;
        qint8 type(0), foe(0);
        qint16 other(0);
        auto q = mk<QString>();
        in >> move >> part >> type >> foe >> other >> *q;
        if (move == 57) {
            output<BattleEnum::StartWeather>(spot, part+1, false); //False for non-ability weather
        } else {
            output<BattleEnum::MoveMessage>(spot, move, part, type, foe, other, &q);
        }
        break;
    }
    case BC::NoOpponent:
        output<BattleEnum::NoTargetMessage>(spot);
        break;
    case BC::ItemMessage:
    {
        quint16 item=0;
        uchar part=0;
        qint8 foe = 0;
        qint32 other=0;
        qint16 berry = 0;
        in >> item >> part >> foe >> berry >> other;
        output<BattleEnum::ItemMessage>(spot, item, part, foe, berry, other);
        break;
    }
    case BC::Flinch:
    {
        output<BattleEnum::Flinch>(spot);
        break;
    }
    case BC::Recoil:
    {
        bool damage;
        in >> damage;

        if (damage)
            output<BattleEnum::Recoil>(spot);
        else
            output<BattleEnum::Drained>(spot);
        break;
    }
    case BC::WeatherMessage: {
        qint8 wstatus, weather;
        in >> wstatus >> weather;
        if (weather == BC::NormalWeather)
            break;

        switch(wstatus) {
        case BC::EndWeather:
            output<BattleEnum::EndWeather>(weather);
            break;
        case BC::HurtWeather:
            output<BattleEnum::WeatherDamage>(spot, weather);
            break;
        case BC::ContinueWeather:
            output<BattleEnum::WeatherMessage>(weather);
            break;
        }
    } break;
    case BC::StraightDamage:
    {
        qint16 damage;
        in >> damage;

        output<BattleEnum::Damaged>(spot, damage);
        break;
    }
    case BC::AbilityMessage:
    {
        quint16 ab=0;
        uchar part=0;
        qint8 type(0), foe(0);
        qint16 other(0);
        in >> ab >> part >> type >> foe >> other;

        if (ab == 14) {
            /* Weather message */
            output<BattleEnum::StartWeather>(spot, part+1, true); //true is for ability-weather
        } else if (ab == 126 && other < 1) {
            output<BattleEnum::StartWeather>(spot, part+5, true); //true is for ability-weather
        } else {
            output<BattleEnum::AbilityMessage>(spot, ab, part, type, foe, other);
        }
        break;
    }
    case BC::Substitute:
    {
        bool sub;
        in >> sub;
        output<BattleEnum::SubstituteStatus>(spot, sub);
        break;
    }
    case BC::BattleEnd:
    {
        qint8 res;
        in >> res;
        output<BattleEnum::BattleEnd>(res, spot);
        break;
    }
    case BC::BlankMessage: {
        output<BattleEnum::BlankMessage>();
        break;
    }
    case BC::Clause:
    {
        output<BattleEnum::ClauseMessage>(spot);
        break;
    }
    case BC::Rated:
    {
        bool rated;
        in >> rated;

        output<BattleEnum::RatedInfo>(rated);
        break;
    }
    case BC::TierSection:
    {
        auto tier = mk<QString>();
        in >> *tier;
        output<BattleEnum::TierInfo>(&tier);
        break;
    }
    case BC::DynamicInfo:
    {
        BattleDynamicInfo info;
        in >> info;
        output<BattleEnum::StatBoostsAndField>(spot, info);
        break;
    }
    case BC::ChangeTempPoke:
    {
        quint8 type;
        in >> type;
        if (type == BC::TempMove || type == BC::DefMove) {
            qint8 slot;
            quint16 move;
            in >> slot >> move;

            output<BattleEnum::MoveChange>(spot, slot, move, type==BC::DefMove);
        } else if (type == BC::TempAbility) {
Ejemplo n.º 24
0
//space that is guaranteed for you
int personal_space(char * b, char color) {
  return ((BOARD_SIZE*BOARD_SIZE) - available(b, other(color)));
}
Ejemplo n.º 25
0
 void run() {
     cout << "AsyncMessageServer starting to listen on: " << _port << endl;
     boost::thread other(boost::bind(&io_service::run, &_ioservice));
     _ioservice.run();
     cout << "AsyncMessageServer done listening on: " << _port << endl;
 }
Ejemplo n.º 26
0
bool ieee_floatt::operator==(int i) const
{
  ieee_floatt other(spec);
  other.from_integer(i);
  return *this==other;
}
Ejemplo n.º 27
0
TEST(message_test, request_construction) {
  http::request request;
  http::request other(request);
}
Ejemplo n.º 28
0
void NormalizerConformanceTest::TestConformance(FileStream *input, int32_t options) {
    enum { BUF_SIZE = 1024 };
    char lineBuf[BUF_SIZE];
    UnicodeString fields[FIELD_COUNT];
    UErrorCode status = U_ZERO_ERROR;
    int32_t passCount = 0;
    int32_t failCount = 0;
    UChar32 c;

    if(input==NULL) {
        return;
    }

    // UnicodeSet for all code points that are not mentioned in NormalizationTest.txt
    UnicodeSet other(0, 0x10ffff);

    int32_t count, countMoreCases = sizeof(moreCases)/sizeof(moreCases[0]);
    for (count = 1;;++count) {
        if (!T_FileStream_eof(input)) {
            T_FileStream_readLine(input, lineBuf, (int32_t)sizeof(lineBuf));
        } else {
            // once NormalizationTest.txt is finished, use moreCases[]
            if(count > countMoreCases) {
                count = 0;
            } else if(count == countMoreCases) {
                // all done
                break;
            }
            uprv_strcpy(lineBuf, moreCases[count]);
        }
        if (lineBuf[0] == 0 || lineBuf[0] == '\n' || lineBuf[0] == '\r') continue;

        // Expect 5 columns of this format:
        // 1E0C;1E0C;0044 0323;1E0C;0044 0323; # <comments>

        // Parse out the comment.
        if (lineBuf[0] == '#') continue;

        // Read separator lines starting with '@'
        if (lineBuf[0] == '@') {
            logln(lineBuf);
            continue;
        }

        // Parse out the fields
        if (!hexsplit(lineBuf, ';', fields, FIELD_COUNT)) {
            errln((UnicodeString)"Unable to parse line " + count);
            break; // Syntax error
        }

        // Remove a single code point from the "other" UnicodeSet
        if(fields[0].length()==fields[0].moveIndex32(0, 1)) {
            c=fields[0].char32At(0);
            if(0xac20<=c && c<=0xd73f && quick) {
                // not an exhaustive test run: skip most Hangul syllables
                if(c==0xac20) {
                    other.remove(0xac20, 0xd73f);
                }
                continue;
            }
            other.remove(c);
        }

        if (checkConformance(fields, lineBuf, options, status)) {
            ++passCount;
        } else {
            ++failCount;
            if(status == U_FILE_ACCESS_ERROR) {
              errln("Something is wrong with the normalizer, skipping the rest of the test.");
              break;
            }
        }
        if ((count % 1000) == 0) {
            logln("Line %d", count);
        }
    }

    T_FileStream_close(input);

    /*
     * Test that all characters that are not mentioned
     * as single code points in column 1
     * do not change under any normalization.
     */

    // remove U+ffff because that is the end-of-iteration sentinel value
    other.remove(0xffff);

    for(c=0; c<=0x10ffff; quick ? c+=113 : ++c) {
        if(0x30000<=c && c<0xe0000) {
            c=0xe0000;
        }
        if(!other.contains(c)) {
            continue;
        }

        fields[0]=fields[1]=fields[2]=fields[3]=fields[4].setTo(c);
        sprintf(lineBuf, "not mentioned code point U+%04lx", (long)c);

        if (checkConformance(fields, lineBuf, options, status)) {
            ++passCount;
        } else {
            ++failCount;
            if(status == U_FILE_ACCESS_ERROR) {
              errln("Something is wrong with the normalizer, skipping the rest of the test.");
              break;
            }
        }
        if ((c % 0x1000) == 0) {
            logln("Code point U+%04lx", c);
        }
    }

    if (failCount != 0) {
        errln((UnicodeString)"Total: " + failCount + " lines/code points failed, " +
              passCount + " lines/code points passed");
    } else {
        logln((UnicodeString)"Total: " + passCount + " lines/code points passed");
    }
}
Ejemplo n.º 29
0
/**
 * Called only by render_picture().
 */
static bool render_picture_internal(const SkString& inputPath, const SkString* writePath,
                                    const SkString* mismatchPath,
                                    sk_tools::PictureRenderer& renderer,
                                    SkBitmap** out) {
    SkString inputFilename = SkOSPath::Basename(inputPath.c_str());
    SkString writePathString;
    if (writePath && writePath->size() > 0 && !FLAGS_writeEncodedImages) {
        writePathString.set(*writePath);
    }
    SkString mismatchPathString;
    if (mismatchPath && mismatchPath->size() > 0) {
        mismatchPathString.set(*mismatchPath);
    }

    SkFILEStream inputStream;
    inputStream.setPath(inputPath.c_str());
    if (!inputStream.isValid()) {
        SkDebugf("Could not open file %s\n", inputPath.c_str());
        return false;
    }

    SkPicture::InstallPixelRefProc proc;
    if (FLAGS_deferImageDecoding) {
        proc = &sk_tools::LazyDecodeBitmap;
    } else if (FLAGS_writeEncodedImages) {
        SkASSERT(!FLAGS_writePath.isEmpty());
        reset_image_file_base_name(inputFilename);
        proc = &write_image_to_file;
    } else {
        proc = &SkImageDecoder::DecodeMemory;
    }

    SkDebugf("deserializing... %s\n", inputPath.c_str());

    SkAutoTUnref<SkPicture> picture(SkPicture::CreateFromStream(&inputStream, proc));

    if (NULL == picture) {
        SkDebugf("Could not read an SkPicture from %s\n", inputPath.c_str());
        return false;
    }

    while (FLAGS_bench_record) {
        SkPictureRecorder recorder;
        picture->playback(recorder.beginRecording(picture->cullRect().width(), 
                                                  picture->cullRect().height(), 
                                                  NULL, 0));
        SkAutoTUnref<SkPicture> other(recorder.endRecording());
    }

    SkDebugf("drawing... [%f %f %f %f] %s\n", 
             picture->cullRect().fLeft, picture->cullRect().fTop,
             picture->cullRect().fRight, picture->cullRect().fBottom,
             inputPath.c_str());

    renderer.init(picture, &writePathString, &mismatchPathString, &inputFilename,
                  FLAGS_writeChecksumBasedFilenames, FLAGS_mpd);

    renderer.setup();
    renderer.enableWrites();

    bool success = renderer.render(out);
    if (!success) {
        SkDebugf("Failed to render %s\n", inputFilename.c_str());
    }

    renderer.end();

    return success;
}
Ejemplo n.º 30
0
 Foo::Foo() : Foo(__null) { other(); }