int isProperPipe(char** args){
	int size = len2(args);
	if(countPipes(args) != 1){	//Only a single pipe symbol for 2-stage pipeline
		return 0;
	}
	if(compareStrings(args[0], "|")|| compareStrings(args[size - 1], "|")){
		return 0;				//Make sure pipes aren't in front or back.
	}
	return 1;
}
int main(void)
{
    char string1[] = "I am an elephant";
    char string2[] = "I am a";

    printf("%i\n", compareStrings(string1, string2));
    printf("%i\n", compareStrings(string2, "I am a"));
    printf("%i\n", compareStrings(string2, "I am a spoon"));
    printf("%i\n", compareStrings("I am b", "I am e"));

    return 0;
}
/*
int isProperRedirection()
	Description:
		Tells whether or not a command is a functioning redirection.
	args:
		char** args
			Array of tokens
	return:
		1 if true, 0 if false.
*/
int isProperRedirection(char** args){
	int size = len2(args);
	if(countRedirections(args) > 2){
		return 0;
	}
	if(compareStrings(args[0],"<") || compareStrings(args[0],">") || 
	   compareStrings(args[size - 1],"<") || compareStrings(args[size - 1],">"))
	{
		return 0;
	}
	return 1;
}
Пример #4
0
int main (void)
{
    const char string1[] = "HOLA";
    const char string2[] = "ADIOS";
    const char string3[] = "HOLA";

    printf("Result of comparing \"%s\" and \"%s\" is: %i.\n", string1, 
string2, compareStrings(string1, string2));
    printf("Result of comparing \"%s\" and \"%s\" is: %i.\n", string1, 
string3, compareStrings(string1, string3));
    printf("Result of comparing \"%s\" and \"%s\" is: %i.\n", string2, 
string3, compareStrings(string2, string3));

    return 0;
}
Пример #5
0
/* Comparator function for pointers to fileRecord structures. */
int compareRecordName(void *p1, void *p2)
{
	struct fileRecord *t1 = (struct fileRecord*)p1;
	struct fileRecord *t2 = (struct fileRecord*)p2;

	return compareStrings(t2->filename,t1->filename);
}
Пример #6
0
bool StrList::find(const char* str, int& index) const
{
	if (!isSorted_)
	{
		index = indexOf(str);
		return (index >= 0);
	}

	bool result = false;
	int l, h, i, c;

	l = 0;
	h = count_ - 1;
	while (l <= h)
	{
		i = (l + h) >> 1;
		c = compareStrings(stringObjectNeeded(i).c_str(), str);
		if (c < 0)
			l = i + 1;
		else
		{
			h = i - 1;
			if (c == 0)
			{
				result = true;
				if (dupMode_ != DM_ACCEPT)
					l = i;
			}
		}
	}

	index = l;
	return result;
}
Пример #7
0
void RecipeActionsHandler::mergeSimilar()
{
	QList<Q3ListViewItem> items = parentListView->selectedItems();
	if ( items.count() > 1 )
		KMessageBox::sorry( kapp->mainWidget(), i18nc("@info", "Please select only one category."), QString() );
	else if ( items.count() == 1 && items.at(0)->rtti() == 1001 ) {
		CategoryListItem * cat_it = ( CategoryListItem* ) items.at(0);
		QString name = cat_it->categoryName();
		const double max_allowed_distance = 0.60;
		const int length = name.length();
		ElementList categories;
		database->loadCategories( &categories );

		ElementList matches;
		for ( ElementList::const_iterator it = categories.begin(); it != categories.end(); ++it ) {
			#if 0
			if ( levenshtein_distance(name.toLatin1(),(*it).name.toLatin1())/double(qMax(length,(*it).name.length())) >= max_allowed_distance ) {
			#else
			if ( compareStrings(name,(*it).name) >= max_allowed_distance ) {
			#endif
				kDebug()<<(*it).name<<" matches";
				if ( cat_it->categoryId() != (*it).id )
					matches.append(*it);
			}
		}


		for ( ElementList::const_iterator it = categories.begin(); it != categories.end(); ++it ) {
			database->mergeCategories(cat_it->categoryId(),(*it).id);
		}

	}
	else //either nothing was selected or a recipe was selected
Пример #8
0
int ReadDir(char* dirPath)
{
    char *dirPATH = dirPath; /*string contains directory path*/
    char *fileAccesPath; /*string containing file path */
    DIR *dirStream; /*directory stream */
    struct dirent *readDir;
    /*if file hash it*/
    if(access(dirPATH, F_OK) ==-1)
    {
		printf("Directory or file doesn't exist\n");
		return 0;
	}
    if((dirStream = opendir(dirPATH)) == 0)
    {
        hashToken(dirPATH);
        return 0;
    }
    
    /*search through the file system to find and read all files*/
    while((readDir = readdir(dirStream)) != 0)
    {
        if(readDir->d_type == DT_REG && compareStrings(readDir->d_name, ".DS_Store")) /*not hidden file*/
        {
			fileAccesPath = dirPATH;
			fileAccesPath = Concat(dirPATH, '/');/*add "/" to string in dirPath*/
			fileAccesPath = ConcatStr(fileAccesPath, readDir->d_name);
			hashToken(fileAccesPath);
		}
		else if(readDir->d_type == DT_DIR)/*it is a directory*/
		{
			if(!compareStrings(readDir->d_name,".") || !compareStrings(readDir->d_name,".."))
            {	/*if directory is a . or .. skip it*/
				continue;

			}
			else
            {
				dirPATH = Concat(dirPATH, '/');
				dirPATH = ConcatStr(dirPATH, readDir->d_name);	/*concatenate "/" and directory name for recursing*/
				ReadDir(dirPATH);
				dirPATH = dirPath;	/*after recursing reset path to current directory*/
			}
		}
    }
    closedir(dirStream);
	return 0;
}
Пример #9
0
void blueToothHandle(void)
{
	if(copiedData[0] == '+')
	{
		if(compareStrings("+RDII\r\n"))
		{
			turnOnLeftDiode();
		}
	}
}
struct symbol* addSymbol(struct symbol* node, char* symbol_name)
{
	/* We've reached a node that's unallocated, it will be our new leaf */
	if (node == NULL)
	{
		printf("win?\n");
		struct symbol* root = (struct symbol*)malloc(sizeof(struct symbol));

		root->symbol_name = symbol_name;

		return root;
	}

	/* Compare strings so we know where to put our new node */
	enum ComparisonValue comparison = compareStrings(symbol_name, node->symbol_name);

	if (comparison == LESS_THAN)
	{
		/* if left is open, put it there, else, let's kill going down the tree */
		if (node->left == NULL)
		{
			node->left = (struct symbol*)malloc(sizeof(struct symbol));

			node->left->symbol_name = symbol_name;

			return node->left;
		}
		else
		{
			return addSymbol(node->left, symbol_name);
		}

	} 
	else if (comparison == GREATER_THAN)
	{
		/* if right is open, put it there, else, let's kill going down the tree */
		if (node->right == NULL)
		{
			node->right = (struct symbol*)malloc(sizeof(struct symbol));

			node->right->symbol_name = symbol_name;

			return node->right;
		}
		else
		{
			return addSymbol(node->right, symbol_name);
		}

	}
	else /* comparison is equal */
	{
		return NULL;
	}
}
string DoublyLinkedListPriorityQueue::dequeueMin() {
    if (isEmpty())
        error ("Queue is empty");
    
    // finding the minimum
    Entry *min, * curr;
    
    min = list;
    for ( curr = list -> next; curr != NULL; curr = curr -> next){
        if (compareStrings(min -> name, curr -> name) < 0){
            min = curr;
        }
    }
    string nameValue = min -> name;
    
    // splicing out the min element and readjusting the pointers
    
     // special case if min is the last element
    if (min -> next == NULL && size() != 1){
        min -> previous -> next = NULL;
        min -> previous = NULL;
        delete min;
        number--;
        
    }
    // special case if min is the first element
    else if (min -> previous == NULL && size() != 1){
        min -> next -> previous = NULL;
        list = list -> next;
        delete min;
        number--;
        
    }
    // special case if size is 1
    else if (size() == 1){
        list = NULL;
        delete min;
        number--;
    }
    // for all other cases
    else {
    min -> next -> previous = min -> previous;
    min -> previous -> next = min -> next;
        min -> next = NULL;
        min -> previous = NULL;
        delete min;
        number--;
    }
    
    
    return nameValue;
}
void LinkedListPriorityQueue::InsertSorted(Entry * &list,  Entry *newOne){
    
    //Base case
    
    if(list==NULL || (compareStrings(list -> name, newOne -> name) < 0)){
        
        newOne -> next = list;
        list = newOne;
        
    } else
        InsertSorted(list -> next, newOne);      // Recursive Case
    
}
Пример #13
0
int Strings::indexOfName(const char* name) const
{
	int result = -1;

	for (int i = 0; i < getCount(); i++)
		if (compareStrings((extractName(getString(i).c_str()).c_str()), name) == 0)
		{
			result = i;
			break;
		}

	return result;
}
Пример #14
0
/* Comparator function for pointers to fileRecord structures. */
int compareRecordStructs(void *p1, void *p2)
{
	struct fileRecord *t1 = (struct fileRecord*)p1;
	struct fileRecord *t2 = (struct fileRecord*)p2;

	int i1 = t1->frequency;
	int i2 = t2->frequency;

	if((i1-i2)==0){
		return compareStrings(t2->filename,t1->filename);
	}else
		return i1-i2;
}
Пример #15
0
int Strings::indexOf(const char* str) const
{
	int result = -1;

	for (int i = 0; i < getCount(); i++)
		if (compareStrings(getString(i).c_str(), str) == 0)
		{
			result = i;
			break;
		}

	return result;
}
Пример #16
0
static String addPooledString (Array<String>& strings, const NewStringType& newString)
{
    int start = 0;
    int end = strings.size();

    while (start < end)
    {
        const String& startString = strings.getReference (start);
        const int startComp = compareStrings (newString, startString);

        if (startComp == 0)
            return startString;

        const int halfway = (start + end) / 2;

        if (halfway == start)
        {
            if (startComp > 0)
                ++start;

            break;
        }

        const String& halfwayString = strings.getReference (halfway);
        const int halfwayComp = compareStrings (newString, halfwayString);

        if (halfwayComp == 0)
            return halfwayString;

        if (halfwayComp > 0)
            start = halfway;
        else
            end = halfway;
    }

    strings.insert (start, newString);
    return strings.getReference (start);
}
Пример #17
0
NonPlayerCharacter::NonPlayerCharacter(TiXmlElement* xml, Game * game, b2Vec2 origin) : Character(xml, game, origin) {
    loadFromXml(xml, origin);

	targetCharacter = -1;

	aiPatternsCount = 0;
	aiPatterns = new int[10];

    traverseMove = 0;

	for (int i = 0; i < movesCount; i++) {
        if ( compareStrings(moveNames[i], "traverse") ) {
            traverseMove = i;
            break;
        }
	}
}
string DoublyLinkedListPriorityQueue::peek() {
	if (isEmpty())
        error ("Queue is empty");
    
    // finding the minimum
    Entry *min, * curr;
    
    min = list;
    for ( curr = list -> next; curr != NULL; curr = curr -> next){
        if (compareStrings(min -> name, curr -> name) < 0){
            min = curr;
        }
    }
    
	
	return min -> name;
}
Пример #19
0
void dictionarySort(struct entry dict[], int entries)
{
    struct entry temp;
    bool swapped;

    do
    {
        swapped = false;

        for ( int i = 0; i < entries - 1; i++ )
        {
            if ( compareStrings(dict[i].word, dict[i+1].word) == 1 )
            {
                temp = dict[i];
                dict[i] = dict[i+1];
                dict[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}
Пример #20
0
int lookup (const struct entry dictionary[], const char search[], const int entries)
{
  int low = 0;
  int high = entries - 1;
  int mid, result;
  bool compareStrings(const char s1[], const char s2[]);

  while ( low <= high )
  {
    mid = (low + high) / 2;
    result = compareStrings (dictionary[mid].word, search);
    if ( result == -1 )
      low = mid + 1;
    else if ( result == 1 )
      high = mid - 1;
    else
      return mid;
  }

  return -1;
}
Пример #21
0
main()
{
	char str1[64], str2[64];
	char ch;

	//string comparison
       	printf("\nString Compare:\nstr1: "); readString(str1);
	printf("str2: "); readString(str2);
	printf("Are equal? %d\n\n", compareStrings(str1, str2));
	
	//Substring Check
	printf("Substring Check:\nstr1: "); readString(str1);
	printf("str2: "); readString(str2);
	printf("Is Substring? %d\n\n", searchSubString(str1, str2));
	
	//Check for char
	printf("Search for char:\nstr1: "); readString(str1);
	printf("char: "); ch = getchar();
	printf("Found char? %d", searchForChar(str1, ch)); 

	return 0;
}
Пример #22
0
int lookup(const struct entry dictionary[],const char search[],const int entries)
{
  int i;
  int low=0;
  int high = entries-1;
  int mid,result;
  while(low<=high)
    {
      mid=(low+high)/2;
      result=compareStrings(dictionary[mid].word,search);
      //here we used string 1 as the dictionary word
      //and string 2 as the word we need to search

      if(result==-1)
        low=mid+1;
      else if(result==1)
          high=mid-1;
      else
          return mid; //found it at the mid
    }
  return -1; //not found at all
}
// Check function prologue with know prologues from the dictionary
// opcodes - dictionary
// inpAddr - pointer to function prologue
// Dictionary contains opcodes for several full asm instructions
// + one opcode byte for the next asm instruction for safe address processing
// RETURN: number of bytes for safe bytes replacement 
// (matched_pattern/2-1)
UINT CheckOpcodes( const char ** opcodes, void *inpAddr )
{
    static size_t opcodesStringsCount = 0;
    static size_t maxOpcodesLength = 0;
    static size_t opcodes_pointer = (size_t)opcodes;
    char opcodeString[61];
    size_t i;
    size_t result;

    // Get the values for static variables
    // max length and number of patterns
    if( !opcodesStringsCount || opcodes_pointer != (size_t)opcodes ){
        while( *(opcodes + opcodesStringsCount)!= NULL ){
            if( (i=strlen(*(opcodes + opcodesStringsCount))) > maxOpcodesLength ) 
                maxOpcodesLength = i;
            opcodesStringsCount++;
        }
        opcodes_pointer = (size_t)opcodes;
        __TBB_ASSERT( maxOpcodesLength < 61, "Limit is 30 opcodes/60 symbols per pattern" );
    }

    // Translate prologue opcodes to string format to compare
    for( i=0; i< maxOpcodesLength/2; i++ ){
        sprintf( opcodeString + 2*i, "%.2X", *((unsigned char*)inpAddr+i) ); 
    }
    opcodeString[maxOpcodesLength] = 0;
    
    // Compare translated opcodes with patterns
    for( i=0; i< opcodesStringsCount; i++ ){
        result = compareStrings( opcodes[i],opcodeString );
        if( result ) 
            return (UINT)(result/2-1);
    }
    // TODO: to add more stuff to patterns
    __TBB_ASSERT( false, "CheckOpcodes failed" );

    // No matches found just do not store original calls
    return 0;
}
Пример #24
0
int lookup (const struct entry1 dictionary[], const char search[], const int entries){
    int low = 0;
    int high = entries -1;
    int mid, result;
    int compareStrings(const char s1[], const char s2[]);
    
    
    while(low <= high){
        // take the average of the high and low
        // (0 + 10) / 2 = 5
        mid = (low + high) / 2;
        // use the average to find the middle dictionary word
        // return where the searched word is relative to the middle word
        result = compareStrings(dictionary[mid].word, search);
        
        // if the dictionary word is before the searched word
        // search the top half
        if(result == -1)
            // low = 5 + 1
            // high remains the same = 10
            low = mid +1;
        
        else if ( result == 1)
            // if the dictionary word comes after the search word
            // search the bottom half
            // high = 5 - 1
            // low remains 0
            high = mid - 1;
        
        else
            // else the word index has been found
            // end the loop and return the index
            return mid;
    }
    
    return -1;
}
Пример #25
0
static void
printRecords(
    const rwRec         rec[])
{
    char starttime[2][RWCOMPARE_BUFSIZ];
    uint32_t elapsed[2];
    uint32_t sport[2];
    uint32_t dport[2];
    uint32_t proto[2];
    uint32_t flowtype[2];
    uint32_t sensor[2];
    uint32_t flags[2];
    uint32_t initflags[2];
    uint32_t restflags[2];
    uint32_t tcpstate[2];
    uint32_t application[2];
    uint32_t memo[2];
    uint32_t input[2];
    uint32_t output[2];
    uint32_t pkts[2];
    uint32_t bytes[2];
    char sip[2][RWCOMPARE_BUFSIZ];
    char dip[2][RWCOMPARE_BUFSIZ];
    char nhip[2][RWCOMPARE_BUFSIZ];
    skipaddr_t ip;
    unsigned i;

    for (i = 0; i < 2; ++i) {
        sktimestamp_r(
            starttime[i], rwRecGetStartTime(&rec[i]), SKTIMESTAMP_EPOCH);
        elapsed[i] = rwRecGetElapsed(&rec[i]);
        sport[i] = rwRecGetSPort(&rec[i]);
        dport[i] = rwRecGetDPort(&rec[i]);
        proto[i] = rwRecGetProto(&rec[i]);
        flowtype[i] = rwRecGetFlowType(&rec[i]);
        sensor[i] = rwRecGetSensor(&rec[i]);
        flags[i] = rwRecGetFlags(&rec[i]);
        initflags[i] = rwRecGetInitFlags(&rec[i]);
        restflags[i] = rwRecGetRestFlags(&rec[i]);
        tcpstate[i] = rwRecGetTcpState(&rec[i]);
        application[i] = rwRecGetApplication(&rec[i]);
        memo[i] = rwRecGetMemo(&rec[i]);
        input[i] = rwRecGetInput(&rec[i]);
        output[i] = rwRecGetOutput(&rec[i]);
        pkts[i] = rwRecGetPkts(&rec[i]);
        bytes[i] = rwRecGetBytes(&rec[i]);
        rwRecMemGetSIP(&rec[i], &ip);
        skipaddrString(sip[i], &ip, SKIPADDR_HEXADECIMAL);
        rwRecMemGetDIP(&rec[i], &ip);
        skipaddrString(dip[i], &ip, SKIPADDR_HEXADECIMAL);
        rwRecMemGetNhIP(&rec[i], &ip);
        skipaddrString(nhip[i], &ip, SKIPADDR_HEXADECIMAL);
    }

    compareStrings("StartTime", starttime);
    compareNumbers("Elapsed", elapsed);
    compareNumbers("SPort", sport);
    compareNumbers("DPort", dport);
    compareNumbers("Proto", proto);
    compareNumbers("FlowType", flowtype);
    compareNumbers("Sensor", sensor);
    compareNumbers("Flags", flags);
    compareNumbers("InitFlags", initflags);
    compareNumbers("RestFlags", restflags);
    compareNumbers("TcpState", tcpstate);
    compareNumbers("Application", application);
    compareNumbers("Memo", memo);
    compareNumbers("Input", input);
    compareNumbers("Output", output);
    compareNumbers("Pkts", pkts);
    compareNumbers("Bytes", bytes);
    compareStrings("SIP", sip);
    compareStrings("DIP", dip);
    compareStrings("NhIP", nhip);
}
Пример #26
0
static int evalCondition(const char *leftSide, Comparator cmpOp, const char *rightSide, KeySet *ks, Key *parentKey)
{
	char *lookupName = NULL;
	char *compareTo = NULL;
	Key *key;
	int len;
	long result = 0;
	if(rightSide[0] == '\'')
	{
		char *endPos = strchr(rightSide+1, '\'');
		if(!endPos)
		{
			result = -1;
			goto Cleanup;
		}
		if(elektraRealloc((void **)&compareTo, endPos-rightSide) < 0)
		{
			ELEKTRA_SET_ERROR(87, parentKey, "Out of memory");
			result = -1;
			goto Cleanup;
		}
		memset(compareTo, 0, endPos-rightSide);
		strncat(compareTo, rightSide+1, endPos-rightSide-1);
	}
	else if(rightSide && elektraStrLen(rightSide) > 1)
	{
		len = keyGetNameSize(parentKey)+elektraStrLen(rightSide);
		if(elektraRealloc((void **)&lookupName, len) < 0)
		{
			ELEKTRA_SET_ERROR(87, parentKey, "Out of memory");
			result = -1;
			goto Cleanup;
		}
		snprintf(lookupName, len, "%s/%s", keyName(parentKey), rightSide);
		key = ksLookupByName(ks, lookupName, 0);
		if(!key)
		{
			ELEKTRA_SET_ERRORF(133, parentKey, "Key %s doesn't exist", lookupName);
			result = -1;
			goto Cleanup;
		}
		if(elektraRealloc((void **)&compareTo, keyGetValueSize(key)) < 0)
		{
			ELEKTRA_SET_ERROR(87, parentKey, "Out of memory");
			result = -1;
			goto Cleanup;
		}
		strcpy(compareTo, keyString(key));
	}

	len = keyGetNameSize(parentKey)+elektraStrLen(leftSide);
	if(elektraRealloc((void **)&lookupName, len) < 0)
	{
		ELEKTRA_SET_ERROR(87, parentKey, "Out of memory");
		result = -1;
		goto Cleanup;
	}
	snprintf(lookupName, len, "%s/%s", keyName(parentKey), leftSide);
	key = ksLookupByName(ks, lookupName, 0);
	if(!key)
	{
		ELEKTRA_SET_ERRORF(133, parentKey, "Key %s doesn't exist", lookupName);
		result = -1;
		goto Cleanup;
	}
	long ret;
	ret = compareStrings(keyString(key), compareTo);
	switch(cmpOp)
	{
		case EQU:
			if(!ret)
				result = 1;
			break;
		case NOT:
			if(ret)
				result = 1;
			break;
		case LT:
			if(ret < 0)
				result = 1;
			break;
		case LE:
			if(ret <= 0)
				result = 1;
			break;
		case GT:
			if(ret > 0)
				result = 1;
			break;
		case GE:
			if(ret >= 0)
				result = 1;
			break;
		case SET:
			keySetString(key, compareTo);
			result = 1;
			break;
		default:
			result = -1;
			break;
	}
//freeing allocated heap
Cleanup:
	if(lookupName)
		elektraFree(lookupName);
	if(compareTo)
		elektraFree(compareTo);
	return result;
}
Пример #27
0
static CondResult evalCondition (const Key * curKey, const char * leftSide, Comparator cmpOp, const char * rightSide,
				 const char * condition, const Key * suffixList, KeySet * ks, Key * parentKey)
{
	char * lookupName = NULL;
	char * compareTo = NULL;
	Key * key;
	int len;
	long result = 0;
	if (rightSide)
	{
		if (rightSide[0] == '\'')
		{
			// right side of the statement is a literal enclosed by ''
			char * endPos = strchr (rightSide + 1, '\'');
			if (!endPos)
			{
				result = ERROR;
				goto Cleanup;
			}
			if (elektraRealloc ((void **) &compareTo, endPos - rightSide) < 0)
			{
				ELEKTRA_SET_ERROR (87, parentKey, "Out of memory");
				result = ERROR;
				goto Cleanup;
			}
			memset (compareTo, 0, endPos - rightSide);
			strncat (compareTo, rightSide + 1, endPos - rightSide - 1);
		}
		else if (rightSide && elektraStrLen (rightSide) > 1)
		{
			// not a literal, it has to be a key
			if (rightSide[0] == '@')
				len = keyGetNameSize (parentKey) + elektraStrLen (rightSide);
			else if (!strncmp (rightSide, "..", 2) || (rightSide[0] == '.'))
				len = keyGetNameSize (curKey) + elektraStrLen (rightSide);
			else
				len = elektraStrLen (rightSide);

			if (elektraRealloc ((void **) &lookupName, len) < 0)
			{
				ELEKTRA_SET_ERROR (87, parentKey, "Out of memory");
				result = ERROR;
				goto Cleanup;
			}
			if (rightSide[0] == '@')
				snprintf (lookupName, len, "%s/%s", keyName (parentKey), rightSide + 1);
			else if (rightSide[0] == '.') // either starts with . or .., doesn't matter at this point
				snprintf (lookupName, len, "%s/%s", keyName (curKey), rightSide);
			else
				snprintf (lookupName, len, "%s", rightSide);

			key = ksLookupByName (ks, lookupName, 0);
			if (!key)
			{
				if (!keyGetMeta (parentKey, "error"))
				{
					ELEKTRA_SET_ERRORF (133, parentKey, "Key %s not found but is required for the evaluation of %s",
							    lookupName, condition);
				}
				result = FALSE;
				goto Cleanup;
			}
			if (elektraRealloc ((void **) &compareTo, keyGetValueSize (key)) < 0)
			{
				ELEKTRA_SET_ERROR (87, parentKey, "Out of memory");
				result = ERROR;
				goto Cleanup;
			}
			strcpy (compareTo, keyString (key));
		}
	}
	if (leftSide[0] == '@')
		len = keyGetNameSize (parentKey) + elektraStrLen (leftSide);
	else if (!strncmp (leftSide, "..", 2) || (leftSide[0] == '.'))
		len = keyGetNameSize (curKey) + elektraStrLen (leftSide);
	else
		len = elektraStrLen (leftSide);

	if (elektraRealloc ((void **) &lookupName, len) < 0)
	{
		ELEKTRA_SET_ERROR (87, parentKey, "Out of memory");
		result = ERROR;
		goto Cleanup;
	}
	if (leftSide[0] == '@')
		snprintf (lookupName, len, "%s/%s", keyName (parentKey), leftSide + 1);
	else if (leftSide[0] == '.') // either . or .., doesn't matter here
		snprintf (lookupName, len, "%s/%s", keyName (curKey), leftSide);
	else
		snprintf (lookupName, len, "%s", leftSide);
	key = ksLookupByName (ks, lookupName, 0);
	if (cmpOp == NEX)
	{
		if (key)
			result = FALSE;
		else
			result = TRUE;
		goto Cleanup;
	}
	if (!key && cmpOp != OR && cmpOp != AND)
	{
		if (!keyGetMeta (parentKey, "error"))
		{
			ELEKTRA_SET_ERRORF (133, parentKey, "Key %s not found but is required for the evaluation of %s", lookupName,
					    condition);
		}
		result = FALSE;
		goto Cleanup;
	}
	long ret;
	if (cmpOp == OR || cmpOp == AND)
		ret = compareStrings (leftSide, rightSide, NULL);
	else
		ret = compareStrings (keyString (key), compareTo, suffixList);
	switch (cmpOp)
	{
	case EQU:
		if (!ret) result = TRUE;
		break;
	case NOT:
		if (ret) result = TRUE;
		break;
	case LT:
		if (ret < 0) result = TRUE;
		break;
	case LE:
		if (ret <= 0) result = TRUE;
		break;
	case GT:
		if (ret > 0) result = TRUE;
		break;
	case GE:
		if (ret >= 0) result = TRUE;
		break;
	case SET:
		keySetString (key, compareTo);
		result = TRUE;
		break;
	case AND:
		if (ret == 0 && !strcmp (leftSide, "'1'")) result = TRUE;
		break;
	case OR:
		if (!strcmp (leftSide, "'1'") || (rightSide && !strcmp (rightSide, "'1'"))) result = TRUE;
		break;
	default:
		result = ERROR;
		break;
	}
// freeing allocated heap
Cleanup:
	if (lookupName) elektraFree (lookupName);
	if (compareTo) elektraFree (compareTo);
	return result;
}
Пример #28
0
/*
 * opnode is the root of a comparison with a non-standard attribute.
 * Evaluate the comparison, returning 1 (true) or 0 (false).
 */
static int
evaluateNonStdComparison(const pnode_t *opnode, evlattribute_t *tmplAtts[])
{
	const pnode_t *left = pnLeft(opnode);
	const pnode_t *right = pnRight(opnode);
	int op = opnode->attr_flag;
	evlattribute_t *att;
	long sval;
	int attType;

	if (!tmplAtts) {
		return 0;
	}
	att = tmplAtts[left->attr_nsa->nsaAtt];
	if (!att || !attExists(att)) {
		return 0;
	}

	if (right->node_type == nt_string || right->node_type == nt_regex) {
		/*
		 * Get the string equivalent of the attribute value, for
		 * comparison either via strstr or via regexec.
		 */
		char leftStr[EVL_ATTRSTR_MAXLEN];
		int status;

		status = evlatt_getstring(att, leftStr, EVL_ATTRSTR_MAXLEN);
		assert(status == 0);

		if (right->node_type == nt_string) {
			const char *rightStr = right->u_att.attr_string;
			return compareStrings(op, leftStr, rightStr);
		} else {
			status = regexec(right->u_att.attr_regex, leftStr,
				0, NULL, 0);
			if (op == '~') {
				return (status == 0);
			} else {
				/* Must be !~ */
				return (status != 0);
			}
		}
	}

	assert(right->node_type == nt_val);
	sval = (long) right->u_att.attr_val;
	
	switch(evlatt_gettype(att)) {
	case TY_CHAR:
	case TY_WCHAR:
	case TY_SHORT:
	case TY_INT:
	case TY_LONG:
		return compareSignedInts(op, evl_getLongAttVal(att), sval);
	case TY_UCHAR:
	case TY_USHORT:
	case TY_UINT:
	case TY_ULONG:
		return compareUnsignedInts(op, evl_getUlongAttVal(att), sval);
	case TY_LONGLONG:
		return compareLonglongs(op, evl_getLonglongAttVal(att), sval);
	case TY_ULONGLONG:
		return compareUlonglongs(op, evl_getUlonglongAttVal(att), sval);
	case TY_FLOAT:
	case TY_DOUBLE:
		return compareDoubles(op, evl_getDoubleAttVal(att), sval);
	case TY_LDOUBLE:
		return compareLongdoubles(op, evl_getLongdoubleAttVal(att), sval);
	}
	
	/* TODO: Handle unsupported types such as TY_WSTRING. */
	return 0;
}
Пример #29
0
int main() {
  stringSize();
  compareStrings();
}
Пример #30
0
void IndexInsert (Index *indx, char *tk,const char *fileName)
{
	int compare;
	int duplicate = 0;
	int dupCompare;
	int hashPosition;
	int tokenNode = tk[0];
	int compareFile;
	fileNode *myFileNode = calloc(1, sizeof(fileNode));
	fileNode *currFile, *prevFile;
	fileNode *tempCurr, *tempPrev;
	fileNode *MynewFile;
	tkNode *myTokenNode;
	tkNode *current;
	tkNode *previous;
	myFileNode->fileName = fileName;
	myFileNode->next = NULL;
	myFileNode->Count = 1;
	hashPosition = Hash(tokenNode);
	/*front of linked list is empty*/
	if(indx->Array[hashPosition].tk == NULL)
	{
        	indx->Array[hashPosition].tk = tk;
       		indx->Array[hashPosition].fileNodePTR = myFileNode;
    	}
   	else
    	{
		/*linked list not empty*/
        	myTokenNode = malloc(sizeof(tkNode));
	        myTokenNode->tk = tk;
	        myTokenNode->next = NULL;
	        myTokenNode->fileNodePTR = myFileNode;
	        current = &indx->Array[hashPosition];
	        previous = NULL;

	        /*determine if a duplicate token exists*/
	        while(current != NULL)
	        {
	            dupCompare = compareStrings(myTokenNode->tk, current->tk);
	            if(dupCompare == 0){
	            duplicate = 1;
   	        }
        	previous = current;
        	current = current->next;
        }
        current = &indx->Array[hashPosition];
        previous = NULL;
	/*determine token position in linked list*/
        while(current != NULL)
        {
        	compare = compareStrings(myTokenNode->tk, current->tk);
		/*token goes before the token its being compared to*/
        	if(compare < 0 && !duplicate)
        	{
                	/*new token needs to be at front of linked list*/
                	if(previous == NULL)
                	{
                	/*a node already exists will be placed front of list*/
                		if(indx->Array[hashPosition].next != NULL)
               			{
                		        current->next = indx->Array[hashPosition].next;
                		        indx->Array[hashPosition].next = myTokenNode;
                       			myTokenNode->tk = indx->Array[hashPosition].tk;
		                        myTokenNode->fileNodePTR = indx->Array[hashPosition].fileNodePTR;
		                        indx->Array[hashPosition].tk = tk;
       			                indx->Array[hashPosition].fileNodePTR = myFileNode;
                    		}
                    		/*only one token in the list*/
                   		else
                   		{
                     			indx->Array[hashPosition].next = myTokenNode;
	                        	myTokenNode->tk = indx->Array[hashPosition].tk;
	                      		myTokenNode->fileNodePTR = indx->Array[hashPosition].fileNodePTR;
								indx->Array[hashPosition].tk = tk;
	        	                indx->Array[hashPosition].fileNodePTR = myFileNode;
		                }
       		         }
        	        /*insert token in the middle*/
        	        else
        	        {
        		    myTokenNode->next = previous->next;
       		            previous->next = myTokenNode;
                	}
         	       return;
		}

		else if(compare > 0 && !duplicate)
		{
                /*token goes at the end of linked list*/
        	        if(current->next == NULL)
        	        {
        	            current->next = myTokenNode;
        	            return;
        	        }

      		}
        	/*increase file frequency count or add new file node*/
        	else if(compare == 0)
            	{
            		currFile = current->fileNodePTR;
            		prevFile = NULL;
               		/*find if there exists the same file*/
            		while(currFile != NULL)
    		        {
                		compareFile = compareStrings((char*)fileName, (char*)currFile->fileName);
                    		/*word and file already exists increment frequency count*/
                   		 if(compareFile == 0)
                    		{
                    			currFile->Count++;
                        		/*sort if necassary*/
                     			if(prevFile != NULL)
                     			{
                            			/*sorts filenames according to token count*/
                     			       	if(prevFile->Count > currFile->Count)
                            			{
                               				 return;
                            			}
                           			 /*files out of order*/
                     			       else
                  			       {
                                			/*take file_node out of list to re-sort*/
                            				prevFile->next = currFile->next;
                    				        tempCurr = current->fileNodePTR;
                                			tempPrev = NULL;
                                			while(tempCurr != NULL)
                                			{
                            				        if(tempCurr->Count < currFile->Count)
                          				        {
                        				                if(tempPrev == NULL)
                                       					{
                                   					        current->fileNodePTR = currFile;
                                            					currFile->next = tempCurr;
                                            					return;
                                        				}
                                       					else
                                        				{
                                  					        tempPrev->next = currFile;
                                          					currFile->next = tempCurr;
                                        					return;
                                        				}
                                    				}
                                   			tempPrev = tempCurr;
                                 			tempCurr = tempCurr->next;
                                			}
                            			}
                        		}
                        		/*file incremented was first in list*/
                        		else
                        		{
                        			return;
                       			}
                    		}
                    		prevFile = currFile;
                    		currFile = currFile->next;
                	}
                	/*first occurence of this word in this file*/
                	MynewFile = (fileNode*)calloc(1,(sizeof(fileNode)));
                	MynewFile->fileName = fileName;
                	MynewFile->Count = 1;
               		MynewFile->next = NULL;
                	prevFile->next = MynewFile;
               		return;
            	}
            	previous = current;
            	current = current->next;
     	}
    }
}