Пример #1
0
int findMatch(node* head, int passedData)
{
	if(head == NULL)
	{
		return 0;
	}	

	if(head->data == passedData)
	{
		return 1 + findMatch(head->next, passedData);
	}
	else
	{
		return 0 + findMatch(head->next, passedData);
	}
}
Пример #2
0
void            ParenCat( void ) {
//==========================

// Check if ) matches ( as opposed to [.
// called on ) // sequence

    itnode      *cit;
    bool        ok_to_axe;
    bool        all_const_opns;

    cit = findMatch( &ok_to_axe, &all_const_opns );
    if( cit != NULL ) {
        // consider:    a(1)(2:3)//c
        if( ( cit->opr == OPR_LBR ) && ok_to_axe ) {
            ReqNOpn();
            cit->is_catparen = 1;
            cit = CITNode;
            AdvanceITPtr();
            FreeOneNode( cit );
        // check for CHAR(73) - CHAR is allowed in constant expressions
        } else if( (cit->opr != OPR_FBR) || !all_const_opns ||
                   ((cit->link->flags & SY_CLASS ) != SY_SUBPROGRAM) ||
                   (!(cit->link->flags & SY_INTRINSIC)) ||
                   (cit->link->sym_ptr->ns.si.fi.index != IF_CHAR) ) {
            ChkConstCatOpn( CITNode->link );
        }
    }
    BackTrack();
}
Пример #3
0
void ShtServer::onMatchFinished(const QString &uuid)
{
    qWarning() << "OnMatchFinished, uuid: " << uuid;
    Match *m = findMatch(uuid);
    matches.removeOne(m);
    m->deleteLater();
}
Пример #4
0
void MainWindow::work()
{
    QString fileName=pathE->text();
    for(int i=0;i<fileName.length();i++)
        if(fileName[i]=='\\')
            fileName[i]='/';
    int picNum=numE->text().toInt();
    wd=new ImageWidget(NULL,fileName,picNum);
    matchFBtn->setVisible(wd->tp.linev.size()==Hei);
    findMBtn->setVisible(true);
    findSBtn->setVisible(true);
    preBtn->setVisible(true);
    addBtn->setVisible(true);
    delBtn->setVisible(true);
    redoBtn->setVisible(true);
    nextBtn->setVisible(true);
    zinBtn->setVisible(true);
    zoutBtn->setVisible(true);
//    listSBtn->setVisible(true);
    connect(listSBtn,SIGNAL(clicked()),this,SLOT(listSameLine()));
    connect(findMBtn,SIGNAL(clicked()),this,SLOT(findMatch()));
    connect(findSBtn,SIGNAL(clicked()),this,SLOT(findSameLine()));
    connect(preBtn,SIGNAL(clicked()),this,SLOT(getPre()));
    connect(nextBtn,SIGNAL(clicked()),this,SLOT(getNext()));
    connect(addBtn,SIGNAL(clicked()),this,SLOT(addEdge()));
    connect(delBtn,SIGNAL(clicked()),this,SLOT(delEdge()));
    connect(redoBtn,SIGNAL(clicked()),this,SLOT(redo()));
    connect(dispBtn,SIGNAL(clicked()),this,SLOT(disp()));
    connect(matchFBtn,SIGNAL(clicked()),this,SLOT(matchFinall()));
    connect(zinBtn,SIGNAL(clicked()),this,SLOT(zoomin()));
    connect(zoutBtn,SIGNAL(clicked()),this,SLOT(zoomout()));
    updateLayout();
    wd->show();

}
Пример #5
0
void            ChkCatOpn( void ) {
//===========================

// Check if ) is the start of a concatenation operand.
// Called on ) rel sequence since only relational operators are allowed with
// character arguments.
// Consider:
//      if( a(1)//a(2) .eq. 'ab' )then
// We want to evaluate 'ab' first. Otherwise, a(2) would get evaluated,
// followed by 'ab' and finally a(1) -- which is incorrect.

    itnode      *cit;
    bool        ok_to_axe;

    cit = findMatch( &ok_to_axe, NULL );
    if( cit != NULL ) {
        if( cit->opr == OPR_FBR ) {
            if( cit->link->opr == OPR_CAT ) {
                CatOpn();
                return;
            }
        }
    }
    BackTrack();
}
Пример #6
0
std::string UserList::completeUserName(std::string const& text, std::string const& ignore)
{
    std::string fullUserName;

    if (text.empty())
    {
        LOG(DEBUG)<< "ignored trying to complete empty string";
        return fullUserName;
    }

    std::vector<std::string> userNames;

    for (int i=0; i<rows(); ++i)
    {
        StringTableRow const & row = getRow(static_cast<std::size_t>(i));
        try
        {
            User const & user = model_.getUser(row.data_[0]);
            userNames.push_back(row.data_[0]);
        }
        catch (std::invalid_argument const & e)
        {
            LOG(WARNING)<< "unexpected exception: "<< e.what();
        }
    }

    auto const match = findMatch(userNames, text, ignore);
    if (!match.empty())
    {
        fullUserName = match;
    }

    return fullUserName;
}
Пример #7
0
int RandOp::getOneUnique(int min, int max)
{
    int val;
    bool isMatch;

    do {
        val = pRand->IRandomX(min, max);

        // If val returned is a zero or one, bump the corresponding
        // counters and check to see if we've exceeded the maximum
        // allowable number for those conditions.
        //
        if(val == 0) {
            m_zeroCount++;
            if(m_zeroCount > m_maxZeros)
                continue;
        }

        if(val == 1) {
            m_onesCount++;
            if(m_onesCount > m_maxOnes)
                continue;
        }

        isMatch = findMatch(val, m_qlLopRepeats);
    } while (isMatch);

    return val;
}
Пример #8
0
int main() {

	puts("\n\n ----- 	Lab 2: Unicode Blocks 	----- ");
	puts(" -----	Author: Matt Hixon 	-----\n\n");

	int size = readFile();

	if(size != 0){
		int codepoint;
		puts("Enter a Codepoint Value (integer)\n");
		scanf("%d", &codepoint);

		do{
			puts("--------------- ");
			int blockIndex = findMatch(codepoint, size);

			if(blockIndex == -1){
				puts("No matching block found.");
			} else {
				printf("%s", blocks[blockIndex].name);
			}

			puts("\n\n\nTry another number (-1 to exit):\n");
			scanf("%d", &codepoint);
		} while (codepoint != -1);
	}
	
}
Пример #9
0
bool win(){
	int begin=0;
	for(int i=0;seq[i]!='\0';i++){
		int pos=findMatch(seq[i],begin);
		if(pos==-1)
			return false;
		begin=pos+1;
	}
	return true;
}
// Main function
int main(int argc, char *argv[]){
  char *line;
  char *address;
  char pattern[] = "GCAG";
  getString(&line);
  address = findMatch(line, pattern);
  printIt(address);
  if (address != NULL)
    getIndex(line, address);
}
Пример #11
0
void GLUTAPIENTRY
glutGameModeString(const char *string)
{
  Criterion *criteria;
  int ncriteria;

  initGameModeSupport();
  criteria = parseDisplayString(string, &ncriteria);
  currentDm = findMatch(dmodes, ndmodes, criteria, ncriteria);
  free(criteria);
}
Пример #12
0
int main(int argc, char *argv[]){
  char *line;
  char *result;
  char *c;
  getString3(&line);
  printString(line);
  result = findMatch(line);

  if (result == NULL){
    printf("Too bad no match\n");
  } else {
    printf("Yippee a match is found\n");
  }
}
Пример #13
0
int main(int argc,char* argv[]) {
	if (argc < 5) {
		printf("%s ratio target id_start id_end\n",argv[0]);
		return 1;
	}

	float ratio = atof(argv[1]);
	int id_start = atoi(argv[3]);
	int id_end = atoi(argv[4]);

	Desc targetDesc = parseKeyFile(argv[2]);
	printf("Loaded %d (dim %d) keypoints from %s\n",targetDesc.n,targetDesc.dimension,argv[2]);
	
	int newDimension = 64;
	float* pca_basis = new float[newDimension * targetDesc.dimension];
	pca(targetDesc,newDimension,pca_basis);
	changeBasis(&targetDesc,newDimension,pca_basis);

	char buffer[128];
	struct timespec tic,toc;
	clock_gettime(CLOCK_MONOTONIC,&tic);
	for (int i=id_start;i<=id_end;i++) {
		sprintf(buffer,"%d.key",i);
		Desc sourceDesc = parseKeyFile(buffer);
		changeBasis(&sourceDesc,newDimension,pca_basis);
		std::vector<Match> match = findMatch(sourceDesc,targetDesc,ratio);
		sprintf(buffer,"%d.site.match",i);
		FILE* output = fopen(buffer,"w");
		for (size_t i=0;i<match.size();i++) {
			fprintf(output,"0 %f %f 1 %f %f\n",
				sourceDesc.x[match[i].id1],sourceDesc.y[match[i].id1],
				targetDesc.x[match[i].id2],targetDesc.y[match[i].id2]);
		}
		printf("Wrote %lu matches to %s\n",match.size(),buffer);
		fclose(output);

		delete[] sourceDesc.x;
		delete[] sourceDesc.y;
		delete[] sourceDesc.data;
	}
	clock_gettime(CLOCK_MONOTONIC,&toc);
	printf("Profiling: %fs for %d images\n",toc.tv_sec - tic.tv_sec + 0.000000001 * toc.tv_nsec - 0.000000001 * tic.tv_nsec,id_end-id_start+1);
	delete[] targetDesc.x;
	delete[] targetDesc.y;
	delete[] targetDesc.data;
	delete[] pca_basis;
}
Пример #14
0
void LZ::myEncode(char n , char l , char s )
{
	cout << "encoding..."<<endl;
	N = n;
	L = l;
	S = s;
	//default values: N = 11, L = 4, S = 3
	if (ifile.is_open()) {
		cout << "file is opened..." << endl;
		W = pow(2, N);
		F = pow(2, L)-1;
		char* buffer = new char[F];
		window = "";
		lookahead = "";
		//while there is input to process 
		//(i.e. there is unread data or unprocessed data in the lookahead)
		while (!ifile.eof()|| lookahead!="") {
			//if there is unread data
			if (!ifile.eof())
			{//read enough chars(at most F) to make lookahead contain F chars
				ifile.read(buffer, F - lookahead.length());
				//only append the number of chars that were read in the previous step to the
				//lookahead(otherwise the rest of the data will be junk data) if you dont use
				//gcount, at the end of the file you will try to append more chars than you have
				lookahead.append(buffer, ifile.gcount());
			}
			//make sure the size of window is correct
			if (window.length() + lookahead.length() > W) {
				//resize window so that len(window) + len(lookahead)<=W 
				int window_start= window.length() - (W - lookahead.length());
				int window_end	= W - lookahead.length();
				window = window.substr(window_start,window_end);
			}
			findMatch();
		}
		ifile.close();
	}
	//now we need to encode the completed tokens to a file and output the reuslt
	//cleanTokens();
	writeTokens();

}
Пример #15
0
/**
 * Removes all rules which are not descendants of simulated DAG rooted at targets.
 *
 * @param rules Queue of rules which is read and modified.
 * @param targets List of targets which act as roots.
 * @return Void.
 */
