Beispiel #1
0
	void TttBoard::setPeiceAt(int row, int column, char peice) {
		boundsCheck(row, column);
		if (!isMoveLegal(row, column)) {
			throw invalid_argument("There is already a peice in the specified cell");
		}
		mCells[row][column].setPeice(peice);
	}
Beispiel #2
0
FailureCode ObjVectorLayout :: for_IndexableAt_Put(Oop o, int i, Oop x) {
  FailureCode c = boundsCheck(o, i);
  if ( c != SUCCEEDED )  return c;

  for_At_Put( o, indexableOriginOf(o) + i, x );
  return SUCCEEDED;
}
Beispiel #3
0
	bool TttBoard::isMoveLegal(int row, int column) const {
		try {
			boundsCheck(row, column);
		}
		catch (const out_of_range& e) {
			return false;
		}
		return mCells[row][column].getPeice() == ' ';
	}
Beispiel #4
0
void Array<T>::remove(int k)
{
  boundsCheck(k);
  
  int j;
  for (j=k; j<size()-1; j++)
    {
      data[j] = data[j+1];
    }
  
  resize( size() - 1 );
}
// -----------------------------------------------------------------------
// Abstract interface from AbstractNumericValidator
// -----------------------------------------------------------------------
void FloatDatatypeValidator::checkContent(const XMLCh*             const content
                                         ,      ValidationContext* const context
                                         ,      bool                     asBase
                                         ,      MemoryManager*     const manager)
{

    //validate against base validator if any
    FloatDatatypeValidator *pBase = (FloatDatatypeValidator*) this->getBaseValidator();
    if (pBase)
        pBase->checkContent(content, context, true, manager);

    // we check pattern first
    if ( (getFacetsDefined() & DatatypeValidator::FACET_PATTERN ) != 0 )
    {
        if (getRegex()->matches(content, manager) ==false)
        {
            ThrowXMLwithMemMgr2(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_NotMatch_Pattern
                    , content
                    , getPattern()
                    , manager);
        }
    }

    // if this is a base validator, we only need to check pattern facet
    // all other facet were inherited by the derived type
    if (asBase)
        return;

    XMLFloat theValue(content, manager);
    XMLFloat *theData = &theValue;

    if (getEnumeration() != 0)
    {
        int i=0;
        int enumLength = getEnumeration()->size();
        for ( ; i < enumLength; i++)
        {
            if (compareValues(theData, (XMLFloat*) getEnumeration()->elementAt(i))==0)
                break;
        }

        if (i == enumLength)
            ThrowXMLwithMemMgr1(InvalidDatatypeValueException, XMLExcepts::VALUE_NotIn_Enumeration, content, manager);
    }

    boundsCheck(theData, manager);
}
Beispiel #6
0
//Parse a "block" -- ex: canonical "if" expression formatting
//This always has strict ordering
parse_part parse_blockline(parser_state state) {
    parse_part result;
    
    //for the block body formatting
    lexid_tree header;
    lexid_tree tmp;
    int i;

    lexid exprid = EXPR_LEXID;
    exprid.attr.intval = 1; //The resulting expr will have strict formatting
    exprid.loc = getCurrent(state).loc;

    result = parse_listitems(state,1);
    result.state = consume(NEWLINE_LEXID, result.state);
    //may have to protect against "end of program" bugs...
    if (!boundsCheck(result.state)) {
        return result;
    }
    if (lexid_eq(getCurrent(result.state),BEGIN_LEXID)) {
        //parse block body
        header = result.tree;
        result.state = consume(BEGIN_LEXID, result.state);
        result = parse_blocklines(result.state);
        result.state = consume(END_LEXID, result.state);

        //assemble the formatting correctly
        //Format the header
        //NOTE: everything in the header after the first item
        //is NOT strictly ordered
        tmp = lexid_tree_init(exprid);
        tmp.data.attr.intval = 0; //Set the rest of the header to be non-strict

        for (i=1; i < header.children.size; i++) {
            tmp = lexid_tree_addchild(tmp, header.children.begin[i]);
        }
        header = lexid_tree_addchild(lexid_tree_init(exprid), header.children.begin[0]);
        header = lexid_tree_addchild(header, tmp);

        //Assimilate with the body
        tmp.children = result.tree.children;
        result.tree.children = lexid_tree_dynarray_cat(header.children, tmp.children);
        lexid_tree_dynarray_free(tmp.children);
        
    }
    //parsed a block line, we're good, return
    return result; 
}
Beispiel #7
0
UBool
GregorianCalendar::validateFields() const
{
    for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) {
        // Ignore DATE and DAY_OF_YEAR which are handled below
        if (field != UCAL_DATE &&
            field != UCAL_DAY_OF_YEAR &&
            isSet((UCalendarDateFields)field) &&
            ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field))
            return FALSE;
    }

    // Values differ in Least-Maximum and Maximum should be handled
    // specially.
    if (isSet(UCAL_DATE)) {
        int32_t date = internalGet(UCAL_DATE);
        if (date < getMinimum(UCAL_DATE) ||
            date > monthLength(internalGet(UCAL_MONTH))) {
                return FALSE;
            }
    }

    if (isSet(UCAL_DAY_OF_YEAR)) {
        int32_t days = internalGet(UCAL_DAY_OF_YEAR);
        if (days < 1 || days > yearLength()) {
            return FALSE;
        }
    }

    // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
    // We've checked against minimum and maximum above already.
    if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) &&
        0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) {
            return FALSE;
        }

        return TRUE;
}
Beispiel #8
0
//if singleline is non-zero, then parsing is for a single line
//All expressions using this are not strictly ordered (as in, a + b will be reordered to + a b)
parse_part parse_listitems(parser_state state, int singleln) {
    parse_part result;
    parse_part tmp;

    state.index -= 1;

    lexid exprid = EXPR_LEXID;
    exprid.attr.intval = 0; //Set strictness property to 0


    if (boundsCheck(state)) {
        exprid.loc = getCurrent(state).loc;
    }

    result.tree = lexid_tree_init(exprid);
    
    lexid current = SPACE_LEXID;

    while (singleln ? lexid_eq(current, SPACE_LEXID) : isWhite(current)) {
        while (singleln ? lexid_eq(current, SPACE_LEXID) : isWhite(current)) {
            state.index += 1;
            current = getCurrent(state);
        }
        if (singleln && isWhite(current)) {
            continue;
        }
        if (lexid_eq(current, COMMA_LEXID) || lexid_eq(current, RPAREN_LEXID)) {
            continue;
        }
        tmp = parse_listitem(state);
        result.tree = lexid_tree_addchild(result.tree, tmp.tree);
        state.index = tmp.state.index;
        current = getCurrent(state);
    }
    result.state = state;
    return result;
}
Beispiel #9
0
//update all game-related variables
void updateVars()
{
    t = (t + 1) % 3600;
    road.row = (road.row + road.speed) % road.height;
    for (int i = 0; i < numGas; i++)
    {
        gas[i].row += road.speed;
    }
    if (player.row == SCREEN_HEIGHT)
    {
        player.dead = TRUE;
    }
    if (player.dead || player.fuel <= 0)
    {
        player.row += road.speed;
        if (player.row > SCREEN_HEIGHT + player.height) {
            lives--;
            resetLevel();
        }
    }
    else
    {
	    if (KEY_DOWN_NOW(BUTTON_RIGHT))
	    {
		    player.col++;
	    }
	    if (KEY_DOWN_NOW(BUTTON_LEFT))
	    {
		    player.col--;
	    }
	    if (KEY_DOWN_NOW(BUTTON_UP))
	    {
            player.row--;
	    }
	    if (KEY_DOWN_NOW(BUTTON_DOWN))
	    {
            player.row++;
	    }
        boundsCheck(&(player.row), 0, SCREEN_HEIGHT + CAR_HEIGHT, player.height);
        boundsCheck(&(player.col), road.col + 2, road.col + road.width - 2, player.width);
        if (t % player.fuelDecInterval == 0 && player.fuel > 0)
        {
            player.fuel--;
        }
    }
    for (int i = 0; i < numCarsUp; i++)
    {
        if (carsUp[i].dead)
        {
            carsUp[i].row += road.speed;
        }
        else
        {
            //move at the fractional rate vSpeedNum / vSpeedDenom
            if (t % carsUp[i].speedDenom == 0)
            {
                carsUp[i].row += carsUp[i].speedNum;
            }
        }
    }
    for (int i = 0; i < numCarsDown; i++)
    {
        if (carsDown[i].dead)
        {
            carsDown[i].row += road.speed;
        }
        else
        {
            //move at the fractional rate vSpeedNum / vSpeedDenom
            if (t % carsDown[i].speedDenom == 0)
            {
                carsDown[i].row += carsDown[i].speedNum;
            }
        }
    }
    if (police.exists)
    {
        if (police.dead)
        {
            police.row += road.speed;
        }
        else
        {
            //move at the fractional rate vSpeedNum / vSpeedDenom
            if (t % police.vSpeedDenom == 0)
            {
                police.row -= police.vSpeedNum;
            }
            //police follows player in terms of horizontal movement if no other cars in the way
            if (player.col <= police.col - police.hSpeed)
            {
                int canMove = TRUE;
                for (int i = 0; i < numCarsUp && canMove; i++) {
                    if (checkCollision(police.row, police.col - police.hSpeed, police.height, police.width
                            , carsUp[i].row, carsUp[i].col, carsUp[i].height, carsUp[i].width))
                    {
                        canMove = FALSE;
                    }
                }
                for (int i = 0; i < numCarsDown && canMove; i++) {
                    if (checkCollision(police.row, police.col - police.hSpeed, police.height, police.width
                            , carsDown[i].row, carsDown[i].col, carsDown[i].height, carsDown[i].width))
                    {
                        canMove = FALSE;
                    }
                }
                if (canMove)
                {
                    police.col -= police.hSpeed;
                }
            }
            if (player.col >= police.col + police.hSpeed)
            {
                int canMove = TRUE;
                for (int i = 0; i < numCarsUp && canMove; i++) {
                    if (checkCollision(police.row, police.col + police.hSpeed, police.height, police.width
                            , carsUp[i].row, carsUp[i].col, carsUp[i].height, carsUp[i].width))
                    {
                        canMove = FALSE;
                    }
                }
                for (int i = 0; i < numCarsDown && canMove; i++) {
                    if (checkCollision(police.row, police.col + police.hSpeed, police.height, police.width
                            , carsDown[i].row, carsDown[i].col, carsDown[i].height, carsDown[i].width))
                    {
                        canMove = FALSE;
                    }
                }
                if (canMove)
                {
                    police.col += police.hSpeed;
                }
            }
            //update animation frame
            if (t % police.updateInterval == 0)
            {
                police.frame = (police.frame + 1) % 2;
            }
        }
    }
    //collision checking
    for (int i = 0; i < numGas; i++)
    {
        //if the player is in contact with a gas container
        if (checkCollision(player.row, player.col, player.height, player.width,
            gas[i].row, gas[i].col, gas[i].height, gas[i].width))
        {
            player.fuel = MAX_FUEL;
            //remove the gas object
            //replace what was previously in index i with the last element and decrement size of array
            gas[i] = gas[(numGas--) - 1];
            i--;
        }
    }
    for (int i = 0; i < numCarsUp; i++)
    {
        if (checkCollision(player.row, player.col, player.height, player.width,
            carsUp[i].row, carsUp[i].col, carsUp[i].height, carsUp[i].width))
        {
            player.dead = TRUE;
            carsUp[i].dead = TRUE;
        }
    }
    for (int i = 0; i < numCarsDown; i++)
    {
        if (checkCollision(player.row, player.col, player.height, player.width,
            carsDown[i].row, carsDown[i].col, carsDown[i].height, carsDown[i].width))
        {
            player.dead = TRUE;
            carsDown[i].dead = TRUE;
        }
    }
    if (police.exists)
    {
        if (checkCollision(player.row, player.col, player.height, player.width,
                police.row, police.col, police.height, police.width))
        {
            player.dead = TRUE;
            police.dead = TRUE;
        }
        for (int i = 0; i < numCarsUp; i++)
        {
            if (checkCollision(police.row, police.col, police.height, police.width,
                carsUp[i].row, carsUp[i].col, carsUp[i].height, carsUp[i].width))
            {
                police.dead = TRUE;
                carsUp[i].dead = TRUE;
            }
        }
        for (int i = 0; i < numCarsDown; i++)
        {
            if (checkCollision(police.row, police.col, police.height, police.width,
                carsDown[i].row, carsDown[i].col, carsDown[i].height, carsDown[i].width))
            {
                police.dead = TRUE;
                carsDown[i].dead = TRUE;
            }
        }
    }
    score++;
}
Beispiel #10
0
T & Array<T>::operator [] (int k)
{
  boundsCheck(k);
  return data[k];
}
Beispiel #11
0
const T & Array<T>::back() const
{
  boundsCheck(0);
  return data.back();
}
// -----------------------------------------------------------------------
// Abstract interface from AbstractNumericValidator
// -----------------------------------------------------------------------
void DecimalDatatypeValidator::checkContent(const XMLCh*             const content
                                           ,      ValidationContext* const context
                                           ,      bool                     asBase
                                           ,      MemoryManager*     const manager)
{
    //validate against base validator if any
    DecimalDatatypeValidator *pBase = (DecimalDatatypeValidator*) this->getBaseValidator();
    if (pBase)
        pBase->checkContent(content, context, true, manager);

    int thisFacetsDefined = getFacetsDefined();

    // we check pattern first
    if ( (thisFacetsDefined & DatatypeValidator::FACET_PATTERN ) != 0 )
    {
        // lazy construction
        if (getRegex() ==0) {
            try {
                // REVISIT: cargillmem fMemoryManager vs manager
                setRegex(new (fMemoryManager) RegularExpression(getPattern(), SchemaSymbols::fgRegEx_XOption, fMemoryManager));                
            }
            catch (XMLException &e)
            {
                ThrowXMLwithMemMgr1(InvalidDatatypeValueException, XMLExcepts::RethrowError, e.getMessage(), manager);
            }
        }

        if (getRegex()->matches(content, manager) ==false)
        {
            ThrowXMLwithMemMgr2(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_NotMatch_Pattern
                    , content
                    , getPattern()
                    , manager);
        }
    }

    // if this is a base validator, we only need to check pattern facet
    // all other facet were inherited by the derived type
    if (asBase)
        return;
    XMLCh *errorMsg = 0;
    try {
        XMLBigDecimal  compareDataValue(content, manager);
        XMLBigDecimal* compareData = &compareDataValue;        
        
        if (getEnumeration())
        {
            int i=0;
            int enumLength = getEnumeration()->size();
            for ( ; i < enumLength; i++)
            {
                if (compareValues(compareData, (XMLBigDecimal*) getEnumeration()->elementAt(i)) ==0 )
                    break;
            }

            if (i == enumLength)
                ThrowXMLwithMemMgr1(InvalidDatatypeValueException, XMLExcepts::VALUE_NotIn_Enumeration, content, manager);
        }

        boundsCheck(compareData, manager);

        if ( (thisFacetsDefined & DatatypeValidator::FACET_FRACTIONDIGITS) != 0 )
        {
            if ( compareData->getScale() > fFractionDigits )
            {                
                XMLCh value1[BUF_LEN+1];
                XMLCh value2[BUF_LEN+1];
                XMLString::binToText(compareData->getScale(), value1, BUF_LEN, 10, manager);
                XMLString::binToText(fFractionDigits, value2, BUF_LEN, 10, manager);
                ThrowXMLwithMemMgr3(InvalidDatatypeFacetException
                                 , XMLExcepts::VALUE_exceed_fractDigit
                                 , compareData->getRawData()
                                 , value1
                                 , value2
                                 , manager);
            }
        }

        if ( (thisFacetsDefined & DatatypeValidator::FACET_TOTALDIGITS) != 0 )
        {
            if ( compareData->getTotalDigit() > fTotalDigits )
            {                
                XMLCh value1[BUF_LEN+1];
                XMLCh value2[BUF_LEN+1];
                XMLString::binToText(compareData->getTotalDigit(), value1, BUF_LEN, 10, manager);
                XMLString::binToText(fTotalDigits, value2, BUF_LEN, 10, manager);
                ThrowXMLwithMemMgr3(InvalidDatatypeFacetException
                                 , XMLExcepts::VALUE_exceed_totalDigit
                                 , compareData->getRawData()
                                 , value1
                                 , value2
                                 , manager);
            }

            /***
             E2-44 totalDigits

             ... by restricting it to numbers that are expressible as i � 10^-n
             where i and n are integers such that |i| < 10^totalDigits and 0 <= n <= totalDigits.
            ***/

            if ( compareData->getScale() > fTotalDigits )  
            {                
                XMLCh value1[BUF_LEN+1];
                XMLCh value2[BUF_LEN+1];
                XMLString::binToText(compareData->getScale(), value1, BUF_LEN, 10, manager);
                XMLString::binToText(fTotalDigits, value2, BUF_LEN, 10, manager);
                ThrowXMLwithMemMgr3(InvalidDatatypeFacetException
                                 , XMLExcepts::VALUE_exceed_totalDigit
                                 , compareData->getRawData()
                                 , value1
                                 , value2
                                 , manager);
            }        
        }
    }
    catch (XMLException &e)
    {
       errorMsg = XMLString::replicate(e.getMessage(), manager);
    }
    if(errorMsg)
    {
       ArrayJanitor<XMLCh> jan(errorMsg, manager);
       ThrowXMLwithMemMgr1(InvalidDatatypeFacetException, XMLExcepts::RethrowError, errorMsg, manager);
    }
}
Beispiel #13
0
int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"Window");
	Rectangle rectangle;
	sf::Vector2f rect_position;
	


	window.setFramerateLimit(60);
	window.setKeyRepeatEnabled(false);
	window.setMouseCursorVisible(true);

	rectangle.setPosition(400,300);

	while (window.isOpen())
	{
		sf::Event event;

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)

				window.close();

			//key press events
			if (event.type == sf::Event::KeyPressed)
			{
				
				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
				{
					window.close();
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
				{
					//check to make sure boundaries won't be exceeded
					if(boundsCheck(rectangle, window, sf::Keyboard::Key::Up))
					{

					//store the coodinates of the rectangle in a temporary place
					rect_position = rectangle.getPosition();
					//alter the coordinates in the temporary place
					rect_position.y -= rectangle.getSpeed().y;
					//set the rectangle's new position
					rectangle.setPosition(rect_position);

					}
					
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
				{
					
					if(boundsCheck(rectangle,window, sf::Keyboard::Down))
					{
					rect_position = rectangle.getPosition();
					rect_position.y += rectangle.getSpeed().y;
					rectangle.setPosition(rect_position);
					}
					
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
				{
					if(boundsCheck(rectangle,window, sf::Keyboard::Left))
					{
					rect_position = rectangle.getPosition();
					rect_position.x -= rectangle.getSpeed().x;
					rectangle.setPosition(rect_position);
					}
					
					
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
				{
					if(boundsCheck(rectangle,window, sf::Keyboard::Right))
					{
					rect_position = rectangle.getPosition();
					rect_position.x += rectangle.getSpeed().x;
					rectangle.setPosition(rect_position);
					}
					
				}
			}
		}

		window.clear();
		window.draw(rectangle);
		window.display();
	}
}
Beispiel #14
0
int main()
{
	REG_DISPCTL = MODE3 | BG2_ENABLE;
	int row = 140;
	int col = 110;
	int oldrow = row;
	int oldcol = col;
	int isPressed = 0;
	int isPressed1 = 0;
	int size = 20;
	int oldsize = size;
	// drawChar(140, 5, 'A', RED);

	int i;
	int dels[] = {1, 2, 3, 4, 5};
	int numdels = sizeof(dels)/sizeof(dels[0]);
	unsigned short colors[] = {RED, GREEN, BLUE, MAGENTA, CYAN, YELLOW, WHITE};
	int numcolors = sizeof(colors)/sizeof(colors[0]);
	COIN objs[4];
	COIN oldobjs[4];
	int numCoins = sizeof(objs)/sizeof(objs[0]);
	COIN *cur;
	for(i=0; i<numCoins; i++)
	{
		objs[i].row = (rand()%100) - 100;// +  rand()% 20;

		//int a = rand() % 3;//tells which column to put block in
		objs[i].col = (i%3)*90 + 20; 
		objs[i].rd = dels[rand()%numdels];
		objs[i].cd = dels[rand()%numdels];
		//objs[i].rd = 2;
		//objs[i].cd = 2;
		objs[i].color = colors[i%numcolors];
		oldobjs[i] = objs[i];
	}



	//unsigned short bgcolor = LTGRAY;
	//DMA[3].src = &bgcolor;
	//DMA[3].dst = videoBuffer;
	//DMA[3].cnt = 38400 | DMA_ON | DMA_SOURCE_FIXED;

	while(1) // Game Loop
	{
		if(KEY_DOWN_NOW(BUTTON_RIGHT))
		{
			if(!isPressed) {
				col = col + (MAXWIDTH - size) / 2;
				if (col >= MAXWIDTH) {
					col = MAXWIDTH;
				}
			}
			isPressed = 1;
		} else {
			isPressed = 0;
		}
		if(KEY_DOWN_NOW(BUTTON_LEFT))
		{
			if(!isPressed1) {
				col = col - (MAXWIDTH - size) / 2;
				if (col <= MINWIDTH) {
					col = MINWIDTH;
				}
			}
			isPressed1 = 1;
		} else {
			isPressed1 = 0;
		}
	//draw coins
		for (i=0; i<numCoins; i++) {
			cur = objs + i;
			cur->row = cur->row + cur->rd;
			//cur->col = cur->col + cur->cd;

			if (boundsCheck(cur->row, 239, 20) == 1) { //passed bounds
				cur->col = (i%3)*90 + 20; //picks new col
        			cur->row = 0; //puts back to top
				cur->rd = dels[rand()%numdels];
			}
		}

		for(i=0; i<numCoins; i++) {
			drawRect(oldobjs[i].row, oldobjs[i].col, 20, 20, BLACK);
		}
		
		for(i=0; i<numCoins; i++) {
			cur = objs + i;
			if (boundsCheck(cur->row, 239, 20) != 2) { //less than 0
				drawRect(cur->row, cur->col, 20, 20, cur->color);
			}
			oldobjs[i] = objs[i];
			
		}
		oldsize = size;
	//


		WaitForVblank();
		drawRect(oldrow, oldcol, oldsize, oldsize, BLACK);// draw background
		drawRect(row, col, size, size, BLUE); //draw player


		oldrow = row;
		oldcol = col;
		oldsize = size;
	}
}
bool QgsDelimitedTextProvider::nextFeature( QgsFeature& feature )
{
  // before we do anything else, assume that there's something wrong with
  // the feature
  feature.setValid( false );
  while ( !mStream->atEnd() )
  {
    QString line = readLine( mStream ); // Default local 8 bit encoding
    if ( line.isEmpty() )
      continue;

    // lex the tokens from the current data line
    QStringList tokens = splitLine( line );

    while ( tokens.size() < mFieldCount )
      tokens.append( QString::null );

    QgsGeometry *geom = 0;

    if ( mWktFieldIndex >= 0 )
    {
      try
      {
        QString &sWkt = tokens[mWktFieldIndex];
        // Remove Z and M coordinates if present, as currently fromWkt doesn't
        // support these.
        if ( mWktHasZM )
        {
          sWkt.remove( mWktZMRegexp ).replace( mWktCrdRegexp, "\\1" );
        }

        geom = QgsGeometry::fromWkt( sWkt );
      }
      catch ( ... )
      {
        geom = 0;
      }

      if ( geom && geom->wkbType() != mWkbType )
      {
        delete geom;
        geom = 0;
      }
      mFid++;
      if ( geom && !boundsCheck( geom ) )
      {
        delete geom;
        geom = 0;
      }
    }
    else if ( mXFieldIndex >= 0 && mYFieldIndex >= 0 )
    {
      QString sX = tokens[mXFieldIndex];
      QString sY = tokens[mYFieldIndex];

      if ( !mDecimalPoint.isEmpty() )
      {
        sX.replace( mDecimalPoint, "." );
        sY.replace( mDecimalPoint, "." );
      }

      bool xOk, yOk;
      double x = sX.toDouble( &xOk );
      double y = sY.toDouble( &yOk );
      if ( xOk && yOk )
      {
        mFid++;
        if ( boundsCheck( x, y ) )
        {
          geom = QgsGeometry::fromPoint( QgsPoint( x, y ) );
        }
      }
    }

    if ( !geom && mWkbType != QGis::WKBNoGeometry )
    {
      mInvalidLines << line;
      continue;
    }

    // At this point the current feature values are valid

    feature.setValid( true );

    feature.setFeatureId( mFid );

    if ( geom )
      feature.setGeometry( geom );

    for ( QgsAttributeList::const_iterator i = mAttributesToFetch.begin();
          i != mAttributesToFetch.end();
          ++i )
    {
      int fieldIdx = *i;
      if ( fieldIdx < 0 || fieldIdx >= attributeColumns.count() )
        continue; // ignore non-existant fields

      QString &value = tokens[attributeColumns[fieldIdx]];
      QVariant val;
      switch ( attributeFields[fieldIdx].type() )
      {
        case QVariant::Int:
          if ( !value.isEmpty() )
            val = QVariant( value );
          else
            val = QVariant( attributeFields[fieldIdx].type() );
          break;
        case QVariant::Double:
          if ( !value.isEmpty() )
            val = QVariant( value.toDouble() );
          else
            val = QVariant( attributeFields[fieldIdx].type() );
          break;
        default:
          val = QVariant( value );
          break;
      }
      feature.addAttribute( fieldIdx, val );
    }

    // We have a good line, so return
    return true;

  } // !mStream->atEnd()

  // End of the file. If there are any lines that couldn't be
  // loaded, display them now.
  if ( mShowInvalidLines && !mInvalidLines.isEmpty() )
  {
    mShowInvalidLines = false;
    QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Error" ) );
    output->setMessage( tr( "Note: the following lines were not loaded because QGIS was "
                            "unable to determine values for the x and y coordinates:\n" ),
                        QgsMessageOutput::MessageText );

    output->appendMessage( "Start of invalid lines." );
    for ( int i = 0; i < mInvalidLines.size(); ++i )
      output->appendMessage( mInvalidLines.at( i ) );
    output->appendMessage( "End of invalid lines." );

    output->showMessage();

    // We no longer need these lines.
    mInvalidLines.clear();
  }

  return false;

} // nextFeature
Beispiel #16
0
	char TttBoard::getPeiceAt(int row, int column) const {
		boundsCheck(row, column);
		return mCells[row][column].getPeice();
	}		
Beispiel #17
0
bool QgsGPXProvider::nextFeature( QgsFeature& feature )
{
  feature.setValid( false );
  bool result = false;

  QgsAttributeList::const_iterator iter;

  if ( mFeatureType == WaypointType )
  {
    // go through the list of waypoints and return the first one that is in
    // the bounds rectangle
    for ( ; mWptIter != data->waypointsEnd(); ++mWptIter )
    {
      const QgsWaypoint* wpt;
      wpt = &( *mWptIter );
      if ( boundsCheck( wpt->lon, wpt->lat ) )
      {
        feature.setFeatureId( wpt->id );
        result = true;

        // some wkb voodoo
        if ( mFetchGeom )
        {
          char* geo = new char[21];
          std::memset( geo, 0, 21 );
          geo[0] = QgsApplication::endian();
          geo[geo[0] == QgsApplication::NDR ? 1 : 4] = QGis::WKBPoint;
          std::memcpy( geo + 5, &wpt->lon, sizeof( double ) );
          std::memcpy( geo + 13, &wpt->lat, sizeof( double ) );
          feature.setGeometryAndOwnership(( unsigned char * )geo, sizeof( wkbPoint ) );
        }
        feature.setValid( true );

        // add attributes if they are wanted
        for ( iter = mAttributesToFetch.begin(); iter != mAttributesToFetch.end(); ++iter )
        {
          switch ( *iter )
          {
            case NameAttr:
              feature.addAttribute( NameAttr, QVariant( wpt->name ) );
              break;
            case EleAttr:
              if ( wpt->ele != -std::numeric_limits<double>::max() )
                feature.addAttribute( EleAttr, QVariant( wpt->ele ) );
              break;
            case SymAttr:
              feature.addAttribute( SymAttr, QVariant( wpt->sym ) );
              break;
            case CmtAttr:
              feature.addAttribute( CmtAttr, QVariant( wpt->cmt ) );
              break;
            case DscAttr:
              feature.addAttribute( DscAttr, QVariant( wpt->desc ) );
              break;
            case SrcAttr:
              feature.addAttribute( SrcAttr, QVariant( wpt->src ) );
              break;
            case URLAttr:
              feature.addAttribute( URLAttr, QVariant( wpt->url ) );
              break;
            case URLNameAttr:
              feature.addAttribute( URLNameAttr, QVariant( wpt->urlname ) );
              break;
          }
        }

        ++mWptIter;
        break;
      }
    }
  }

  else if ( mFeatureType == RouteType )
  {
    // go through the routes and return the first one that is in the bounds
    // rectangle
    for ( ; mRteIter != data->routesEnd(); ++mRteIter )
    {
      const QgsRoute* rte;
      rte = &( *mRteIter );

      if ( rte->points.size() == 0 )
        continue;
      const QgsRectangle& b( *mSelectionRectangle );
      if (( rte->xMax >= b.xMinimum() ) && ( rte->xMin <= b.xMaximum() ) &&
          ( rte->yMax >= b.yMinimum() ) && ( rte->yMin <= b.yMaximum() ) )
      {
        // some wkb voodoo
        int nPoints = rte->points.size();
        char* geo = new char[9 + 16 * nPoints];
        std::memset( geo, 0, 9 + 16 * nPoints );
        geo[0] = QgsApplication::endian();
        geo[geo[0] == QgsApplication::NDR ? 1 : 4] = QGis::WKBLineString;
        std::memcpy( geo + 5, &nPoints, 4 );
        for ( uint i = 0; i < rte->points.size(); ++i )
        {
          std::memcpy( geo + 9 + 16 * i, &rte->points[i].lon, sizeof( double ) );
          std::memcpy( geo + 9 + 16 * i + 8, &rte->points[i].lat, sizeof( double ) );
        }

        //create QgsGeometry and use it for intersection test
        //if geometry is to be fetched, it is attached to the feature, otherwise we delete it
        QgsGeometry* theGeometry = new QgsGeometry();
        theGeometry->fromWkb(( unsigned char * )geo, 9 + 16 * nPoints );
        bool intersection = theGeometry->intersects( b );//use geos for precise intersection test

        if ( !intersection )
        {
          delete theGeometry;
        }
        else
        {
          if ( mFetchGeom )
          {
            feature.setGeometry( theGeometry );
          }
          else
          {
            delete theGeometry;
          }
          feature.setFeatureId( rte->id );
          result = true;
          feature.setValid( true );

          // add attributes if they are wanted
          for ( iter = mAttributesToFetch.begin(); iter != mAttributesToFetch.end(); ++iter )
          {
            switch ( *iter )
            {
              case NameAttr:
                feature.addAttribute( NameAttr, QVariant( rte->name ) );
                break;
              case NumAttr:
                if ( rte->number != std::numeric_limits<int>::max() )
                  feature.addAttribute( NumAttr, QVariant( rte->number ) );
                break;
              case CmtAttr:
                feature.addAttribute( CmtAttr, QVariant( rte->cmt ) );
                break;
              case DscAttr:
                feature.addAttribute( DscAttr, QVariant( rte->desc ) );
                break;
              case SrcAttr:
                feature.addAttribute( SrcAttr, QVariant( rte->src ) );
                break;
              case URLAttr:
                feature.addAttribute( URLAttr, QVariant( rte->url ) );
                break;
              case URLNameAttr:
                feature.addAttribute( URLNameAttr, QVariant( rte->urlname ) );
                break;
            }
          }

          ++mRteIter;
          break;

        }

        //++mRteIter;
        //xbreak;
      }
    }
  }

  else if ( mFeatureType == TrackType )
  {
    // go through the tracks and return the first one that is in the bounds
    // rectangle
    for ( ; mTrkIter != data->tracksEnd(); ++mTrkIter )
    {
      const QgsTrack* trk;
      trk = &( *mTrkIter );

      QgsDebugMsg( QString( "GPX feature track segments: %1" ).arg( trk->segments.size() ) );
      if ( trk->segments.size() == 0 )
        continue;

      // A track consists of several segments. Add all those segments into one.
      int totalPoints = 0;;
      for ( std::vector<QgsTrackSegment>::size_type i = 0; i < trk->segments.size(); i ++ )
      {
        totalPoints += trk->segments[i].points.size();
      }
      if ( totalPoints == 0 )
        continue;
      QgsDebugMsg( "GPX feature track total points: " + QString::number( totalPoints ) );
      const QgsRectangle& b( *mSelectionRectangle );
      if (( trk->xMax >= b.xMinimum() ) && ( trk->xMin <= b.xMaximum() ) &&
          ( trk->yMax >= b.yMinimum() ) && ( trk->yMin <= b.yMaximum() ) )
      {
        // some wkb voodoo
        char* geo = new char[9 + 16 * totalPoints];
        if ( !geo )
        {
          QgsDebugMsg( "Too large track!!!" );
          return false;
        }
        std::memset( geo, 0, 9 + 16 * totalPoints );
        geo[0] = QgsApplication::endian();
        geo[geo[0] == QgsApplication::NDR ? 1 : 4] = QGis::WKBLineString;
        std::memcpy( geo + 5, &totalPoints, 4 );

        int thisPoint = 0;
        for ( std::vector<QgsTrackSegment>::size_type k = 0; k < trk->segments.size(); k++ )
        {
          int nPoints = trk->segments[k].points.size();
          for ( int i = 0; i < nPoints; ++i )
          {
            std::memcpy( geo + 9 + 16 * thisPoint,     &trk->segments[k].points[i].lon, sizeof( double ) );
            std::memcpy( geo + 9 + 16 * thisPoint + 8, &trk->segments[k].points[i].lat, sizeof( double ) );
            thisPoint++;
          }
        }

        //create QgsGeometry and use it for intersection test
        //if geometry is to be fetched, it is attached to the feature, otherwise we delete it
        QgsGeometry* theGeometry = new QgsGeometry();
        theGeometry->fromWkb(( unsigned char * )geo, 9 + 16 * totalPoints );
        bool intersection = theGeometry->intersects( b );//use geos for precise intersection test

        if ( !intersection ) //no intersection, delete geometry and move on
        {
          delete theGeometry;
        }
        else //intersection
        {
          if ( mFetchGeom )
          {
            feature.setGeometry( theGeometry );
          }
          else
          {
            delete theGeometry;
          }
          feature.setFeatureId( trk->id );
          result = true;

          feature.setValid( true );

          // add attributes if they are wanted
          for ( iter = mAttributesToFetch.begin(); iter != mAttributesToFetch.end(); ++iter )
          {
            switch ( *iter )
            {
              case NameAttr:
                feature.addAttribute( NameAttr, QVariant( trk->name ) );
                break;
              case NumAttr:
                if ( trk->number != std::numeric_limits<int>::max() )
                  feature.addAttribute( NumAttr, QVariant( trk->number ) );
                break;
              case CmtAttr:
                feature.addAttribute( CmtAttr, QVariant( trk->cmt ) );
                break;
              case DscAttr:
                feature.addAttribute( DscAttr, QVariant( trk->desc ) );
                break;
              case SrcAttr:
                feature.addAttribute( SrcAttr, QVariant( trk->src ) );
                break;
              case URLAttr:
                feature.addAttribute( URLAttr, QVariant( trk->url ) );
                break;
              case URLNameAttr:
                feature.addAttribute( URLNameAttr, QVariant( trk->urlname ) );
                break;
            }
          }

          ++mTrkIter;
          break;
        }
      }

    }
  }
  if ( result )
  {
    feature.setValid( true );
  }
  return result;
}
bool QgsDelimitedTextProvider::nextFeature( QgsFeature& feature )
{
  // before we do anything else, assume that there's something wrong with
  // the feature
  feature.setValid( false );
  while ( ! mStream->atEnd() )
  {
    double x = 0.0;
    double y = 0.0;
    QString line = mStream->readLine(); // Default local 8 bit encoding

    // lex the tokens from the current data line
    QStringList tokens;
    if ( mDelimiterType == "regexp" )
      tokens = line.split( mDelimiterRegexp );
    else
      tokens = line.split( mDelimiter );

    bool xOk = false;
    bool yOk = false;

    // Skip indexing malformed lines.
    if ( attributeFields.size() == tokens.size() )
    {
      x = tokens[mXFieldIndex].toDouble( &xOk );
      y = tokens[mYFieldIndex].toDouble( &yOk );
    }

    if ( !( xOk && yOk ) )
    {
      // Accumulate any lines that weren't ok, to report on them
      // later, and look at the next line in the file, but only if
      // we need to.
      QgsDebugMsg( "Malformed line : " + line );
      if ( mShowInvalidLines )
        mInvalidLines << line;

      continue;
    }

    // Give every valid line in the file an id, even if it's not
    // in the current extent or bounds.
    ++mFid;             // increment to next feature ID

    // skip the feature if it's out of current bounds
    if ( ! boundsCheck( x, y ) )
      continue;

    // at this point, one way or another, the current feature values
    // are valid
    feature.setValid( true );

    feature.setFeatureId( mFid );

    QByteArray  buffer;
    QDataStream s( &buffer, static_cast<QIODevice::OpenMode>( QIODevice::WriteOnly ) ); // open on buffers's data

    switch ( QgsApplication::endian() )
    {
      case QgsApplication::NDR :
        // we're on a little-endian platform, so tell the data
        // stream to use that
        s.setByteOrder( QDataStream::LittleEndian );
        s << ( quint8 )1; // 1 is for little-endian
        break;
      case QgsApplication::XDR :
        // don't change byte order since QDataStream is big endian by default
        s << ( quint8 )0; // 0 is for big-endian
        break;
      default :
        qDebug( "%s:%d unknown endian", __FILE__, __LINE__ );
        //delete [] geometry;
        return false;
    }

    s << ( quint32 )QGis::WKBPoint;
    s << x;
    s << y;

    unsigned char* geometry = new unsigned char[buffer.size()];
    memcpy( geometry, buffer.data(), buffer.size() );

    feature.setGeometryAndOwnership( geometry, sizeof( wkbPoint ) );

    for ( QgsAttributeList::const_iterator i = mAttributesToFetch.begin();
          i != mAttributesToFetch.end();
          ++i )
    {
      QVariant val;
      switch ( attributeFields[*i].type() )
      {
        case QVariant::Int:
          val = QVariant( tokens[*i].toInt() );
          break;
        case QVariant::Double:
          val = QVariant( tokens[*i].toDouble() );
          break;
        default:
          val = QVariant( tokens[*i] );
          break;
      }
      feature.addAttribute( *i, val );
    }

    // We have a good line, so return
    return true;

  } // ! textStream EOF

  // End of the file. If there are any lines that couldn't be
  // loaded, display them now.

  if ( mShowInvalidLines && !mInvalidLines.isEmpty() )
  {
    mShowInvalidLines = false;
    QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Error" ) );
    output->setMessage( tr( "Note: the following lines were not loaded because Qgis was "
                            "unable to determine values for the x and y coordinates:\n" ),
                        QgsMessageOutput::MessageText );

    output->appendMessage( "Start of invalid lines." );
    for ( int i = 0; i < mInvalidLines.size(); ++i )
      output->appendMessage( mInvalidLines.at( i ) );
    output->appendMessage( "End of invalid lines." );

    output->showMessage();

    // We no longer need these lines.
    mInvalidLines.empty();
  }

  return false;

} // nextFeature
Beispiel #19
0
Address ObjVectorLayout :: for_AddressOfIndexableAt( Oop o, int i )  {
  FailureCode c = boundsCheck(o, i);
  if ( c != SUCCEEDED )  return INVALID_ADDRESS;
  
  return for_AddressAt( o,  indexableOriginOf(o) + i );
}
Beispiel #20
0
Oop ObjVectorLayout::for_IndexableAt(Oop o, int i) {
  FailureCode c = boundsCheck(o, i);
  if ( c != SUCCEEDED )  return INVALID_OOP;

  return for_At( o, indexableOriginOf(o) + i );
}