Example #1
0
 void next()
 {
     switch (rand() % 4) {
     case 0: emit nextState(); break;
     case 1: emit nextStateWrong(); break;
     case 2: emit nextStateRight(); break;
     case 3: emit nextStateTimeOut(); break;
     }
     QTimer::singleShot(0, this, SLOT(next()));
 }
Example #2
0
void QButton::animateTimeout()
{
    if ( !animation )
	return;
    animation  = FALSE;
    buttonDown = FALSE;
    nextState();
    emit released();
    emit clicked();
}
Example #3
0
void MetropolisHastings::AdvanceChainConfig(size_t iChainConfig, size_t iBeta, size_t nSteps)
{
    LOG_ASSERT( fChainConfigs.size() > iChainConfig && fChainConfigs[iChainConfig],
        "Chain configuration " << iChainConfig << " not initialized.");

    ChainConfig& chainConfig = *fChainConfigs[iChainConfig];

    LOG_ASSERT( chainConfig.fPtChains.size() > iBeta,
        "Chain for beta index " << iBeta << " not initialized.");

    LOG_ASSERT( chainConfig.fProposalFunctions[iBeta], "No proposal function defined." );

    Proposal* proposal = chainConfig.fProposalFunctions[iBeta].get();
    ParameterConfig& paramConfig = chainConfig.fDynamicParamConfigs[iBeta];

    Chain& chain = chainConfig.fPtChains[iBeta];

    LOG_ASSERT( !chain.empty(), "No starting point in chain " << iChainConfig
        << "/" << iBeta << "." );

    for (size_t iStep = 0; iStep < nSteps; iStep++) {

        const Sample& previousState = chain.back();

        // prepare the upcoming sample
        Sample nextState( previousState );
        nextState.IncrementGeneration();
        nextState.Reset();

        // propose the next point in the parameter space
        const double proposalAsymmetry = proposal->Transition( previousState, nextState );

        // attempt reflection if limits are exceeded
        paramConfig.ReflectFromLimits( nextState.Values() );

        // evaluate likelihood and prior
        Evaluate( nextState );

        const double mhRatio = CalculateMHRatio( previousState, nextState,
            proposalAsymmetry, fBetas[iBeta] );

        const bool proposalAccepted = Random::Instance().Bool( mhRatio );

        if (proposalAccepted) {
            nextState.SetAccepted( true );
            chain.push_back( nextState );
        }
        else {
            nextState = previousState;
            nextState.SetAccepted( false );
            nextState.IncrementGeneration();
            chain.push_back( nextState );
        }
    }
}
Example #4
0
 FilterState FilterState::descend(const std::string& name)
 {
     FilterState nextState(name);
     bool exc = updateFilter(m_Exclude, name, nextState.m_Exclude);
     bool inc = updateFilter(m_Include, name, nextState.m_Include);
     if (exc != inc)
         nextState.m_Type = exc ? ExclusiveFilter : InclusiveFilter;
     else
         nextState.m_Type = m_Type;
     return nextState;
 }
Example #5
0
void Stacker::keepPlaying() {
    // Check for victory
    if (currY > 15) {
        displayWin();
    }

    // Check timer to see if next frame yet
    if (timer.read_ms() > (250-40*(levelSpeeds[currY]))) {
        nextState();     // Go to next state
        timer.reset();   // Reset timer to 0
    }
}
Example #6
0
void stepLeft(void)
{
//    if (posX == 0)
//    {
//        return;
//    }
    posX--;
    intDecrement = INTDEC_INIT;;
    TIMSK0 |= _BV(TOIE0);
    stepSequence[AXIS_Y] = nextState(stepSequence[AXIS_Y]);
    coilState(AXIS_Y);
    INTERSTEP_DELAY;
}
Example #7
0
void ADSRReader::nextState(ADSRState state)
{
	m_state = state;

	switch(m_state)
	{
	case ADSR_STATE_ATTACK:
		m_level = 0;
		if(m_attack <= 0)
		{
			nextState(ADSR_STATE_DECAY);
			return;
		}
		return;
	case ADSR_STATE_DECAY:
		if(m_decay <= 0)
		{
			nextState(ADSR_STATE_SUSTAIN);
			return;
		}
		if(m_level > 1.0)
			m_level = 1 - (m_level - 1) * m_attack / m_decay * (1 - m_sustain);
		if(m_level <= m_sustain)
			nextState(ADSR_STATE_SUSTAIN);
		break;
	case ADSR_STATE_SUSTAIN:
		m_level = m_sustain;
		break;
	case ADSR_STATE_RELEASE:
		if(m_release <= 0)
		{
			nextState(ADSR_STATE_INVALID);
			return;
		}
		break;
	case ADSR_STATE_INVALID:
		break;
	}
}
/*
 *计算状态转移函数
 */