static void filterOnTargets(queue_t **rules, char **targets){
	queue_t *validRules = malloc(sizeof(queue_t));
	queue_init(validRules);
	int idx;
	
	//initialize validRules with targets
	for(idx=0; idx < queue_size(*rules);idx++){
		rule_t *curRule = queue_at(*rules, idx);
		int tarIdx;
		for(tarIdx=0; targets[tarIdx] != NULL; tarIdx++){
			if(strcmp(curRule->target, targets[tarIdx]) == 0){
				queue_enqueue(validRules, curRule);
				queue_remove_at(*rules, idx);
				idx--;
				break;
			}
		}
	}

	//repeated linear search for new valid targets
	int prevSize = 0;
	while(prevSize != queue_size(validRules)){
		prevSize = queue_size(validRules);

		for(idx=0; idx < queue_size(*rules); idx++){
			rule_t *curRule = queue_at(*rules, idx);
			if(findMatch(curRule, validRules)){
				queue_enqueue(validRules, curRule);
				queue_remove_at(*rules, idx);
				idx--;
			}
		}
	}
	
	//cleanup old rules
	queue_iterate(*rules, rule_free_adapter, 0);
	queue_destroy(*rules);
	free(*rules);

	//assign new queue
	*rules = validRules;
}
Пример #16
0
	virtual size_t match(const char* data, size_t size)
	{
		__m128i firstLetter = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->firstLetter));
		__m128i patternData = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->patternData));
		__m128i patternMask = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->patternMask));

		size_t offset = firstLetterPos;

		while (offset + 32 <= size)
		{
			__m128i value = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + offset));
			unsigned int mask = _mm_movemask_epi8(_mm_cmpeq_epi8(value, firstLetter));

			// advance offset regardless of match results to reduce number of live values
			offset += 16;

			while (mask != 0)
			{
				unsigned int pos = re2::countTrailingZeros(mask);
				size_t dataOffset = offset - 16 + pos - firstLetterOffset;

				mask &= ~(1 << pos);

				// check if we have a match
				__m128i patternMatch = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + dataOffset));
				__m128i matchMask = _mm_or_si128(patternMask, _mm_cmpeq_epi8(patternMatch, patternData));

				if (_mm_movemask_epi8(matchMask) == 0xffff)
				{
					size_t matchOffset = dataOffset + firstLetterOffset - firstLetterPos;

					// final check for full pattern
					if (matchOffset + pattern.size() < size && memcmp(data + matchOffset, pattern.c_str(), pattern.size()) == 0)
					{
						return matchOffset;
					}
				}
			}
		}

		return findMatch(pattern.c_str(), pattern.size(), data, size, offset - firstLetterPos);
	}
