Ejemplo n.º 1
0
 const char * BSONObj::getStringField(const char *name) const {
     BSONElement e = getField(name);
     return e.type() == String ? e.valuestr() : "";
 }
Ejemplo n.º 2
0
void Board::mousePressEvent(QMouseEvent *e)
{
	// Calculate field position
	int pos_x = (e->pos().x() - xOffset()) / tiles.tileWidth();
	int pos_y = (e->pos().y() - yOffset()) / tiles.tileHeight();

	if(e->pos().x() < xOffset() || e->pos().y() < yOffset() ||
		pos_x >= x_tiles() || pos_y >= y_tiles())
	{
		pos_x = -1;
		pos_y = -1;
	}

	// Mark tile
	if(e->button() == LeftButton)
	{
		clearHighlight();

		if(pos_x != -1)
			marked(pos_x, pos_y);
	}

	// Assist by highlighting all tiles of same type
	if(e->button() == RightButton)
	{
		int clicked_tile = getField(pos_x, pos_y);

		// Clear marked tile
		if(mark_x != -1 && getField(mark_x, mark_y) != clicked_tile)
		{
			// We need to set mark_x and mark_y to -1 before calling
			// updateField() to ensure the tile is redrawn as unmarked.
			int oldmarkx = mark_x;
			int oldmarky = mark_y;
			mark_x = -1;
			mark_y = -1;
			updateField(oldmarkx, oldmarky, false);
		}
		else
		{
			mark_x = -1;
			mark_y = -1;
		}

		// Perform highlighting
		if(clicked_tile != highlighted_tile)
		{
			int old_highlighted = highlighted_tile;
			highlighted_tile = clicked_tile;
			for(int i = 0; i < x_tiles(); i++)
			{
				for(int j = 0; j < y_tiles(); j++)
				{
					const int field_tile = getField(i, j);
					if(field_tile != EMPTY)
					{
						if(field_tile == old_highlighted)
							updateField(i, j, false);
						else if(field_tile == clicked_tile)
							updateField(i, j, false);
					}
				}
			}
		}
	}
}
Ejemplo n.º 3
0
static Variant HHVM_FUNCTION(mysql_result, const Resource& result, int row,
                                    const Variant& field /* = 0 */) {
  auto res = php_mysql_extract_result(result);
  if (res == nullptr) return false;

  MYSQL_RES *mysql_result = nullptr;
  MYSQL_ROW sql_row = nullptr;
  unsigned long *sql_row_lengths = nullptr;

  if (res->isLocalized()) {
    if (!res->seekRow(row)) return false;
    if (!res->fetchRow()) return false;
  } else {
    mysql_result = res->get();
    if (row < 0 || row >= (int)mysql_num_rows(mysql_result)) {
      raise_warning("Unable to jump to row %d on MySQL result index %d",
                      row, result->o_getId());
      return false;
    }
    mysql_data_seek(mysql_result, row);

    sql_row = mysql_fetch_row(mysql_result);
    if (!sql_row) {
      return false;
    }
    sql_row_lengths = mysql_fetch_lengths(mysql_result);
    if (!sql_row_lengths) {
      return false;
    }
  }

  int field_offset = 0;
  if (!field.isNull()) {
    if (field.isString()) {
      String sfield = field.toString();
      const char *tmp = strchr(sfield.data(), '.');
      String table_name, field_name;
      if (tmp) {
        int pos = tmp - sfield.data();
        table_name = sfield.substr(0, pos);
        field_name = sfield.substr(pos + 1);
      } else {
        field_name = sfield;
      }

      int i = 0;
      bool found = false;
      res->seekField(0);
      while (i < res->getFieldCount()) {
        MySQLFieldInfo *info = res->getFieldInfo(i);
        if ((table_name.empty() || table_name.same(info->table)) &&
            field_name.same(info->name)) {
          field_offset = i;
          found = true;
          break;
        }
        i++;
      }
      if (!found) { /* no match found */
        raise_warning("%s%s%s not found in MySQL result index %d",
                        table_name.data(), (table_name.empty() ? "" : "."),
                        field_name.data(), result->o_getId());
        return false;
      }
    } else {
      field_offset = field.toInt32();
      if (field_offset < 0 ||
          field_offset >= (int)res->getFieldCount()) {
        raise_warning("Bad column offset specified");
        return false;
      }
    }
  }

  if (res->isLocalized()) {
    Variant f = res->getField(field_offset);
    if (!f.isNull()) {
      return f.toString();
    }
  } else {
    if (sql_row[field_offset]) {
      return String(sql_row[field_offset], sql_row_lengths[field_offset],
                    CopyString);
    }
  }
  return init_null();
}
Ejemplo n.º 4
0
void QgsDataDefinedButton::aboutToShowMenu()
{
  mDefineMenu->clear();

  bool hasExp = !getExpression().isEmpty();
  bool hasField = !getField().isEmpty();
  QString ddTitle = tr( "Data defined override" );

  QAction* ddTitleAct = mDefineMenu->addAction( ddTitle );
  QFont titlefont = ddTitleAct->font();
  titlefont.setItalic( true );
  ddTitleAct->setFont( titlefont );
  ddTitleAct->setEnabled( false );

  bool addActiveAction = false;
  if ( useExpression() && hasExp )
  {
    QgsExpression exp( getExpression() );
    // whether expression is parse-able
    addActiveAction = !exp.hasParserError();
  }
  else if ( !useExpression() && hasField )
  {
    // whether field exists
    addActiveAction = mFieldNameList.contains( getField() );
  }

  if ( addActiveAction )
  {
    ddTitleAct->setText( ddTitle + " (" + ( useExpression() ? tr( "expression" ) : tr( "field" ) ) + ")" );
    mDefineMenu->addAction( mActionActive );
    mActionActive->setText( isActive() ? tr( "Deactivate" ) : tr( "Activate" ) );
    mActionActive->setData( QVariant( isActive() ? false : true ) );
  }

  if ( !mFullDescription.isEmpty() )
  {
    mDefineMenu->addAction( mActionDescription );
  }

  mDefineMenu->addSeparator();

  if ( !mDataTypesString.isEmpty() )
  {
    QAction* fieldTitleAct = mDefineMenu->addAction( tr( "Attribute field" ) );
    fieldTitleAct->setFont( titlefont );
    fieldTitleAct->setEnabled( false );

    mDefineMenu->addAction( mActionDataTypes );

    mFieldsMenu->clear();

    if ( mFieldNameList.size() > 0 )
    {

      for ( int j = 0; j < mFieldNameList.count(); ++j )
      {
        QString fldname = mFieldNameList.at( j );
        QAction* act = mFieldsMenu->addAction( fldname + "    (" + mFieldTypeList.at( j ) + ")" );
        act->setData( QVariant( fldname ) );
        if ( getField() == fldname )
        {
          act->setCheckable( true );
          act->setChecked( !useExpression() );
        }
      }
    }
    else
    {
      QAction* act = mFieldsMenu->addAction( tr( "No matching field types found" ) );
      act->setEnabled( false );
    }

    mDefineMenu->addSeparator();
  }

  QAction* exprTitleAct = mDefineMenu->addAction( tr( "Expression" ) );
  exprTitleAct->setFont( titlefont );
  exprTitleAct->setEnabled( false );

  if ( hasExp )
  {
    QString expString = getExpression();
    if ( expString.length() > 35 )
    {
      expString.truncate( 35 );
      expString.append( "..." );
    }

    expString.prepend( tr( "Current: " ) );

    if ( !mActionExpression )
    {
      mActionExpression = new QAction( expString, this );
      mActionExpression->setCheckable( true );
    }
    else
    {
      mActionExpression->setText( expString );
    }
    mDefineMenu->addAction( mActionExpression );
    mActionExpression->setChecked( useExpression() );

    mDefineMenu->addAction( mActionExpDialog );
    mDefineMenu->addAction( mActionCopyExpr );
    mDefineMenu->addAction( mActionPasteExpr );
    mDefineMenu->addAction( mActionClearExpr );
  }
  else
  {
    mDefineMenu->addAction( mActionExpDialog );
    mDefineMenu->addAction( mActionPasteExpr );
  }

}
Ejemplo n.º 5
0
void QgsDataDefinedButton::updateGui()
{
  QString oldDef = mCurrentDefinition;
  QString newDef( "" );
  bool hasExp = !getExpression().isEmpty();
  bool hasField = !getField().isEmpty();

  if ( useExpression() && !hasExp )
  {
    setActive( false );
    setUseExpression( false );
  }
  else if ( !useExpression() && !hasField )
  {
    setActive( false );
  }

  QIcon icon = mIconDataDefine;
  QString deftip = tr( "undefined" );
  if ( useExpression() && hasExp )
  {
    icon = isActive() ? mIconDataDefineExpressionOn : mIconDataDefineExpression;
    newDef = deftip = getExpression();

    QgsExpression exp( getExpression() );
    if ( exp.hasParserError() )
    {
      setActive( false );
      icon = mIconDataDefineExpressionError;
      deftip = tr( "Parse error: %1" ).arg( exp.parserErrorString() );
      newDef = "";
    }
  }
  else if ( !useExpression() && hasField )
  {
    icon = isActive() ? mIconDataDefineOn : mIconDataDefine;
    newDef = deftip = getField();

    if ( !mFieldNameList.contains( getField() ) )
    {
      setActive( false );
      icon = mIconDataDefineError;
      deftip = tr( "'%1' field missing" ).arg( getField() );
      newDef = "";
    }
  }

  setIcon( icon );

  // update and emit current definition
  if ( newDef != oldDef )
  {
    mCurrentDefinition = newDef;
    emit dataDefinedChanged( mCurrentDefinition );
  }

  // build full description for tool tip and popup dialog
  mFullDescription = tr( "<b><u>Data defined override</u></b><br>" );

  mFullDescription += tr( "<b>Active: </b>%1&nbsp;&nbsp;&nbsp;<i>(ctrl|right-click toggles)</i><br>" ).arg( isActive() ? tr( "yes" ) : tr( "no" ) );

  if ( !mUsageInfo.isEmpty() )
  {
    mFullDescription += tr( "<b>Usage:</b><br>%1<br>" ).arg( mUsageInfo );
  }

  if ( !mInputDescription.isEmpty() )
  {
    mFullDescription += tr( "<b>Expected input:</b><br>%1<br>" ).arg( mInputDescription );
  }

  if ( !mDataTypesString.isEmpty() )
  {
    mFullDescription += tr( "<b>Valid input types:</b><br>%1<br>" ).arg( mDataTypesString );
  }

  QString deftype( "" );
  if ( deftip != tr( "undefined" ) )
  {
    deftype = QString( " (%1)" ).arg( useExpression() ? tr( "expression" ) : tr( "field" ) );
  }

  // truncate long expressions, or tool tip may be too wide for screen
  if ( deftip.length() > 75 )
  {
    deftip.truncate( 75 );
    deftip.append( "..." );
  }

  mFullDescription += tr( "<b>Current definition %1:</b><br>%2" ).arg( deftype ).arg( deftip );

  setToolTip( mFullDescription );

}
Ejemplo n.º 6
0
/// Get Direction
Board::Direction Board::getDirection(unsigned int x, unsigned int y)
{
    return getField(x,y).dir;
}
Ejemplo n.º 7
0
SFBool *ScriptNode::getDirectOutputField()
{
	if (isInstanceNode() == false)
		return directOutputField;
	return (SFBool *)getField(directOutputFieldString);
}
Ejemplo n.º 8
0
field_t		Packet_v1_Channel::getClientSessionId() const
{
  return getField(PROTOV1_CHANNEL_CLIENTSESSIONID_OFF, PROTOV1_CHANNEL_CLIENTSESSIONID_SIZE);
}
Ejemplo n.º 9
0
QString CacheDatabase::getSegmentPath(const QString &cloud_path)
{
    return getField(CacheColumnSegmentBase, CacheColumnCloudPath, cloud_path);
}
Ejemplo n.º 10
0
unsigned long long DataSet::getUInt64Field(int field) const {
  const char *value = getField(field);
  return value ? atoll(value) : 0;
}
Ejemplo n.º 11
0
field_t		Packet_v1_Channel::getChannelId() const
{
  return getField(PROTOV1_CHANNEL_CHANNELID_OFF, PROTOV1_CHANNEL_CHANNELID_SIZE);
}
Ejemplo n.º 12
0
unsigned int DataSet::getUIntField(int field) const {
  const char *value = getField(field);
  return value ? atoi(value) : 0;
}
Ejemplo n.º 13
0
const char *DataSet::getStringField(int field) const {
  const char *value = getField(field);
  return value ? value : "";
}
/* ****************************************************************************
*
* mongoUpdateContextAvailabilitySubscription - 
*/
HttpStatusCode mongoUpdateContextAvailabilitySubscription
(
  UpdateContextAvailabilitySubscriptionRequest*   requestP,
  UpdateContextAvailabilitySubscriptionResponse*  responseP,
  Format                                          notifyFormat,
  const std::string&                              tenant
)
{
  bool reqSemTaken;

  LM_T(LmtMongo, ("Update Context Subscription, notifyFormat: '%s'", formatToString(notifyFormat)));
  reqSemTake(__FUNCTION__, "ngsi9 update subscription request", SemWriteOp, &reqSemTaken);  

  /* Look for document */
  BSONObj     sub;
  std::string err;
  OID         id;

  if (!safeGetSubId(requestP->subscriptionId, &id, &(responseP->errorCode)))
  {
    reqSemGive(__FUNCTION__, "ngsi9 update subscription request (mongo assertion exception)", reqSemTaken);
    if (responseP->errorCode.code == SccContextElementNotFound)
    {
      std::string details = std::string("invalid OID format: '") + requestP->subscriptionId.get() + "'"; 
      alarmMgr.badInput(clientIp, details);
    }
    else // SccReceiverInternalError
    {
      LM_E(("Runtime Error (exception getting OID: %s)", responseP->errorCode.details.c_str()));
    }
    return SccOk;
  }

  if (!collectionFindOne(getSubscribeContextAvailabilityCollectionName(tenant), BSON("_id" << id), &sub, &err))
  {
    reqSemGive(__FUNCTION__, "ngsi9 update subscription request (mongo db exception)", reqSemTaken);
    responseP->errorCode.fill(SccReceiverInternalError, err);
    return SccOk;
  }

  if (sub.isEmpty())
  {
     responseP->errorCode.fill(SccContextElementNotFound);
     reqSemGive(__FUNCTION__, "ngsi9 update subscription request (no subscriptions found)", reqSemTaken);
     return SccOk;
  }

  /* We start with an empty BSONObjBuilder and process requestP for all the fields that can
   * be updated. I don't like too much this strategy (I would have preferred to start with
   * a copy of the original document, then modify as neded, but this doesn't seem to be easy
   * using the API provide by the Mongo C++ driver)
   *
   * FIXME: a better implementation strategy could be doing an findAndModify() query to do the
   * update, so detecting if the document was not found, instead of using findOne() + update()
   * with $set operation. One operations to MongoDb. vs two operations.
   */
  BSONObjBuilder newSub;

  /* Entities (mandatory) */
  BSONArrayBuilder entities;
  for (unsigned int ix = 0; ix < requestP->entityIdVector.size(); ++ix) {
      EntityId* en = requestP->entityIdVector[ix];
      if (en->type == "") {
          entities.append(BSON(CASUB_ENTITY_ID << en->id <<
                               CASUB_ENTITY_ISPATTERN << en->isPattern));
      }
      else {
          entities.append(BSON(CASUB_ENTITY_ID << en->id <<
                               CASUB_ENTITY_TYPE << en->type <<
                               CASUB_ENTITY_ISPATTERN << en->isPattern));
      }

  }
  newSub.append(CASUB_ENTITIES, entities.arr());

  /* Attributes (always taken into account) */
  BSONArrayBuilder attrs;
  for (unsigned int ix = 0; ix < requestP->attributeList.size(); ++ix) {
      attrs.append(requestP->attributeList[ix]);
  }
  newSub.append(CASUB_ATTRS, attrs.arr());

  /* Duration (optional) */
  if (requestP->duration.isEmpty())
  {
    newSub.append(CASUB_EXPIRATION, getField(sub, CASUB_EXPIRATION).numberLong());
  }
  else {
      long long expiration = getCurrentTime() + requestP->duration.parse();
      newSub.append(CASUB_EXPIRATION, expiration);
      LM_T(LmtMongo, ("New subscription expiration: %l", expiration));
  }

  /* Reference is not updatable, so it is appended directly */
  newSub.append(CASUB_REFERENCE, getStringField(sub, CASUB_REFERENCE));

  int count = sub.hasField(CASUB_COUNT) ? getIntField(sub, CASUB_COUNT) : 0;

  /* The hasField check is needed due to lastNotification/count could not be present in the original doc */
  if (sub.hasField(CASUB_LASTNOTIFICATION)) {
      newSub.append(CASUB_LASTNOTIFICATION, getIntField(sub, CASUB_LASTNOTIFICATION));
  }
  if (sub.hasField(CASUB_COUNT)) {
      newSub.append(CASUB_COUNT, count);
  }

  /* Adding format to use in notifications */
  newSub.append(CASUB_FORMAT, std::string(formatToString(notifyFormat)));

  /* Update document in MongoDB */
  if (!collectionUpdate(getSubscribeContextAvailabilityCollectionName(tenant), BSON("_id" << OID(requestP->subscriptionId.get())), newSub.obj(), false, &err))
  {
    reqSemGive(__FUNCTION__, "ngsi9 update subscription request (mongo db exception)", reqSemTaken);
    responseP->errorCode.fill(SccReceiverInternalError, err);
    return SccOk;
  }

  /* Send notifications for matching context registrations */
  processAvailabilitySubscription(requestP->entityIdVector, requestP->attributeList, requestP->subscriptionId.get(), getStringField(sub, CASUB_REFERENCE), notifyFormat, tenant);

  /* Duration is an optional parameter, it is only added in the case they
   * was used for update */
  if (!requestP->duration.isEmpty())
  {
      responseP->duration = requestP->duration;
  }

  responseP->subscriptionId = requestP->subscriptionId;

  reqSemGive(__FUNCTION__, "ngsi9 update subscription request", reqSemTaken);

  return SccOk;
}
Ejemplo n.º 15
0
bool GFF4Struct::hasField(uint32 field) const {
	return getField(field) != 0;
}
Ejemplo n.º 16
0
QString CacheDatabase::getCloudPath(const QString &segment_path)
{
    return getField(CacheColumnCloudPath, CacheColumnSegmentBase, segment_path);
}
Ejemplo n.º 17
0
Common::SeekableReadStream *GFF4Struct::getField(uint32 fieldID, const Field *&field) const {
	if (!(field = getField(fieldID)))
		return 0;

	return getData(*field);
}
Ejemplo n.º 18
0
QString CacheDatabase::getMap(const QString &cloud_path)
{
    return getField(CacheColumnMap, CacheColumnCloudPath, cloud_path);
}
Ejemplo n.º 19
0
/// Set Direction
void Board::setDirection(unsigned int x, unsigned int y, Direction dir)
{
    getField(x,y).dir = dir;
}
Ejemplo n.º 20
0
Common::UString GFF3Struct::getString(const Common::UString &field,
                                      const Common::UString &def) const {

    const Field *f = getField(field);
    if (!f)
        return def;

    if (f->type == kFieldTypeExoString) {
        Common::SeekableReadStream &data = getData(*f);

        const uint32 length = data.readUint32LE();
        return Common::readStringFixed(data, Common::kEncodingASCII, length);
    }

    if (f->type == kFieldTypeResRef) {
        Common::SeekableReadStream &data = getData(*f);

        const uint32 length = data.readByte();
        return Common::readStringFixed(data, Common::kEncodingASCII, length);
    }

    if ((f->type == kFieldTypeByte  ) ||
            (f->type == kFieldTypeUint16) ||
            (f->type == kFieldTypeUint32) ||
            (f->type == kFieldTypeUint64) ||
            (f->type == kFieldTypeStrRef)) {

        return Common::composeString(getUint(field));
    }

    if ((f->type == kFieldTypeChar  ) ||
            (f->type == kFieldTypeSint16) ||
            (f->type == kFieldTypeSint32) ||
            (f->type == kFieldTypeSint64)) {

        return Common::composeString(getSint(field));
    }

    if ((f->type == kFieldTypeFloat) ||
            (f->type == kFieldTypeDouble)) {

        return Common::composeString(getDouble(field));
    }

    if (f->type == kFieldTypeVector) {
        float x = 0.0, y = 0.0, z = 0.0;

        getVector(field, x, y, z);
        return Common::composeString(x) + "/" +
               Common::composeString(y) + "/" +
               Common::composeString(z);
    }

    if (f->type == kFieldTypeOrientation) {
        float a = 0.0, b = 0.0, c = 0.0, d = 0.0;

        getOrientation(field, a, b, c, d);
        return Common::composeString(a) + "/" +
               Common::composeString(b) + "/" +
               Common::composeString(c) + "/" +
               Common::composeString(d);
    }

    throw Common::Exception("GFF3: Field is not a string(able) type");
}
Ejemplo n.º 21
0
SFBool *ScriptNode::getMustEvaluateField()
{
	if (isInstanceNode() == false)
		return mustEvaluateField;
	return (SFBool *)getField(mustEvaluateFieldString);
}
Ejemplo n.º 22
0
/* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 */
bool Board::fromFEN(const char * fen)
{
  clear();

  if ( !fen )
    fen = stdFEN_;

  // trim left
  const char * sepr =" \t\r\n";
  for ( ; *fen && strchr(sepr, *fen); ++fen);
  
  // copy
  strncpy(fen_, fen, FENsize);
  
  // trim right
  int n = (int)strlen(fen_) - 1;
  for (; n >= 0 && strchr(sepr, fen_[n]); --n);
  fen_[n+1] = 0;

  const char * s = fen;
  int x = 0, y = 7;
  for ( ; s && y >= 0; ++s)
  {
    char c = *s;
    if ( '/' == c )
      continue;
    else if ( isdigit(c) )
    {
      int dx = c - '0';
      x += dx;
      if ( x > 7 )
      {
        --y;
        x = 0;
      }
    }
    else
    {
      Figure::Type  ftype = Figure::TypeNone;
      Figure::Color color = Figure::ColorBlack;

      if ( isupper(c) )
        color = Figure::ColorWhite;

      ftype = Figure::toFtype(toupper(c));

      if ( Figure::TypeNone == ftype )
        return false;

      Index p(x, y);
      addFigure(color, ftype, p);

      if ( ++x > 7 )
      {
        --y;
        x = 0;
      }
    }
  }

  int i = 0;
  for ( ; *s; )
  {
    char c = *s;
    if ( c <= ' ' )
    {
      ++s;
      continue;
    }

    if ( 0 == i ) // process move color
    {
      if ( 'w' == c )
        color_ = Figure::ColorWhite;
      else if ( 'b' == c )
        color_ = Figure::ColorBlack;
      else
        return false;
      ++i;
      ++s;
      continue;
    }

    if ( 1 == i ) // process castling possibility
    {
      if ( '-' == c )
      {
        ++i;
        ++s;
        continue;
      }

      for ( ; *s && *s > 32; ++s)
      {
        Field fk, fr;

        switch ( *s )
        {
        case 'k':
          set_castling(Figure::ColorBlack, 0);
          fmgr_.hashCastling(Figure::ColorBlack, 0);
          break;

        case 'K':
          set_castling(Figure::ColorWhite, 0);
          fmgr_.hashCastling(Figure::ColorWhite, 0);
          break;

        case 'q':
          set_castling(Figure::ColorBlack, 1);
          fmgr_.hashCastling(Figure::ColorBlack, 1);
          break;

        case 'Q':
          set_castling(Figure::ColorWhite, 1);
          fmgr_.hashCastling(Figure::ColorWhite, 1);
          break;

        default:
          return false;
        }
      }

      ++i;
      continue;
    }

    if ( 2 == i )
    {
      ++i;
      char cx = *s++;
      if ( '-' == cx ) // no en-passant pawn
        continue;

      if ( !*s )
        return false;

      char cy = *s++;

      Index enpassant(cx, cy);

      if ( color_ )
        cy--;
      else
        cy++;

      Index pawn_pos(cx, cy);

      Field & fp = getField(pawn_pos);
      if ( fp.type() != Figure::TypePawn || fp.color() == color_ )
        return false;

      en_passant_ = enpassant;
      fmgr_.hashEnPassant(en_passant_, fp.color());
      continue;
    }

    if ( 3 == i ) // fifty moves rule
    {
      char str[4];
      str[0] = 0;
      for (int j = 0; *s && j < 4; ++j, ++s)
      {
        if ( *s > 32 )
          str[j] = *s;
        else
        {
          str[j] = 0;
          break;
        }
      }

      fiftyMovesCount_ = atoi(str);
      ++i;
      continue;
    }

    if ( 4 == i ) // moves counter
    {
      movesCounter_ = atoi(s);
      break;
    }
  }

  if ( !invalidate() )
    return false;

  return true;
}
Ejemplo n.º 23
0
void QgsDataDefinedButton::menuActionTriggered( QAction* action )
{
  if ( action == mActionActive )
  {
    setActive( mActionActive->data().toBool() );
    updateGui();
  }
  else if ( action == mActionDescription )
  {
    showDescriptionDialog();
  }
  else if ( action == mActionExpDialog )
  {
    showExpressionDialog();
  }
  else if ( action == mActionExpression )
  {
    setUseExpression( true );
    setActive( true );
    updateGui();
  }
  else if ( action == mActionCopyExpr )
  {
    QApplication::clipboard()->setText( getExpression() );
  }
  else if ( action == mActionPasteExpr )
  {
    QString exprString = QApplication::clipboard()->text();
    if ( !exprString.isEmpty() )
    {
      setExpression( exprString );
      setUseExpression( true );
      setActive( true );
      updateGui();
    }
  }
  else if ( action == mActionClearExpr )
  {
    // only deactivate if defined expression is being used
    if ( isActive() && useExpression() )
    {
      setUseExpression( false );
      setActive( false );
    }
    setExpression( QString( "" ) );
    updateGui();
  }
  else if ( mFieldsMenu->actions().contains( action ) )  // a field name clicked
  {
    if ( action->isEnabled() )
    {
      if ( getField() != action->text() )
      {
        setField( action->data().toString() );
      }
      setUseExpression( false );
      setActive( true );
      updateGui();
    }
  }
}
Ejemplo n.º 24
0
bool Board::toFEN(char * fen) const
{
  if ( !fen )
    return false;

  char * s = fen;

  // 1 - write figures
  for (int y = 7; y >= 0; --y)
  {
    int n = 0;
    for (int x = 0; x < 8; ++x)
    {
      Index idx(x, y);
      const Field & field = getField(idx);
      if ( !field )
      {
        ++n;
        continue;
      }

      if ( n > 0 )
      {
        *s++ = '0' + n;
        n = 0;
      }

      char c = fromFtype(field.type());
      if ( field.color() == Figure::ColorBlack )
        c = tolower(c);

      *s++ = c;
    }
    
    if ( n > 0 )
      *s++ = '0' + n;

    if ( y > 0 )
      *s++ = '/';
  }

  // 2 - color to move
  {
    *s++ = ' ';
    if ( Figure::ColorBlack == color_ )
      *s++ = 'b';
    else
      *s++ = 'w';
  }

  // 3 - castling possibility
  {
    *s++ = ' ';
	  if ( !castling() )
    {
      *s++ = '-';
    }
    else
    {
      if ( castling_K() )
      {
        if ( !verifyCastling(Figure::ColorWhite, 0) )
          return false;

        *s++ = 'K';
      }
      if ( castling_Q() )
      {
        if ( !verifyCastling(Figure::ColorWhite, 1) )
          return false;

        *s++ = 'Q';
      }
      if ( castling_k() )
      {
        if ( !verifyCastling(Figure::ColorBlack, 0) )
          return false;
        
        *s++ = 'k';
      }
      if ( castling_q() )
      {
        if ( !verifyCastling(Figure::ColorBlack, 1) )
          return false;

        *s++ = 'q';
      }
    }
  }

  {
    // 4 - en passant
    *s++ = ' ';
    if ( en_passant_ >= 0 )
    {
      Index ep_pos(en_passant_);

      int x = ep_pos.x();
      int y = ep_pos.y();

      if ( color_ )
        y--;
      else
        y++;

      Index pawn_pos(x, y);
      const Field & ep_field = getField(pawn_pos);
      if ( ep_field.color() == color_ || ep_field.type() != Figure::TypePawn )
        return false;

      char cx = 'a' + ep_pos.x();
      char cy = '1' + ep_pos.y();
      *s++ = cx;
      *s++ = cy;
    }
    else
      *s++ = '-';

    // 5 - fifty move rule
    {
      *s++ = ' ';
      char str[8];
      _itoa(fiftyMovesCount_, str, 10);
      char * sf = str;
      for ( ; *sf; ++sf, ++s)
        *s = *sf;
    }

    // 6 - moves counter
    {
      *s++ = ' ';
      char str[8];
      _itoa(movesCounter_, str, 10);
      char * sf = str;
      for ( ; *sf; ++sf, ++s)
        *s = *sf;
    }
  }

  // terminal
  *s++ = 0;

  return true;
}
Ejemplo n.º 25
0
void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UBool timeOnly) 
{
    UnicodeString pat;
    if(fmt->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
        errln("DateFormat wasn't a SimpleDateFormat");
        return;
    }
    
    UBool isGregorian = FALSE;
    UErrorCode minStatus = U_ZERO_ERROR;
    UDate minDate = CalendarTest::minDateOfCalendar(*fmt->getCalendar(), isGregorian, minStatus);
    if(U_FAILURE(minStatus)) {
      errln((UnicodeString)"Failure getting min date for " + origLocale.getName());
      return;
    } 
    //logln(UnicodeString("Min date is ") + fullFormat(minDate)  + " for " + origLocale.getName());

    pat = ((SimpleDateFormat*)fmt)->toPattern(pat);

    // NOTE TO MAINTAINER
    // This indexOf check into the pattern needs to be refined to ignore
    // quoted characters.  Currently, this isn't a problem with the locale
    // patterns we have, but it may be a problem later.

    UBool hasEra = (pat.indexOf(UnicodeString("G")) != -1);
    UBool hasZoneDisplayName = (pat.indexOf(UnicodeString("z")) != -1) || (pat.indexOf(UnicodeString("v")) != -1) 
        || (pat.indexOf(UnicodeString("V")) != -1);

    // Because patterns contain incomplete data representing the Date,
    // we must be careful of how we do the roundtrip.  We start with
    // a randomly generated Date because they're easier to generate.
    // From this we get a string.  The string is our real starting point,
    // because this string should parse the same way all the time.  Note
    // that it will not necessarily parse back to the original date because
    // of incompleteness in patterns.  For example, a time-only pattern won't
    // parse back to the same date.

    //try {
        for(int i = 0; i < TRIALS; ++i) {
            UDate *d                = new UDate    [DEPTH];
            UnicodeString *s    = new UnicodeString[DEPTH];

            if(isGregorian == TRUE) {
              d[0] = generateDate();
            } else {
              d[0] = generateDate(minDate);
            }

            UErrorCode status = U_ZERO_ERROR;

            // We go through this loop until we achieve a match or until
            // the maximum loop count is reached.  We record the points at
            // which the date and the string starts to match.  Once matching
            // starts, it should continue.
            int loop;
            int dmatch = 0; // d[dmatch].getTime() == d[dmatch-1].getTime()
            int smatch = 0; // s[smatch].equals(s[smatch-1])
            for(loop = 0; loop < DEPTH; ++loop) {
                if (loop > 0)  {
                    d[loop] = fmt->parse(s[loop-1], status);
                    failure(status, "fmt->parse", s[loop-1]+" in locale: " + origLocale.getName());
                    status = U_ZERO_ERROR; /* any error would have been reported */
                }

                s[loop] = fmt->format(d[loop], s[loop]);
                
                // For displaying which date is being tested
                //logln(s[loop] + " = " + fullFormat(d[loop]));
                
                if(s[loop].length() == 0) {
                  errln("FAIL: fmt->format gave 0-length string in " + pat + " with number " + d[loop] + " in locale " + origLocale.getName());
                }

                if(loop > 0) {
                    if(smatch == 0) {
                        UBool match = s[loop] == s[loop-1];
                        if(smatch == 0) {
                            if(match) 
                                smatch = loop;
                        }
                        else if( ! match) 
                            errln("FAIL: String mismatch after match");
                    }

                    if(dmatch == 0) {
                        // {sfb} watch out here, this might not work
                        UBool match = d[loop]/*.getTime()*/ == d[loop-1]/*.getTime()*/;
                        if(dmatch == 0) {
                            if(match) 
                                dmatch = loop;
                        }
                        else if( ! match) 
                            errln("FAIL: Date mismatch after match");
                    }

                    if(smatch != 0 && dmatch != 0) 
                        break;
                }
            }
            // At this point loop == DEPTH if we've failed, otherwise loop is the
            // max(smatch, dmatch), that is, the index at which we have string and
            // date matching.

            // Date usually matches in 2.  Exceptions handled below.
            int maxDmatch = 2;
            int maxSmatch = 1;
            if (dmatch > maxDmatch) {
                // Time-only pattern with zone information and a starting date in PST.
                if(timeOnly && hasZoneDisplayName) {
                    int32_t startRaw, startDst;
                    fmt->getTimeZone().getOffset(d[0], FALSE, startRaw, startDst, status);
                    failure(status, "TimeZone::getOffset");
                    // if the start offset is greater than the offset on Jan 1, 1970
                    // in PST, then need one more round trip.  There are two cases
                    // fall into this category.  The start date is 1) DST or
                    // 2) LMT (GMT-07:52:58).
                    if (startRaw + startDst > -28800000) {
                        maxDmatch = 3;
                        maxSmatch = 2;
                    }
                }
            }

            // String usually matches in 1.  Exceptions are checked for here.
            if(smatch > maxSmatch) { // Don't compute unless necessary
                UBool in0;
                // Starts in BC, with no era in pattern
                if( ! hasEra && getField(d[0], UCAL_ERA) == GregorianCalendar::BC)
                    maxSmatch = 2;
                // Starts in DST, no year in pattern
                else if((in0=fmt->getTimeZone().inDaylightTime(d[0], status)) && ! failure(status, "gettingDaylightTime") &&
                         pat.indexOf(UnicodeString("yyyy")) == -1)
                    maxSmatch = 2;
                // If we start not in DST, but transition into DST
                else if (!in0 &&
                         fmt->getTimeZone().inDaylightTime(d[1], status) && !failure(status, "gettingDaylightTime"))
                    maxSmatch = 2;
                // Two digit year with no time zone change,
                // unless timezone isn't used or we aren't close to the DST changover
                else if (pat.indexOf(UnicodeString("y")) != -1
                        && pat.indexOf(UnicodeString("yyyy")) == -1
                        && getField(d[0], UCAL_YEAR)
                            != getField(d[dmatch], UCAL_YEAR)
                        && !failure(status, "error status [smatch>maxSmatch]")
                        && ((hasZoneDisplayName
                         && (fmt->getTimeZone().inDaylightTime(d[0], status)
                                == fmt->getTimeZone().inDaylightTime(d[dmatch], status)
                            || getField(d[0], UCAL_MONTH) == UCAL_APRIL
                            || getField(d[0], UCAL_MONTH) == UCAL_OCTOBER))
                         || !hasZoneDisplayName)
                         )
                {
                    maxSmatch = 2;
                }
                // If zone display name is used, fallback format might be used before 1970
                else if (hasZoneDisplayName && d[0] < 0) {
                    maxSmatch = 2;
                }
            }

            if(dmatch > maxDmatch || smatch > maxSmatch) { // Special case for Japanese and Islamic (could have large negative years)
              const char *type = fmt->getCalendar()->getType();
              if(!strcmp(type,"japanese")) {
                maxSmatch = 4;
                maxDmatch = 4;
              }
            }

            // Use @v to see verbose results on successful cases
            UBool fail = (dmatch > maxDmatch || smatch > maxSmatch);
            if (optionv || fail) {
                if (fail) {
                    errln(UnicodeString("\nFAIL: Pattern: ") + pat +
                          " in Locale: " + origLocale.getName());
                } else {
                    errln(UnicodeString("\nOk: Pattern: ") + pat +
                          " in Locale: " + origLocale.getName());
                }
                
                logln("Date iters until match=%d (max allowed=%d), string iters until match=%d (max allowed=%d)",
                      dmatch,maxDmatch, smatch, maxSmatch);

                for(int j = 0; j <= loop && j < DEPTH; ++j) {
                    UnicodeString temp;
                    FieldPosition pos(FieldPosition::DONT_CARE);
                    errln((j>0?" P> ":"    ") + fullFormat(d[j]) + " F> " +
                          escape(s[j], temp) + UnicodeString(" d=") + d[j] + 
                          (j > 0 && d[j]/*.getTime()*/==d[j-1]/*.getTime()*/?" d==":"") +
                          (j > 0 && s[j] == s[j-1]?" s==":""));
                }
            }
            delete[] d;
            delete[] s;
        }
    /*}
    catch (ParseException e) {
        errln("Exception: " + e.getMessage());
        logln(e.toString());
    }*/
}
Ejemplo n.º 26
0
void Board::verifyMasks() const
{
  for (int c = 0; c < 2; ++c)
  {
    BitMask pawn_mask_o = 0ULL;
    BitMask pawn_mask_t = 0ULL;
    BitMask knight_mask = 0ULL;
    BitMask bishop_mask = 0ULL;
    BitMask rook_mask = 0ULL;
    BitMask queen_mask = 0ULL;
    BitMask king_mask = 0ULL;
    BitMask all_mask = 0ULL;

    Figure::Color color = (Figure::Color)c;
    for (int p = 0; p < NumOfFields; ++p)
    {
      const Field & field = getField(p);
      if ( !field || field.color() != color )
        continue;

      all_mask |= set_mask_bit(p);

      switch ( field.type() )
      {
      case Figure::TypePawn:
        {
          pawn_mask_t |= set_mask_bit(Index(p).transp());
          pawn_mask_o |= set_mask_bit(p);
        }
        break;

      case Figure::TypeKnight:
        knight_mask |= set_mask_bit(p);
        break;

      case Figure::TypeBishop:
        bishop_mask |= set_mask_bit(p);
        break;

      case Figure::TypeRook:
        rook_mask |= set_mask_bit(p);
        break;

      case Figure::TypeQueen:
        queen_mask |= set_mask_bit(p);
        break;

      case Figure::TypeKing:
        king_mask |= set_mask_bit(p);
        break;
      }
    }

    THROW_IF( pawn_mask_o != fmgr_.pawn_mask_o(color), "pawn mask invalid" );
    THROW_IF( pawn_mask_t != fmgr_.pawn_mask_t(color), "pawn mask invalid" );
    THROW_IF( knight_mask != fmgr_.knight_mask(color), "knight mask invalid" );
    THROW_IF( bishop_mask != fmgr_.bishop_mask(color), "bishop mask invalid" );
    THROW_IF( rook_mask != fmgr_.rook_mask(color), "rook mask invalid" );
    THROW_IF( queen_mask != fmgr_.queen_mask(color), "queen mask invalid" );
    THROW_IF( king_mask != fmgr_.king_mask(color), "king mask invalid" );
    THROW_IF( all_mask != fmgr_.mask(color), "invalid all figures mask" );

  }
}
Ejemplo n.º 27
0
void Board::newGame()
{
	//kdDebug() << "NewGame" << endl;
	int i, x, y, k;

	mark_x = -1;
	mark_y = -1;
	highlighted_tile = -1; // will clear previous highlight

	_undo.clear();
	_redo.clear();
	connection.clear();

	// distribute all tiles on board
	int cur_tile = 1;
	for(y = 0; y < y_tiles(); y += 4)
	{
		for(x = 0; x < x_tiles(); ++x)
		{
			for(k = 0; k < 4 && y + k < y_tiles(); k++)
				setField(x, y + k, cur_tile);

			cur_tile++;
			if(cur_tile > TileSet::nTiles)
				cur_tile = 1;
		}
	}

	if(getShuffle() == 0)
	{
		update();
		starttime = time((time_t *)0);
		emit changed();
		return;
	}

	// shuffle the field
	int tx = x_tiles();
	int ty = y_tiles();
	for(i = 0; i < x_tiles() * y_tiles() * getShuffle(); i++)
	{
		int x1 = random.getLong(tx);
		int y1 = random.getLong(ty);
		int x2 = random.getLong(tx);
		int y2 = random.getLong(ty);
		int t  = getField(x1, y1);
		setField(x1, y1, getField(x2, y2));
		setField(x2, y2, t);
	}

	// do not make solvable if _solvable_flag is false
	if(!_solvable_flag)
	{
		update();
		starttime = time((time_t *)0);
		emit changed();
		return;
	}


	int fsize = x_tiles() * y_tiles() * sizeof(int);
	int *oldfield = new int[x_tiles() * y_tiles()];
	memcpy(oldfield, field, fsize);			// save field
	int *tiles = new int[x_tiles() * y_tiles()];
	int *pos = new int[x_tiles() * y_tiles()];

	while(!solvable(true))
	{
		//kdDebug() << "Not solvable" << endl;
		//dumpBoard();

		// generate a list of free tiles and positions
		int num_tiles = 0;
		for(i = 0; i < x_tiles() * y_tiles(); i++)
			if(field[i] != EMPTY)
			{
				pos[num_tiles] = i;
				tiles[num_tiles] = field[i];
				num_tiles++;
			}

		// restore field
		memcpy(field, oldfield, fsize);

		// redistribute unsolved tiles
		while(num_tiles > 0)
		{
			// get a random tile
			int r1 = random.getLong(num_tiles);
			int r2 = random.getLong(num_tiles);
			int tile = tiles[r1];
			int apos = pos[r2];

			// truncate list
			tiles[r1] = tiles[num_tiles-1];
			pos[r2] = pos[num_tiles-1];
			num_tiles--;

			// put this tile on the new position
			field[apos] = tile;
		}

		// remember field
		memcpy(oldfield, field, fsize);
	}


	// restore field
	memcpy(field, oldfield, fsize);
	delete tiles;
	delete pos;
	delete oldfield;

	update();
	starttime = time((time_t *)0);
	emit changed();
}
Ejemplo n.º 28
0
void Hero::putPortableLamp(SDL_Renderer* renderer)
{
    PortableLamp* temp = PortableLamp::putLamp(getField(), renderer);
    if(temp)
        portableLampsOnMap.push_back(temp);
}
Ejemplo n.º 29
0
bool GFF3Struct::hasField(const Common::UString &field) const {
	return getField(field) != 0;
}
Ejemplo n.º 30
0
 bool BSONObj::getBoolField(const char *name) const {
     BSONElement e = getField(name);
     return e.type() == Bool ? e.boolean() : false;
 }