void ComputeTransitionFunction(char *pattern, char*chset, int n, int ST[][n])
{
	const int m = strlen(pattern);
	for(int q = 0; q <= m; q++)
	{
		for(int c = 0; c < n; c++)
		{
			int neState;
			nextState(pattern, chset[c], q, &neState);
			ST[q][c] = neState;
		}
	}
}
Example #9
0
void stepBack(void)
{
//    if (posY == 0)
//    {
//        return;
//    }
    posY--;
    intDecrement = INTDEC_INIT;;
    TIMSK0 |= _BV(TOIE0);
    stepSequence[AXIS_X] = nextState(stepSequence[AXIS_X]);
    coilState(AXIS_X);
    INTERSTEP_DELAY;
}
Example #10
0
void testApp::update() {
	if(!capturing) {
		camera.update();
	}
	if(camera.isPhotoNew()) {
		camera.savePhoto(curDirectory + ofToString(pattern) + ".jpg");
		if(nextState()) {
			captureTime = ofGetElapsedTimeMillis();
			needToCapture = true;
		} else {
			capturing = false;
		}
	}
}
TaskExecuter::State TaskExecuter::run(const string &taskName, State start) {
  if (!initialized) {
    init(taskName);
  }
  State s = start;
  currStep = 0;
  do {
    Transition t = execState(s);
    State s2 = nextState(s, t);
    LOG_INFO("state machine: transitioning from " << s << " to " << s2 << " via " << t);
    s = s2;
  } while (!isTerminalState(s));
  return s;
}
Example #12
0
void ADSRReader::read(int & length, bool &eos, sample_t* buffer)
{
	Specs specs = m_reader->getSpecs();
	m_reader->read(length, eos, buffer);

	for(int i = 0; i < length; i++)
	{
		for(int channel = 0; channel < specs.channels; channel++)
		{
			buffer[i * specs.channels + channel] *= m_level;
		}

		switch(m_state)
		{
		case ADSR_STATE_ATTACK:
			m_level += 1 / m_attack / specs.rate;
			if(m_level >= 1)
				nextState(ADSR_STATE_DECAY);
			break;
		case ADSR_STATE_DECAY:
			m_level -= (1 - m_sustain) /  m_decay / specs.rate;
			if(m_level <= m_sustain)
				nextState(ADSR_STATE_SUSTAIN);
			break;
		case ADSR_STATE_SUSTAIN:
			break;
		case ADSR_STATE_RELEASE:
			m_level -= m_sustain / m_release / specs.rate ;
			if(m_level <= 0)
				nextState(ADSR_STATE_INVALID);
			break;
		case ADSR_STATE_INVALID:
			length = i;
			return;
		}
	}
}
Example #13
0
Pomodoro::Pomodoro (std::shared_ptr<Settings> settings, QObject *parent)
    : QObject (parent),
      m_state (State::STOPPED),
      pomodorosAmount (0),
      m_prevState (State::STOPPED),
      settings (settings)
{
    //    timer.setTimerType(Qt::VeryCoarseTimer);
    timer.setSingleShot (true);
    connect (&timer, SIGNAL (timeout()), this, SLOT (nextState()));
    passed_timer.setTimerType (Qt::PreciseTimer);
    passed_timer.setInterval (500);
    connect (&passed_timer, SIGNAL (timeout()), this, SLOT (notifyRemaining()));
    passed_timer.start();
}
Example #14
0
void QExercise::updateCountDown()
{
	mCounter++;
	if ( mCounter<=3 )
	{	
	//	QString text = QString("%1").arg( mCounter );
	//	mPresenter->setText( text );
	}
	else
	{
		mPresenter->setText("GO!");
		mTimer->stop();
		nextState();
	}
}
Example #15
0
inline void
upgradeState (actualStatePtr actual, stateDscPtr tmp)
{
  // reset downgrade counter to low threshold
  actual->dcount = tmp->low;
  // if upgrade counter fires...
  if (!(--(actual->ucount)))
    {
      // upgrade actual state...
      actual->state = nextState (tmp->level);
      // ...and initialize new actual state's thresholds
      actual->ucount = (actual->state)->sup;
      actual->dcount = (actual->state)->low;
    }
}
Example #16
0
/*!
  \reimp
 */