Пример #17
0
void recognizeAlphabet(int size){
	//recognize alphabet
	char line[2048];
	unsigned char *c;
	int lenptr;
 	unsigned int codepoint;
 	int blockIndex = 0;

 	while(fgets(line, 2048, stdin) != NULL){
 		c = line;
 		while(*c != '\0' && *c != '\n'){
 			codepoint = utf8_to_codepoint(c, &lenptr);
			if(codepoint > 0){ 
				int blockIndex = findMatch(codepoint, size);
				if(blockIndex != -1){ blocks[blockIndex].counter += 1; }	 
				c = c + lenptr; 
			}
			if(codepoint == 0){c++;}
 		}
 	}
}
Пример #18
0
	virtual size_t match(const char* data, size_t size)
	{
		__m128i firstLetter = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->firstLetter));
		__m128i patternData = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->patternData));
		__m128i patternMask = _mm_loadu_si128(reinterpret_cast<const __m128i*>(this->patternMask));

		size_t offset = firstLetterPos;

		while (offset + 32 <= size)
		{
			__m128i value = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + offset));
			int mask = _mm_movemask_epi8(_mm_cmpeq_epi8(value, firstLetter));

			if (mask == 0)
				offset += 16;
			else
			{
				offset += re2::countTrailingZeros(mask);

				// check if we have a match
				__m128i patternMatch = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + offset - firstLetterOffset));
				__m128i matchMask = _mm_or_si128(patternMask, _mm_cmpeq_epi8(patternMatch, patternData));

				if (_mm_movemask_epi8(matchMask) == 0xffff)
				{
					// final check for full pattern
					if (memcmp(data + offset - firstLetterPos, pattern.c_str(), pattern.size()) == 0)
					{
						return offset - firstLetterPos;
					}
				}

				offset += 1;
			}
		}

		return findMatch(pattern.c_str(), pattern.size(), data, size, offset - firstLetterPos);
	}
Пример #19
0
bool Parser::parse(QString pattern)
{
    if(!pattern.isEmpty())
        setExpression(pattern);

    for(std::vector<Token *>::iterator iter = _tokens.begin(); iter != _tokens.end(); ++iter)
        delete *iter;

    _tokens.clear();

    int previousPositon = 0;
    while(_pos < pattern.length())
    {
        handleToken(findMatch());

        // In the case where no progress is being made, exit returning false
        if(previousPositon == _pos)
            return false;

        previousPositon = _pos;
    }

    return true;
}
Пример #20
0
int main (int argc, char** argv) {
	int my_rank, p;
	long int n = atoi(argv[1]);
	long int q=1;
	long int *qlist;
	mpz_t l;
	mpz_init(l);

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
	qlist = (long int*)malloc(sizeof(long int)*(n/p));
	
	int i = 0;
	int u = 0;
	while(q <= sqrt(n)){
		if (i == p) i = 0;
		if (my_rank == i) {
			qlist[u] = q;
			u++;
		}
		mpz_nextprime(l, l);
		q = mpz_get_si(l);
		i++;	
	}
	for (int a=0; a<u; a++){
		if(findMatch(qlist[a], n)){
			printf("Answer: %u and %u\n", qlist[a], n/(qlist[a]));
		}
	}
	
	free(qlist);
	MPI_Finalize();
	return 0;
}
Пример #21
0
void            CatParen( void ) {
//==========================

// Check if ) matches ( as opposed to [.
// called on // ) sequence

    itnode      *cit;
    bool        ok_to_axe;

    cit = findMatch( &ok_to_axe, NULL );
    if( cit != NULL ) {
        if( ( cit->opr == OPR_LBR ) && ok_to_axe ) {
            cit->is_catparen = 1;
            cit = CITNode;
            AdvanceITPtr();
            ReqNOpn();
            cit->link = CITNode->link;
            FreeOneNode( CITNode );
            CITNode = cit;
        } else {
            CatOpn();
        }
    }
}
Пример #22
0
void main(int argc, char *argv[])
{
    unsigned char buf[100];
    unsigned char notice[100];
    unsigned char fullName[100];
    unsigned char familyName[100];
    unsigned char weigth[100];
    unsigned char italic[100];
    unsigned char fixed[100];

    unsigned char foundry[100]  = "";
    unsigned char slant[100]  = "r";
    unsigned char width[100]  = "normal";


    for (;;) {
        getWord( buf, 99 );
        if (stricmp( buf, "/Notice" )==0)
            getString( notice, 99 );        else if (stricmp( buf, "/FullName" )==0)
            getString( fullName, 99 );
        else if (stricmp( buf, "/FamilyName" )==0)
            getString( familyName, 99 );
        else if (stricmp( buf, "/Weight" )==0)
            getString( weigth, 99 );
        else if (stricmp( buf, "/ItalicAngle" )==0)
            getWord( italic, 99 );
        else if (stricmp( buf, "/isFixedPitch" )==0)
            getWord( fixed, 99 );
        else if (stricmp( buf, "eexec" )==0)
            break;
        else {
//            if (buf[0]=='/')
//                printf( "%s\n", buf );
        }

    }


    lower( weigth );
    ConvertBuf( weigth, mapWeight );
    lower( fixed );
    ConvertBuf( fixed, mapFixed );
    if (atoi(italic)!=0)
        strcpy( slant, "i" );

    if (argc>1) {
        strcpy( buf, argv[1] );
        lower( buf );
    } else
        strcpy( buf, "" );

    lower( notice );
    findMatch( notice, foundry, mapFoundry );

    // Lets dig out as much as possible from fullName
    lower( fullName );
    findMatch( fullName, slant, mapSlant );
    findMatch( fullName, width, mapWidth );

    lower( familyName );

    printf( "%s -%s-%s-%s-%s-%s--0-0-0-0-%s-0-iso8859-1\n",
            buf, foundry, familyName, weigth, slant, width, fixed );

}
Пример #23
0
void PcreParser::handleToken(RegexpToken token)
{
    QRegExp rx;
    QRegExp characterClass;
    QRegExp bracketExpressionLiteral("[^\\\\[\\]\\.]|\\\\[^a-zA-Z0-9]");
    QRegExp bracketExpressionRange(_syntax[T_BRACKET_EXPRESSION_RANGE]);
    QRegExp flagClose;
    Token *openingToken;
    QString character;
    QString tmp;

    switch(token)
    {
    case T_LITERAL:
    case T_ALTERNATION:
    case T_ANY_CHARACTER:
    case T_STARTING_POSITION:
    case T_ENDING_POSITION:
    case T_BACKREFERENCE:
    case T_WORD:
    case T_NOT_WORD:
    case T_DIGIT:
    case T_NOT_DIGIT:
    case T_SPACE:
    case T_NOT_SPACE:
    case T_WORD_BOUNDARY:
    case T_NOT_WORD_BOUNDARY:
    case T_OCTAL_CHAR:
    case T_NAMED_BACKREFERENCE:
    case T_FIRST_MATCHING_POSITION:
    case T_START_OF_STRING:
    case T_END_OF_STRING:
    case T_END_OF_STRING_WITH_CLOSING_EOL:
    case T_ALNUM:
    case T_ALPHA:
    case T_BLANK:
    case T_CNTRL:
    case T_GRAPH:
    case T_LOWER:
    case T_PRINT:
    case T_PUNCT:
    case T_UPPER:
    case T_XDIGIT:
    case T_HORIZONTAL_WHITESPACE:
    case T_NOT_HORIZONTAL_WHITESPACE:
    case T_VERTICAL_WHITESPACE:
    case T_NOT_VERTICAL_WHITESPACE:
    case T_BELL:
    case T_BACKSPACE:
    case T_ESCAPE:
    case T_FORM_FEED:
    case T_LINE_FEED:
    case T_HORIZONTAL_TAB:
    case T_HEXADECIMAL_CHAR:
        _tokens.push_back(new Token(token, _expression.mid(_pos, _matchLength)));
        _pos += _matchLength;
        break;
    case T_GROUPING_OPEN:
    case T_REVERSED_CAPTURING_GROUPING_OPEN:
    case T_NAMED_GROUPING_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        rx.setPattern(_syntax[T_GROUPING_CLOSE]);

        while(rx.indexIn(_expression, _pos) != _pos && _pos < _expression.length())
            handleToken(findMatch());

        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_GROUPING_CLOSE, _expression.mid(_pos, 1)));
            _pos += 1;
        }
        else
            openingToken->setType(T_ERROR);
        break;
    case T_BRACKET_EXPRESSION_OPEN:
    case T_NEGATED_BRACKET_EXPRESSION_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        rx.setPattern(_syntax[T_BRACKET_EXPRESSION_CLOSE]);
        // Look for a "[]...]" or "[^]...]" including a literal close bracket in
        // the first position of the bracket expression
        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_LITERAL, _expression.mid(_pos, rx.matchedLength())));
            _pos += rx.matchedLength();
        }

        while(rx.indexIn(_expression, _pos) != _pos && _pos < _expression.length())
        {
            bool matched = false;
            if(matched == false && bracketExpressionRange.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_BRACKET_EXPRESSION_RANGE, _expression.mid(_pos, bracketExpressionRange.matchedLength())));
                _pos += bracketExpressionRange.matchedLength();
            }

            if(matched == false && bracketExpressionLiteral.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_LITERAL, _expression.mid(_pos, bracketExpressionLiteral.matchedLength())));
                _pos += bracketExpressionLiteral.matchedLength();
            }

            characterClass.setPattern(_syntax[T_WORD]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_WORD, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_NOT_WORD]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_NOT_WORD, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_DIGIT]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_DIGIT, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_NOT_DIGIT]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_NOT_DIGIT, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_SPACE]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_SPACE, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_NOT_SPACE]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_NOT_SPACE, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_WORD_BOUNDARY]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_WORD_BOUNDARY, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_NOT_WORD_BOUNDARY]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_NOT_WORD_BOUNDARY, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_BELL]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_BELL, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_ESCAPE]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_ESCAPE, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_FORM_FEED]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_FORM_FEED, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_LINE_FEED]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_LINE_FEED, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_HORIZONTAL_TAB]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_HORIZONTAL_TAB, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            characterClass.setPattern(_syntax[T_OCTAL_CHAR]);
            if(matched == false && characterClass.indexIn(_expression, _pos) == _pos)
            {
                matched = true;
                _tokens.push_back(new Token(T_OCTAL_CHAR, _expression.mid(_pos, characterClass.matchedLength())));
                _pos += characterClass.matchedLength();
            }

            if(!matched)
            {
                _tokens.push_back(new Token(T_ERROR, _expression.mid(_pos, 1)));
                ++_pos;
            }
        }

        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_BRACKET_EXPRESSION_CLOSE,
                                        _expression.mid(_pos, rx.matchedLength()))
                              );
            _pos += rx.matchedLength();
        }
        else
            openingToken->setType(T_ERROR);

        break;
    case T_POSITIVE_LOOKAHEAD_ASSERTION_OPEN:
    case T_NEGATIVE_LOOKAHEAD_ASSERTION_OPEN:
    case T_POSITIVE_LOOKBEHIND_ASSERTION_OPEN:
    case T_NEGATIVE_LOOKBEHIND_ASSERTION_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        rx.setPattern(_syntax[T_ASSERTION_CLOSE]);
        while(rx.indexIn(_expression, _pos) != _pos && _pos < _expression.length())
            handleToken(findMatch());

        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_ASSERTION_CLOSE, _expression.mid(_pos, 1)));
            _pos += 1;
        }
        else
            openingToken->setType(T_ERROR);
        break;
    case T_REPEAT_ZERO_OR_ONE:
    case T_REPEAT_ANY_NUMBER:
    case T_REPEAT_ONE_OR_MORE:
    case T_REPEAT_SPECIFIED:
    case T_REPEAT_ZERO_OR_ONE_NONGREEDY:
    case T_REPEAT_ANY_NUMBER_NONGREEDY:
    case T_REPEAT_ONE_OR_MORE_NONGREEDY:
    case T_REPEAT_SPECIFIED_NONGREEDY:
    case T_REPEAT_ZERO_OR_ONE_POSSESSIVE:
    case T_REPEAT_ANY_NUMBER_POSSESSIVE:
    case T_REPEAT_ONE_OR_MORE_POSSESSIVE:
    case T_REPEAT_SPECIFIED_POSSESSIVE:
        switch(_tokens[_tokens.size()-1]->type())
        {
        case T_POSITIVE_LOOKAHEAD_ASSERTION_OPEN:
        case T_NEGATIVE_LOOKAHEAD_ASSERTION_OPEN:
        case T_POSITIVE_LOOKBEHIND_ASSERTION_OPEN:
        case T_NEGATIVE_LOOKBEHIND_ASSERTION_OPEN:
        case T_REPEAT_ZERO_OR_ONE:
        case T_REPEAT_ANY_NUMBER:
        case T_REPEAT_ONE_OR_MORE:
        case T_REPEAT_SPECIFIED:
        case T_REPEAT_ZERO_OR_ONE_NONGREEDY:
        case T_REPEAT_ANY_NUMBER_NONGREEDY:
        case T_REPEAT_ONE_OR_MORE_NONGREEDY:
        case T_REPEAT_SPECIFIED_NONGREEDY:
        case T_REPEAT_ZERO_OR_ONE_POSSESSIVE:
        case T_REPEAT_ANY_NUMBER_POSSESSIVE:
        case T_REPEAT_ONE_OR_MORE_POSSESSIVE:
        case T_REPEAT_SPECIFIED_POSSESSIVE:
        case T_GROUPING_OPEN:
        case T_REVERSED_CAPTURING_GROUPING_OPEN:
        case T_NAMED_GROUPING_OPEN:
            _tokens.push_back(new Token(T_ERROR, _expression.mid(_pos, _matchLength)));
            _pos += _matchLength;
            break;
        case T_LITERAL:
            // Requires a bit of extra work to separate the last character from
            // the literal
            character = _tokens[_tokens.size()-1]->value().right(1);
            tmp = _tokens[_tokens.size()-1]->value();
            if(tmp.size() > 1)
            {
                tmp.truncate(tmp.length() - 1);
                _tokens[_tokens.size()-1]->setValue(tmp);
                _tokens.push_back(new Token(T_LITERAL, character));
            }
        default:
            _tokens.push_back(new Token(token, _expression.mid(_pos, _matchLength)));
            _pos += _matchLength;
        }
        break;
    case T_COMMENT_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        // Comments contain one literal comment message lasting up until the
        // next closing paren
        rx.setMinimal(true);
        rx.setPattern(QString(".*(?=") + _syntax[T_COMMENT_CLOSE] + ")");
        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_LITERAL, _expression.mid(_pos, rx.matchedLength())));
            _pos += rx.matchedLength();
        }

        rx.setPattern(_syntax[T_COMMENT_CLOSE]);
        if(rx.indexIn(_expression, _pos) != _pos)
            openingToken->setType(T_ERROR);
        else
        {
            _tokens.push_back(new Token(T_COMMENT_CLOSE, _expression.mid(_pos, rx.matchedLength())));
            _pos += rx.matchedLength();
        }
        break;
    case T_QUOTE_SEQUENCE_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        // Quote sequences are literal up until a closing \E
        rx.setMinimal(true);
        rx.setPattern(QString(".*(?=") + _syntax[T_QUOTE_SEQUENCE_CLOSE] + ")");
        if(rx.indexIn(_expression, _pos) == _pos)
        {
            _tokens.push_back(new Token(T_LITERAL, _expression.mid(_pos, rx.matchedLength())));
            _pos += rx.matchedLength();
        }

        rx.setPattern(_syntax[T_QUOTE_SEQUENCE_CLOSE]);
        if(rx.indexIn(_expression, _pos) != _pos)
            openingToken->setType(T_ERROR);
        else
        {
            _tokens.push_back(new Token(T_QUOTE_SEQUENCE_CLOSE, _expression.mid(_pos, rx.matchedLength())));
            _pos += rx.matchedLength();
        }
        break;
    case T_FLAGS_OPEN:
        openingToken = new Token(token, _expression.mid(_pos, _matchLength));
        _tokens.push_back(openingToken);
        _pos += _matchLength;

        // Flag sections can contain a-zA-Z- characters and end with a close
        // paren, if we encounter anything else then we'll stop trying to match
        // it as a flag and mark the opening as an error
        rx.setMinimal(true);
        rx.setPattern(QString("[a-zA-Z-]*") + _syntax[T_FLAGS_CLOSE]);
        if(rx.indexIn(_expression, _pos) != _pos)
            openingToken->setType(T_ERROR);
        else
        {
            flagClose.setPattern(_syntax[T_FLAGS_CLOSE]);
            while(flagClose.indexIn(_expression, _pos) != _pos)
            {
                bool matched = false;

                rx.setPattern(_syntax[T_FLAGS_NEGATION]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAGS_NEGATION, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_CASELESS]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_CASELESS, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_DOTALL]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_DOTALL, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_MULTILINE]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_MULTILINE, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_EXTENDED]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_EXTENDED, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_PCRE_EXTRA]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_PCRE_EXTRA, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_ANCHORED]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_ANCHORED, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                rx.setPattern(_syntax[T_FLAG_UNGREEDY]);
                if(!matched && rx.indexIn(_expression, _pos) == _pos)
                {
                    _tokens.push_back(new Token(T_FLAG_UNGREEDY, _expression.mid(_pos, rx.matchedLength())));
                    _pos += rx.matchedLength();
                    matched = true;
                }

                if(!matched)
                {
                    _tokens.push_back(new Token(T_ERROR, _expression.mid(_pos, 1)));
                    ++_pos;
                }
            }

            _tokens.push_back(new Token(T_FLAGS_CLOSE, _expression.mid(_pos, flagClose.matchedLength())));
            _pos += flagClose.matchedLength();
        }
        break;
    default:
        qDebug() << "Unknown token at position " << _pos << ": " << token;
        qDebug() << "Value: " << _expression.mid(_pos, _matchLength);
        _tokens.push_back(new Token(T_ERROR, _expression.mid(_pos, _matchLength)));
        _pos += _matchLength;
    }
}
GHOST_TSuccess GHOST_DisplayManagerWin32::setCurrentDisplaySetting(GHOST_TUns8 display, const GHOST_DisplaySetting& setting)
{
	GHOST_ASSERT((display==kMainDisplay), "GHOST_DisplayManagerWin32::setCurrentDisplaySetting(): only main display is supported");

	GHOST_DisplaySetting match;
	findMatch(display, setting, match);
	DEVMODE dm;
	int i = 0;
	while (::EnumDisplaySettings(NULL, i++, &dm)) {
		if ((dm.dmBitsPerPel == match.bpp) &&
			(dm.dmPelsWidth == match.xPixels) &&
			(dm.dmPelsHeight == match.yPixels) &&
			(dm.dmDisplayFrequency == match.frequency)) {
			break;
		}
	}
	/*
	dm.dmBitsPerPel = match.bpp;
	dm.dmPelsWidth = match.xPixels;
	dm.dmPelsHeight = match.yPixels;
	dm.dmDisplayFrequency = match.frequency;
	dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
	dm.dmSize = sizeof(DEVMODE);
	dm.dmDriverExtra = 0;
	*/
#ifdef GHOST_DEBUG
	printf("display change: Requested settings:\n");
	printf("  dmBitsPerPel=%d\n", dm.dmBitsPerPel);
	printf("  dmPelsWidth=%d\n", dm.dmPelsWidth);
	printf("  dmPelsHeight=%d\n", dm.dmPelsHeight);
	printf("  dmDisplayFrequency=%d\n", dm.dmDisplayFrequency);
#endif // GHOST_DEBUG

	LONG status = ::ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
#ifdef GHOST_DEBUG
	switch (status)
	{
	case DISP_CHANGE_SUCCESSFUL:
		printf("display change: The settings change was successful.\n");
		break;
	case DISP_CHANGE_RESTART:
		printf("display change: The computer must be restarted in order for the graphics mode to work.\n");
		break;
	case DISP_CHANGE_BADFLAGS:
		printf("display change: An invalid set of flags was passed in.\n");
		break;
	case DISP_CHANGE_BADPARAM:
		printf("display change: An invalid parameter was passed in. This can include an invalid flag or combination of flags.\n");
		break;
	case DISP_CHANGE_FAILED:
		printf("display change: The display driver failed the specified graphics mode.\n");
		break;
	case DISP_CHANGE_BADMODE:
		printf("display change: The graphics mode is not supported.\n");
		break;
	case DISP_CHANGE_NOTUPDATED:
		printf("display change: Windows NT: Unable to write settings to the registry.\n");
		break;
	default:
		printf("display change: Return value invalid\n");
		break;
	}
#endif // GHOST_DEBUG
	return status == DISP_CHANGE_SUCCESSFUL? GHOST_kSuccess : GHOST_kFailure;
}
Пример #25
0
void GLUTAPIENTRY
glutGameModeString(const char *string)
{
  Criterion *criteria;
  int ncriteria[4], requestedMask, queries = 1;
#if _WIN32
  int bpp, width, height, hertz, n;
#endif

  initGameModeSupport();
#if _WIN32
  XHDC = GetDC(GetDesktopWindow());
  bpp = GetDeviceCaps(XHDC, BITSPIXEL);
  /* Note that Windows 95 and 98 systems always return zero
     for VREFRESH so be prepared to ignore values of hertz
     that are too low. */
  hertz = GetDeviceCaps(XHDC, VREFRESH);
  width = GetSystemMetrics(SM_CXSCREEN);
  height = GetSystemMetrics(SM_CYSCREEN);
#endif
  criteria = parseGameModeString(string, &ncriteria[0], &requestedMask);

#if _WIN32
  /* Build an extra set of default queries.  If no pixel depth is
     explicitly specified, prefer a display mode that doesn't change
     the display mode.  Likewise for the width and height.  Likewise for
     the display frequency. */
  n = ncriteria[0];
  if (!(requestedMask & (1 << DM_PIXEL_DEPTH))) {
    criteria[n].capability = DM_PIXEL_DEPTH;
    criteria[n].comparison = EQ;
    criteria[n].value = bpp;
    n += 1;
    ncriteria[queries] = n;
    queries++;
  }
  if (!(requestedMask & ((1<<DM_WIDTH) | (1<<DM_HEIGHT)) )) {
    criteria[n].capability = DM_WIDTH;
    criteria[n].comparison = EQ;
    criteria[n].value = width;
    criteria[n].capability = DM_HEIGHT;
    criteria[n].comparison = EQ;
    criteria[n].value = height;
    n += 2;
    ncriteria[queries] = n;
    queries++;
  }
  /* Assume a display frequency of less than 50 is to be ignored. */
  if (hertz >= 50) {
    if (!(requestedMask & (1 << DM_HERTZ))) {
      criteria[n].capability = DM_HERTZ;
      criteria[n].comparison = EQ;
      criteria[n].value = hertz;
      n += 1;
      ncriteria[queries] = n;
      queries++;
    }
  }
#endif

  /* Perform multiple queries until one succeeds or no more queries. */
  do {
    queries--;
    currentDm = findMatch(dmodes, ndmodes, criteria, ncriteria[queries]);
  } while((currentDm == NULL) && (queries > 0));

  free(criteria);
}
Пример #26
0
bool isMatch(char* s, char* p) {
	int length = 0,posp = 0,hasStar = 0, poss = 0;//当前s 已经匹配到的位置

	int plen = strlen(p), slen = strlen(s);
	for (posp = 0; p[posp] != '\0'; posp++) {
		if (p[posp] == '*')	 {
			break;
		}
		buf[length++] = p[posp];
	}
	if (length > slen || (plen == length && slen > plen)) {
		return false;
	}
	for (int i = 0;i < length;i++) {
		if (buf[i] != '?' && buf[i] != s[i]) {
			return false;
		}
	}
	
	//检查前排
	poss = length;
	length = 0;
	for (posp = posp + 1; p[posp] != '\0' && posp < plen ;posp++) {
		if (p[posp] == '*') {
			hasStar = 1;
			if (length > 0) {
				poss = findMatch(s, poss,length)	;
				length = 0;
				if (poss == -1) {
					return false;
				}
			}
		} else {
			// 或者是 * 前面没有匹配上
			buf[length++] = p[posp];
			//return false;	
		}
	}
	if (length > 0) {
		/*
		if (hasStar == 0 && slen != strlen(p)) {
			return false;
		}
		*/
		//检验末尾的行,是不是正好
		slen = slen - length;
		if (slen < poss) {
			return false;
		}
		for (int j  = 0;s[slen] != '\0' && j < length;slen++,j++) {
			if (buf[j] != '?' && buf[j] != s[slen]) {
				return false;
			}
		}
		/*
		poss = findMatch(s, poss,length);
		if (poss == -1 ) {
			//没有匹配就是错的
			return false;
		}
		//匹配完了,就是对的
		if (s[poss] == '\0') {
			return true;
		}
		//没有匹配完,但是最后的都是?,可以随意放置
		for (int i = 0;i < length;i++) {
			if (buf[i] != '?') {
				return false;
			}
		}
		*/
	}
	return true;
	//return check(s, p, 0, 0);
}
Пример #27
0
void ShtServer::onTextMessage(QString msg)
{
    QElapsedTimer totalTime;
    totalTime.start();

    QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
    qWarning() << "received: " << msg << "from " << socket->peerName();

    //Json
    QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8());
    if(!doc.isObject()){
        socket->sendTextMessage("json or gtfo");
        return;
    }

    QJsonObject docObj = doc.object();
    int r = docObj["request"].toInt();
    switch(r){
    case 0:     //LOGIN
    {
        QString uuid = docObj["uuid"].toString();
        User* u = dbManager->findUserByUuid(uuid);
        if(!u){
            //DEFAULTS FOR NEW USERS
           u = new User();
           u->setUuid(QUuid::createUuid().toString());
           u->setName("anonimo");
           u->setEmail("");
           u->setMatches(0);
           u->setKilos(0);
           u->setState(User::AVAILABLE);
           u->setAvatar("263a");
           dbManager->addUser(u);

           u->setSocket(socket);
        }
        usersBySocket.insert(socket, u);

        QJsonObject obj = u->getJsonObject();
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray msg = doc.toJson(QJsonDocument::Compact);
        socket->sendTextMessage(msg);
    }break;

    case 1:     //GET MATCHES
    {
        User *u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "WARNING: getMatches from unknown user";
            break;
        }

        QJsonArray matchesList;
        for(Match* m: matches){
            QJsonObject matchObj = m->getJsonObject();
            matchesList.append(matchObj);
        }

        QJsonObject obj;
        obj["request"] = 1;
        obj["matchesList"] = matchesList;
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray msg = doc.toJson(QJsonDocument::Compact);
        socket->sendTextMessage(msg);
    }break;
    case 2:     //CREATE MATCH
    {
        User* u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "ERROR: createMatch() user not found";
            break;
        }

        if(u->getPendingMatch() != NULL){
            qWarning() << "SKIPPING: user already has a match pending";
            break;
        }

        Match *m = new Match(this);
        m->init(u);
        m->addPlayer(u);
        matches.append(m);
        u->setPendingMatch(m);

        QJsonObject obj;
        obj["request"] = 2;
        obj["result"] = "ok";
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray msg = doc.toJson(QJsonDocument::Compact);
        socket->sendTextMessage(msg);
        connect(m, &Match::finished, this, &ShtServer::onMatchFinished);
    }break;
    case 3:     //JOIN MATCH
    {
        User* u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "ERROR: joinMatch() user not found";
            break;
        }

        Match* m = findMatch(docObj["uuid"].toString());
        if(!m){
            qWarning() << "ERROR: match not found";
            break;
        }
        m->addPlayer(u);
        u->setPendingMatch(m);
    }break;
    case 4:     //LEAVE MATCH
    {
        User* u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "ERROR: leaveMatch() user not found";
            break;
        }

        Match* m = findMatch(docObj["uuid"].toString());
        if(!m){
            qWarning() << "ERROR: match not found";
            break;
        }
        m->leavePlayer(u);
    }break;
    case 5:     //PASS CARD
    {
        User* u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "ERROR: passCard user not found";
            break;
        }

        Match* m = findMatch(docObj["uuid"].toString());
        if(!m){
            qWarning() << "ERROR: match not found";
            break;
        }
        m->passCard(u, docObj["card"].toString());
    }break;
    case 6:     //START MATCH
    {
        User* u = usersBySocket.value(socket);
        if(!u){
            qWarning() << "ERROR: matchStart user not found";
            break;
        }

        Match* m = findMatch(docObj["uuid"].toString());
        if(!m){
            qWarning() << "ERROR: match not found";
            break;
        }

        //Only match creator can start the match
        if(m->state()==Match::INIT && m->getOwner() == u){
            m->start();
        } else {
            u->sendMessage("match_server", "start_game", "denied", "");
        }

    }break;

    default:
        break;
    }
    qWarning() << "Request " << r << " evaded in " << totalTime.elapsed() << "ms";
}
Пример #28
0
int main( const int argc, const char const *argv[] )
{
     static nst_save_state_s  empty_save_state = { 0 };
     const  char             *rom_filename     = NULL;
     const  char             *ss_filename      = NULL;

     tsbrom_s         *rom            = NULL;
     nst_save_state_s *save_state     = NULL;
     nst_matchup_s    *match          = NULL;
     unsigned char    *state_file     = NULL;
     organization_s   *organization   = NULL;
     team_s           *road_team      = NULL;
     team_s           *home_team      = NULL;
     int               save_state_len = 0;


     if ( argc != 3 )
     {
          printf( "Usage: %s <rom_file> <save_state_file>\n", argv[0] );

          return EXIT_SUCCESS;
     }

     rom_filename = argv[1];
     ss_filename  = argv[2];

     if ( (rom = readTsbRom( rom_filename )) == NULL )
     {
          printf( "Error reading rom: %s\n", getFileUtilsError() );

          return EXIT_FAILURE;
     }

     if ( (state_file = readNstSaveState( ss_filename, &save_state_len )) == NULL )
     {
          printf( "Error reading Save State: %s\n", getFileUtilsError() );

          free( rom );

          return EXIT_FAILURE;
     }

     if ( (save_state = getSaveStateStats( state_file, save_state_len )) == NULL )
     {
          printf( "Error retrieving stats from Save State: %s\n", getFileUtilsError() );

          free( rom        );
          free( state_file );

          return EXIT_FAILURE;
     }

     if ( (organization = convertOrganization( rom, &empty_save_state, rom, &empty_save_state, 0, bg_None )) == NULL )
     {
          printf( "Error converting rom and save state data: %s\n", getConvertOrganizationError() );

          free( rom        );
          free( state_file );

          return EXIT_FAILURE;
     }

     if ( (match = findMatch( save_state )) == NULL )
     {
          printf( "Unable to retrieve match\n" );

          free( rom        );
          free( state_file );

          free_organization( organization );

          return EXIT_FAILURE;
     }

     if ( (road_team = findTeam( organization, match->road[0] )) == NULL )
     {
          printf( "Road team <%d> not found in rom\n", match->road[0] );

          free( rom        );
          free( state_file );

          free_organization( organization );

          return EXIT_FAILURE;
     }

     if ( (home_team = findTeam( organization, match->home[0] )) == NULL )
     {
          printf( "Home team <%d> not found in rom\n", match->home[0] );

          free( rom        );
          free( state_file );

          free_organization( organization );

          return EXIT_FAILURE;
     }

     loadGameStats( road_team, home_team, save_state, state_file );

     printBoxscore( road_team, home_team, save_state );

     free( rom        );
     free( state_file );

     free_organization( organization );

     return EXIT_SUCCESS;
}
Пример #29
0
const LCDbTankMap * LCDbTankMaps::findCurrent( int pTankCID ) const
{
	return findMatch( Matcher( pTankCID ) );
}