void QButton::keyReleaseEvent( QKeyEvent * e)
{
    got_a_release = TRUE;
    switch ( e->key() ) {
    case Key_Space:
	if ( buttonDown && !e->isAutoRepeat() ) {
	    buttonDown = FALSE;
	    nextState();
	    emit released();
	    emit clicked();
	}
	break;
    default:
	e->ignore();
    }
}
Example #17
0
void QButton::mouseReleaseEvent( QMouseEvent *e)
{
    if ( e->button() != LeftButton || !mlbDown )
	return;
    if ( d )
	timer()->stop();
    mlbDown = FALSE;				// left mouse button up
    buttonDown = FALSE;
    if ( hitButton( e->pos() ) ) {		// mouse release on button
    nextState();
        emit released();
    emit clicked();
    } else {
	    repaint( FALSE );
	    emit released();
    }
}
Example #18
0
char *TKGetNextToken(TokenizerT *tk) {

	tk->type = state0;
	char end = '\0';
	int length = strlen(tk->tokenStream);

	while ((tk->j < length+1) && (tk->type < word)){
		if (tk->j <= length){
			nextState(tk->tokenStream[tk->j], &tk->type);
			if ((tk->type >= undefined) && (tk->type < word)){
				switch(tk->type) {
				case malformed_integer:
					{tk->j--; tk->type = integer; break;}
				case malformed_integer2:
					{tk->j--; tk->type = integer; break;}
				case malformed_integer3:
					{tk->j-= 2; tk->type = integer; break;}
				case malformed_float:
					{tk->j--; tk->type = floating_point; break;}
				case malformed_float2:
					{tk->j-= 2; tk->type = floating_point; break;}
				case malformed_stop:
					{tk->j--; tk->type = full_stop; break;}
				case undefined:
					{tk->k = tk->j+1; tk->type = state0; break;}
				default: break;
				}
			}
		tk->j++;
		}
	}
	if (tk->type >= word){
		char *tempToken;
		tk->j--;
		tempToken = (char *)malloc(sizeof(char)*(tk->j-tk->k+1));
		if (tempToken == NULL){
			fprintf(stderr, "Error: No memory available for token string");
		}
		memcpy(tempToken, tk->tokenStream+tk->k, sizeof(char)*(tk->j-tk->k));
		memcpy(tempToken+tk->j-tk->k,&end,sizeof(char));
		tk->k = tk->j;
		return tempToken;
	}
	return NULL;
}
Example #19
0
void SlidingTilePuzzlePDB::BuildPDB()
{
	uint64_t rank;
	GetPDBRankFromState(goalState, rank);
	pdbData[rank] = 0;

	std::queue<uint64_t> openQueue;
	openQueue.push(rank);
	int depth = -1;
	uint64_t numTotal = 0;
	uint64_t numNodesOfCurDepth = 0;
	uint64_t nextRank;
	SlidingTilePuzzleState nextState(goalState.width,goalState.height);
	std::vector<SlidingTilePuzzleAction> actions;
	while (!openQueue.empty())
	{
		nextRank = openQueue.front();
		openQueue.pop();
		//in this case, we have justed finished last depth
		if (pdbData[nextRank] == depth + 1)
		{
			depth++;
			std::cout << "depth: " << depth << " " << 1 + openQueue.size() << " of " << pdbSize << "\n";
			numTotal += 1 + openQueue.size();
		}

		GetStateFromPDBRank(nextState, nextRank);
		env.GetActions(nextState, actions);
		//generate its successors
		for (unsigned int i = 0; i < actions.size(); i++)
		{
			env.ApplyAction(nextState, actions[i]);
			
			GetPDBRankFromState(nextState, nextRank);
			if (pdbData[nextRank] > depth+1)
			{
				pdbData[nextRank] = depth+1;
				openQueue.push(nextRank);
			}		

			env.UndoAction(nextState, actions[i]);
		}
	}
	std::cout<<"total num of nodes: "<<numTotal<<" of " << pdbSize << "\n";
}
Example #20
0
 void gameOfLife(vector<vector<int>>& board) {
   sizeA = board.size();
   sizeB = board[0].size();
   if (sizeA == 0 || sizeB == 0) return;
   if (sizeA == 1 && sizeB == 1) {
     board[0][0] = 0;
     return;
   }
   for (int i = 0; i < sizeA; ++i) {
     for (int j = 0; j < sizeB; ++j) {
       update(board, i, j);
     }
   }
   for (int i = 0; i < sizeA; ++i) {
     for (int j = 0; j < sizeB; ++j) {
       nextState(board, i, j);
     }
   }
 }
Example #21
0
void mouse(int button, int state, int x, int y)
{
    (void)x;
    (void)y;

    if(state != GLUT_DOWN)
        return;

    if(button == GLUT_LEFT_BUTTON)
        nextState();
    
    if(button == GLUT_RIGHT_BUTTON) {
        g_clear = true;
    }

#ifdef __GNUC__
    display();
#endif // __GNUC__
}
void testApp::doHashBits()
{
    timer -= ofGetLastFrameTime();
    if ( timer < 0 )
    {
        nextState();
        return;
    }
    
    intern_timer -= ofGetLastFrameTime();
    printf("intern_timer %f\n", intern_timer );
    
    if ( intern_timer < 0 )
    {
        fans.setGroupOf8( ofRandom( 0, fans.getNumBaseFans()/8 )*8, (unsigned char)ofRandom( 0, 256 ) );
        float t = ofRandomuf();
        t *= t;
        t *= 0.5f;
        intern_timer += t;
    }
}
Example #23
0
LRESULT DemoWidget::processKeyDown(WPARAM wparam, LPARAM lparam)
{
	switch(wparam)
	{
	case VK_LEFT:
		preState();
		break;

	case VK_RIGHT:
		nextState();
		break;

	default:
		break;
	}

	_skiaView.processKeyDown(wparam, lparam);
	_gdiView.processKeyDown(wparam, lparam);
	_gdiplusView.processKeyDown(wparam, lparam);

	return Widget::processKeyDown(wparam, lparam);
}
Example #24
0
void QExercise::start()
{
	if ( mState!=Stopped )
		return;

	mNoteGenerator.reset( new LeitnerNoteGenerator() );
	if (mPresenter->getStaff()->getStaffClef() == StaffClef::TrebbleClef)
	{
		mNoteGenerator->setRange(60, 7 );
	}
	else if (mPresenter->getStaff()->getStaffClef() == StaffClef::BassClef)
	{
		mNoteGenerator->setRange(41, 60);
	}


	mNoteCount = 0;
	mLog.open ("Results.csv", std::fstream::in | std::fstream::out | std::fstream::app);
	assert( mLog.is_open() );
	mLog << "#DateTime;Count;NoteToFindNum;NoteToFindName;AnsweredNoteNum;AnsweredNoteName;AnswerTimeInMs;OK" << std::endl;

	nextState();
}
Example #25
0
void
WorkerBee::onState(State state, sf::Time dt)
{
    Vec2d empty(-1.0, -1.0);

    // first state
    if (state == IN_HIVE) {
        // if bee has pollen transfer it to hive
        if (getPollen() > 0) {
            transferPollen(dt);
            flower_location_ = empty;
            setDebugStatus("in_hive_leaving_pollen");
        } else {
            // if bee has not enough energy to leave hive, eat its nectar
            if (getEnergy() < energy_leave_hive_
                && getHive().getNectar() > 0) {
                setDebugStatus("in_hive_eating");
                eatFromHive(dt);
            }
            // if there is a flower in memory and enough energy, target move
            // to this flower
            else if (flower_location_ != empty
                     && getEnergy() > energy_collect_pollen_) {
                setDebugStatus("in_hive_leaving");
                setMoveTarget(flower_location_);
                // change state to to flower
                nextState();
            } else {
                setDebugStatus("in_hive_no_flower");
            }
        }
    }

    // second state
    else if (state == TO_FLOWER) {
        setDebugStatus("to_flower");

        if (getEnergy() < energy_collect_pollen_) {
            nextState();
            nextState();
        }

        Flower* flower  = getAppEnv().getCollidingFlower(getVisionRange());

        if (flower) {
            setMoveTarget(flower->getPosition());
            setMoveState(MoveState::TARGET);
            if (isPointInside(flower->getPosition())) {
                nextState();
            }
        } else if (isPointInside(flower_location_)) {
            // go back to hive and clear location
            nextState();
            nextState();
            setFlowerLocation(Vec2d(-1,-1));
        }
    }

    // third state
    else if (state == COLLECT_POLLEN) {
        // if there is a flower at flower location and it has pollen and
        // bee has not enough pollen, eat pollen from flower
        Flower* flower(getAppEnv().getCollidingFlower(getCollider()));
        if ((getPollen() < max_pollen_)
            && (flower != nullptr)
            && (flower->getPollen() > 0)) {
            eatPollen(flower, dt);
        } else {
            // else skip collection
            nextState();
        }
    } else if (state == RETURN_HIVE) {
        // if bee is in hive change state to in hive
        if (getHive().isColliderInside(getCollider())) {
            nextState();
        }
    }
}
Example #26
0
	uint32_t processByte(TStream& stream, uint32_t c = 0) {
		uint32_t p0 = owhash & 0xFF;
		byte* o0ptr = &order0[0];
		byte* o1ptr = &order1[p0 << 8];
		uint32_t o2h = ((owhash & 0xFFFF) * 256) & hash_mask;
		uint32_t o3h = ((owhash & 0xFFFFFF) * 3413763181) & hash_mask;
		uint32_t o4h = (owhash * 798765431) & hash_mask;

		uint32_t learn_rate = 4 +
			(byte_count > KB) +
			(byte_count > 16 * KB) +
			(byte_count > 256 * KB) +
			(byte_count > MB);

		const short* no_alias st = table.getStretchPtr();
		uint32_t code = 0;
		if (!kDecode) {
			code = c << (sizeof(uint32_t) * 8 - 8);
		}
		uint32_t len = word_model.getLength();
		int ctx = 1;
		for (uint32_t i = 0; i < 8; ++i) {
			byte
				*no_alias s0 = nullptr, *no_alias s1 = nullptr, *no_alias s2 = nullptr, *no_alias s3 = nullptr, 
				*no_alias s4 = nullptr, *no_alias s5 = nullptr, *no_alias s6 = nullptr, *no_alias s7 = nullptr;

			s0 = &o1ptr[ctx];
			s1 = &hash_table[o2h ^ ctx];
			s2 = &hash_table[o4h ^ ctx];
			// s3 = len > 4 ? &hash_table[(word_model.getHash() & hash_mask) ^ ctx] : &hash_table[o3h ^ ctx];
			s3 = &hash_table[(word_model.getHash() & hash_mask) ^ ctx];

			auto& pr0 = probs[0][*s0];
			auto& pr1 = probs[1][*s1];
			auto& pr2 = probs[2][*s2];
			auto& pr3 = probs[3][*s3];
#if 0
			uint32_t p = table.sq(
				(
				3 * table.st(pr0.getP()) +
				3 * table.st(pr1.getP()) +
				7 * table.st(pr2.getP()) +
				8 * table.st(pr3.getP())) / 16);
#elif 1
			int p0 = table.st(pr0.getP());
			int p1 = table.st(pr1.getP());
			int p2 = table.st(pr2.getP());
			int p3 = table.st(pr3.getP());
			int p = table.sq(mixer.p(9, p0, p1, p2, p3));
#else
			int p = table.sq((table.st(pr0.getP()) + table.st(pr1.getP()) + table.st(pr2.getP()) + table.st(pr3.getP())) / 4) ;
#endif

			uint32_t bit;
			if (kDecode) { 
				bit = ent.getDecodedBit(p, shift);
			} else {
				bit = code >> (sizeof(uint32_t) * 8 - 1);
				code <<= 1;
				ent.encode(stream, bit, p, shift);
			}

			ctx = ctx * 2 + bit;

			mixer.update(p, bit, 12, 28, 1, p0, p1, p2, p3, 0, 0, 0, 0);
			pr0.update(bit, learn_rate);
			pr1.update(bit, learn_rate);
			pr2.update(bit, learn_rate);
			pr3.update(bit, learn_rate);
			*s0 = nextState(*s0, bit, 0);
			*s1 = nextState(*s1, bit, 1);
			*s2 = nextState(*s2, bit, 2);
			*s3 = nextState(*s3, bit, 3);
			
			// Encode the bit / decode at the last second.
			if (kDecode) {
				ent.Normalize(stream);
			}
		}

		return ctx ^ 256;
	}
/////////////////////////////////////////////////////////////////
// Main loop
/////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
  //fmm_omega.open("fmm_omega.dat");

  ROS_INFO_STREAM("Command converter begin: ");
  ROS_INFO_STREAM("Loop Rate: " << next_time);

  // Set up ROS
  ros::init(argc, argv, "command_converter");

  // Make handles
  ros::NodeHandle nh;
  ros::NodeHandle private_nh("~");

  // Publish the following topics:
  // Commands
  ros::Publisher cmd_velocity_publisher = nh.advertise<geometry_msgs::TwistStamped>("twist_raw", 10);

  // Subscribe to the following topics:
  // Curvature parameters and state parameters
  ros::Subscriber spline_parameters = nh.subscribe("spline", 1, splineCallback);
  ros::Subscriber state_parameters = nh.subscribe("state", 1, stateCallback);

  // Setup message to hold commands
  geometry_msgs::TwistStamped twist;

  // Setup the loop rate in Hz
  ros::Rate loop_rate(LOOP_RATE);

  bool endflag = false;
  static  double vdes;

  while (ros::ok())
  {
    std_msgs::Bool _lf_stat;
    

    ros::spinOnce();
    current_time = ros::Time::now().toSec();
    double elapsedTime = current_time - start_time;

    // Make sure we haven't finished the mission yet
    if(endflag==FALSE)
    {
          if(newState == TRUE)
          {
            vdes = veh.vdes;
            // This computes the next command
            veh_temp = nextState(veh, curvature, vdes, next_time, elapsedTime + 0.1);
          }

          // Set velocity
          twist.twist.linear.x=vdes;
          
          // Ensure kappa is reasonable
          veh_temp.kappa = min(kmax, veh_temp.kappa);
          veh_temp.kappa = max (kmin, veh_temp.kappa); 

          // Set angular velocity
          twist.twist.angular.z=vdes*veh_temp.kappa;
    }

    // If we have finished the mission clean up 
    else
    {
      ROS_INFO_STREAM("End mission");
    }
    
    // Publish messages
    cmd_velocity_publisher.publish(twist);
    loop_rate.sleep();
  }
  return 0;
}
 void consumeChars() {
   _pContext->_pState->eatChars();
   _pContext->_pState = nextState();
 }
Example #29
0
void MotionActionHandler::mainLoop(const ros::TimerEvent& te)
{
	current_state = nextState();

}
bool QMimeTypeParserBase::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
    QMimeTypePrivate data;
    int priority = 50;
    QStack<QMimeMagicRule *> currentRules; // stack for the nesting of rules
    QList<QMimeMagicRule> rules; // toplevel rules
    QXmlStreamReader reader(dev);
    ParseState ps = ParseBeginning;
    QXmlStreamAttributes atts;
    while (!reader.atEnd()) {
        switch (reader.readNext()) {
        case QXmlStreamReader::StartElement:
            ps = nextState(ps, reader.name());
            atts = reader.attributes();
            switch (ps) {
            case ParseMimeType: { // start parsing a MIME type name
                const QString name = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (name.isEmpty()) {
                    reader.raiseError(QString::fromLatin1("Missing '%1'-attribute").arg(QString::fromLatin1(mimeTypeAttributeC)));
                } else {
                    data.name = name;
                }
            }
                break;
            case ParseGenericIcon:
                data.genericIconName = atts.value(QLatin1String(nameAttributeC)).toString();
                break;
            case ParseIcon:
                data.iconName = atts.value(QLatin1String(nameAttributeC)).toString();
                break;
            case ParseGlobPattern: {
                const QString pattern = atts.value(QLatin1String(patternAttributeC)).toString();
                unsigned weight = atts.value(QLatin1String(weightAttributeC)).toString().toInt();
                const bool caseSensitive = atts.value(QLatin1String(caseSensitiveAttributeC)).toString() == QLatin1String("true");

                if (weight == 0)
                    weight = QMimeGlobPattern::DefaultWeight;

                Q_ASSERT(!data.name.isEmpty());
                const QMimeGlobPattern glob(pattern, data.name, weight, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
                if (!process(glob, errorMessage))   // for actual glob matching
                    return false;
                data.addGlobPattern(pattern); // just for QMimeType::globPatterns()
            }
                break;
            case ParseSubClass: {
                const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!inheritsFrom.isEmpty())
                    processParent(data.name, inheritsFrom);
            }
                break;
            case ParseComment: {
                // comments have locale attributes. We want the default, English one
                QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
                const QString comment = reader.readElementText();
                if (locale.isEmpty())
                    locale = QString::fromLatin1("en_US");
                data.localeComments.insert(locale, comment);
            }
                break;
            case ParseAlias: {
                const QString alias = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!alias.isEmpty())
                    processAlias(alias, data.name);
            }
                break;
            case ParseMagic: {
                priority = 50;
                const QString priorityS = atts.value(QLatin1String(priorityAttributeC)).toString();
                if (!priorityS.isEmpty()) {
                    if (!parseNumber(priorityS, &priority, errorMessage))
                        return false;

                }
                currentRules.clear();
                //qDebug() << "MAGIC start for mimetype" << data.name;
            }
                break;
            case ParseMagicMatchRule: {
                QMimeMagicRule *rule = 0;
                if (!createMagicMatchRule(atts, errorMessage, rule))
                    return false;
                QList<QMimeMagicRule> *ruleList;
                if (currentRules.isEmpty())
                    ruleList = &rules;
                else // nest this rule into the proper parent
                    ruleList = &currentRules.top()->m_subMatches;
                ruleList->append(*rule);
                //qDebug() << " MATCH added. Stack size was" << currentRules.size();
                currentRules.push(&ruleList->last());
                delete rule;
                break;
            }
            case ParseError:
                reader.raiseError(QString::fromLatin1("Unexpected element <%1>").
                                  arg(reader.name().toString()));
                break;
            default:
                break;
            }
            break;
        // continue switch QXmlStreamReader::Token...
        case QXmlStreamReader::EndElement: // Finished element
        {
            const QStringRef elementName = reader.name();
            if (elementName == QLatin1String(mimeTypeTagC)) {
                if (!process(QMimeType(data), errorMessage))
                    return false;
                data.clear();
            } else if (elementName == QLatin1String(matchTagC)) {
                // Closing a <match> tag, pop stack
                currentRules.pop();
                //qDebug() << " MATCH closed. Stack size is now" << currentRules.size();
            } else if (elementName == QLatin1String(magicTagC)) {
                //qDebug() << "MAGIC ended, we got" << rules.count() << "rules, with prio" << priority;
                // Finished a <magic> sequence
                QMimeMagicRuleMatcher ruleMatcher(data.name, priority);
                ruleMatcher.addRules(rules);
                processMagicMatcher(ruleMatcher);
                rules.clear();
            }
            break;
        }
        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (errorMessage)
            *errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString());
        return false;
    }

    return true;
}