示例#1
0
int listInsertNext(List *list, ListElmt *element, const void *data)
{
    ListElmt *newElement;
    if ((newElement = (ListElmt *)malloc(sizeof(ListElmt))) == NULL) {
        return -1;
    }
    newElement->data = (void *)data;
    if (element == NULL) {
        if (listSize(list) == 0) {
            list->tail = newElement;
        }
        newElement->next = list->head;
        list->head = newElement;
    } else {
        if (element->next == NULL) {
            list->tail = newElement;
        }
        newElement->next = element->next;
        element->next = newElement;
    }
    list->size += 1;
    return 0;
}
示例#2
0
文件: Parser.c 项目: Engeltj/Tibia
void read_new_attr(List ** lists, int * new_id, int * new_level){
	int x=0,y=0;
	for (x=0;x<CAT;x++){
		double num=1.00;
		ListNode * nodePtr = lists[x]->head;
		double size = (double) listSize(nodePtr);
		nodePtr=nodePtr->next;
		
		while (nodePtr != NULL){
			//printf("%s\n",(char *)nodePtr->key);
			int level = pow((num/size),2.0) * 1000;
			if (num == 1)
				level = 1;
			new_id[y] = atoi(nodePtr->key);
			new_level[y] = level;
			//printf("ID: %d\n", new_id[y]);
			//printf("id: %d  new_level:%d %d \n", new_id[y], new_level[y], level);
			nodePtr=nodePtr->next;
			num++;
			y++;
		}
	}
}
int
waitPreloadJobs () {
    int i;
    int size;

    // destroy preload thread list
    size = listSize(PreloadThreadList);
    for(i=0;i<size;i++) {
        LOCK(PreloadLock);
        preloadThreadInfo_t *threadInfo = (preloadThreadInfo_t *)removeFirstElementOfConcurrentList(PreloadThreadList);
        if(threadInfo != NULL) {
            rodsLog (LOG_DEBUG, "waitPreloadJobs: Waiting for a preload job - %s", threadInfo->path);
            UNLOCK(PreloadLock);
#ifdef USE_BOOST
            threadInfo->thread->join();
#else
            pthread_join(threadInfo->thread, NULL);
#endif
        } else {
            UNLOCK(PreloadLock);
        }
    }
    return 0;
}
示例#4
0
文件: handler.c 项目: KaSt/nereamud
void obj_to_game(OBJ_DATA *obj) {
  if(setIn(object_set, obj))
    return;

  // property table, for lookup by python
  if(!obj_exists(obj))
    obj_exist(obj);

  // set and list storage, for objects physically 'in' the game
  listPut(object_list, obj);
  setPut(object_set, obj);

  // execute all of our to_game hooks
  hookRun("obj_to_game", hookBuildInfo("obj", obj));

  // also add all contents
  if(listSize(objGetContents(obj)) > 0) {
    LIST_ITERATOR *cont_i = newListIterator(objGetContents(obj));
    OBJ_DATA *cont = NULL;
    ITERATE_LIST(cont, cont_i)
      obj_to_game(cont);
    deleteListIterator(cont_i);
  }
}
示例#5
0
文件: levels.c 项目: manolaz/Wizznic
//Adds the level to list if it's not allready there.
void addUserLevel(const char* fn)
{
  levelInfo_t* tl;
  listItem* l=userLevelFiles;
  //Check if it's there
  while( (l=l->next) )
  {
    if(strcmp( ((levelInfo_t*)l->data)->file, fn )==0)
    {
      return;
    }
  }


  tl=mkLevelInfo(fn);

  if(tl)
  {
    listAddData(userLevelFiles, (void*)tl);
    numUserLevels=listSize(userLevelFiles);
  } else {
    printf("Strange error, couldn't open saved level.\n");
  }
}
示例#6
0
/**
 * Remove from position i of the linkList
 */
data *popatPosition(dlinklist *ll,int position)
{
	if(!checkEmpty(ll)) return NULL;
	int length = listSize(ll);
	if(position > length) {
		printf("You entered the position out of the bound!\n");
		return NULL;
	}
	node *temp;
	int i = 1;

	if(position == 1) {
		//pop here - popFront and return;
		popFront(ll);
	} else if(position == length) {
		//pop here - popBack and return;
		popBack(ll);
	}

	for(temp= ll->head; temp != NULL; temp=temp->next) {
		if(i == position) {
			//pop here and return;
			temp->prev->next = temp->next;
			temp->next->prev = temp->prev;
#if DEBUG
			printf(">>==============Node pop'd at position %d ================<<\n",position);
#endif
			data *returndata = createData(temp->dataPtr->val);
			free(temp->dataPtr);
			free(temp);
			return returndata;
		}
		i++;
	}
	return NULL;
}
示例#7
0
int main(int argc, char *argv[]) {

    GRAPH g;
    int countTotal = 0;
    boolean writethem = FALSE, printThem = FALSE, printNew = FALSE, printOld = FALSE;
    boolean first = TRUE;

    list = NULL;

    int c;
    char *name = argv[0];

    while ((c = getopt(argc, argv, "hiwnop")) != -1) {
        switch (c) {
            case 'h':
                help(name);
                return EXIT_SUCCESS;
            case 'i':
                printNew = TRUE;
                printOld = TRUE;
                break;
            case 'n':
                printNew = TRUE;
                break;
            case 'o':
                printOld = TRUE;
                break;
            case 'p':
                printThem = TRUE;
                break;
            case 'w':
                writethem = TRUE;
                break;
            default:
                usage(name);
                return EXIT_FAILURE;
        }
    }

    struct tms TMS;
    unsigned int oldtime = 0;

    while (read_pgc_code(stdin, &g) != EOF) {
        countTotal++;
        int isNew = handle_new_graph(&g, &list);

        if(isNew && writethem) {
            write_pgc_code(stdout, &g, first);
            first = FALSE;
        }

        if (isNew) {
            if(printNew) fprintf(stderr, "Graph %d is new.\n", countTotal);
        } else {
            if(printOld) fprintf(stderr, "Graph %d is not new.\n", countTotal);
        }

        if(isNew && printThem) {
            printGraph(stderr, &g);
        }

    }

    int countNonIso = listSize(list);

    fprintf(stderr, "Read %d graphs, of which %d pairwise not isomorph.\n", countTotal, countNonIso);

    times(&TMS);
    unsigned int savetime = oldtime + (unsigned int) TMS.tms_utime;
    fprintf(stderr, "CPU time: %.1f seconds.\n", (double) savetime / time_factor);
    
    return (0);

}
/** Open all required output files
	
	Note: for LLgen output an output file is created for each input file. 
	Further, two files, <prefix>pars.h and <prefix>pars.c, are created.
*/
static void openOutputs(void) {
	const char *cExtension = "c", *hExtension = "h";
	FileListItem *currentItem;
	const char *inputName, *prefixText;
	char *outputName;
	size_t lenPrefix;
	int i;

	if (option.extensions) {
		char *extension = listIndex(option.extensions, 0);
		if (extension != NULL)
			cExtension = extension;
		if (listSize(option.extensions) > 1 && (extension = listIndex(option.extensions, 1)) != NULL)
			hExtension = extension;
	}
	
	outputs = newList();
	
	if (listSize(option.inputFileList) == 0) {
		ASSERT(option.outputBaseName != NULL);
		currentItem = (FileListItem *) safeMalloc(sizeof(FileListItem), "openOutputs");
		/* Note that for LLgen style outputs the use of include files is
		   prohibited, so fileName still points to the string "<stdin>". */
		currentItem->sourceFileName = fileName;
		currentItem->firstNonTerminal = true;
		outputName = createNameWithExtension(option.outputBaseName, cExtension);
		currentItem->output = checkAndOpenFile(outputName, true);
		listAppend(outputs, currentItem);
	} else {
		/* Open the different output files */
		for (i = 0; i < listSize(option.inputFileList); i++) {
			inputName = (const char *) listIndex(option.inputFileList, i);
			
			currentItem = (FileListItem *) safeMalloc(sizeof(FileListItem), "openOutputs");
			currentItem->sourceFileName = inputName;
			/* Set the flag that indicates that we haven't yet generated a
			   NonTerminal */
			currentItem->firstNonTerminal = true;
			
			/* For LLgen style outputs we never keep the directory, as multiple 
			   directories may be present for different files. */
			inputName = baseName(inputName);
			outputName = createNameWithExtension(inputName, cExtension);
			for (i = 0; i < listSize(outputs); i++) {
				FileListItem *itemToCheck = (FileListItem *) listIndex(outputs, i);
				if (strcmp(outputName, itemToCheck->output->name) == 0)
					fatal("Input files %s and %s map to the same output name.\n", itemToCheck->output->name, outputName);
			}
			currentItem->output = checkAndOpenFile(outputName, true);
			listAppend(outputs, currentItem);
		}
	}
	
	/* Open Lpars.h and Lpars.c, or appropriatly prefixed version of them */
	if (prefixDirective == NULL) {
		prefixText = "L";
		lenPrefix = 1;
	} else {
		prefixText = prefixDirective->token[0]->text;
		lenPrefix = strlen(prefixText);
	}

	outputName = (char *) safeMalloc(strlen(prefixText) + 6 + strlen(hExtension), "openOutputs");
	sprintf(outputName, "%spars.%s", prefixText, hExtension);
	hOutput = checkAndOpenFile(outputName, false);
	outputName = (char *) safeMalloc(strlen(prefixText) + 6 + strlen(cExtension), "openOutputs");
	sprintf(outputName, "%spars.%s", prefixText, cExtension);
	cOutput = checkAndOpenFile(outputName, true);
}
Decipher::Decipher(int index, int public_cipher): QDialog()
{
    setFixedSize(800, 400);
    this->setWindowTitle("Decipher");

    labelCipher = new QLabel("Choose file to decipher :",this);
    labelPlain = new QLabel("Choose where to create output file :",this);
    if(public_cipher)
        labelKey = new QLabel("Choose which key to use :",this);
    else
        labelKey = new QLabel("Type in your passphrase :", this);
    labelMode = new QLabel("Block chaining mode and size :");
    //labelIv = new QLabel("Enter IV :", this);

    buttonBrowseCipher = new QPushButton("Browse", this);
    if(public_cipher)
        buttonBrowseKey = new QPushButton("Browse", this);
    buttonCancel = new QPushButton("Cancel", this);
    buttonCompute = new QPushButton("Compute", this);

    QStringList listMode(QStringList() << "CBC");
    QStringList listSize(QStringList() << "128" << "256");

    comboMode = new QComboBox(this);
    comboMode->addItems(listMode);

    comboSize = new QComboBox(this);
    comboSize->addItems(listSize);

    lePlain = new QLineEdit(this);
    leCipher = new QLineEdit(this);
    leKey = new QLineEdit(this);

    // EchoMode(1) sets a password type of echo
    if(!public_cipher)
        leKey->setEchoMode(QLineEdit::Password);

    //leIv = new QLineEdit(this);

    fdCipher = new QFileDialog(this);
    fdKey = new QFileDialog(this);

    fdCipher->setDirectory("../ressources/");
    fdKey->setDirectory("../ressources/");

    QStringList listFilters;

    if(public_cipher)
        listFilters << "*.puKey" << "*";
    else
        listFilters << "*.key" << "*";

    fdCipher->setNameFilter("*.cipher");
    fdKey->setNameFilter("*.prKey");

    fdKey->setNameFilters(listFilters);

    gl = new QGridLayout(this);

    gl->addWidget(labelCipher, 0, 0);
    gl->addWidget(leCipher, 0, 1);
    gl->addWidget(buttonBrowseCipher, 0, 2);

    gl->addWidget(labelKey, 1, 0);
    gl->addWidget(leKey, 1, 1);

    if(public_cipher)
        gl->addWidget(buttonBrowseKey, 1, 2);

    gl->addWidget(labelMode, 2, 0);
    gl->addWidget(comboMode, 2, 1);
    gl->addWidget(comboSize, 2, 2);

    /*gl->addWidget(labelIv, 3, 0);
    gl->addWidget(leIv, 3, 1);*/

    gl->addWidget(labelPlain, 4, 0);
    gl->addWidget(lePlain, 4, 1);

    gl->addWidget(buttonCancel, 5, 1);
    gl->addWidget(buttonCompute, 5, 2);

    this->setLayout(gl);

    QObject::connect(buttonCancel,SIGNAL(clicked()),this,SLOT(close()));
    QObject::connect(buttonBrowseCipher, SIGNAL(clicked()), fdCipher, SLOT(exec()));

    if(public_cipher)
        QObject::connect(buttonBrowseKey, SIGNAL(clicked()), fdKey, SLOT(exec()));

    QObject::connect(fdCipher, SIGNAL(fileSelected(QString)), leCipher, SLOT(setText(QString)));
    QObject::connect(fdKey, SIGNAL(fileSelected(QString)), leKey, SLOT(setText(QString)));

    switch(index){
        case 0:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRSA()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 1:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRSACRT()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 2:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeElGamal()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 3:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRabin()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 4:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRSAOAEP()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 5:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeAES()));
            break;
        case 6:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeDES()));
            break;
        default:
            this->close();
            break;
    }
}
示例#10
0
文件: grep.c 项目: kinroux/grep
int eGrep(int argc, char** argv){


	Arguments* args = getArgs(argc, argv);

	int return_val = 0;
	short int quit = 0;

	if (args == NULL)
	{
		printf("Invalid command.\n");
		return_val = 2;
		quit = 1;
	}

	if (!quit && !hasOption('q', args->options))
	{
		// Command display
		printf("grep");
		int i;
		for (i = 1; argv[i] != NULL; i++)
			printf(" %s", argv[i]);
		printf("\n");
		for (i = 0; i < 50; i++)
			printf("-");
		printf("\n");
		// ---

	}
	else
	{
#ifdef _WIN32
		system("cls");
#else
		system("clear");
#endif
	}
	if (!quit && args->options != NULL && (*(Options*)args->options->data).name == '-' && args->files == NULL && args->pattern == NULL)
	{
		printf(
					"Usage : grep [OPTION] ... PATTERN [FILE]...\n"
					"Search for PATTERN or standard input in each FILE\n"
					"PATTERN is, by default, a standard regular expression (BRE) i.e \"hello world\".\n"
					"\nRegex selection :\n"
					"\n-E, --extended-regexp\tPattern is an extended regular expression (ERE)\n"
					"\n-e, --regexp=PATTERN\tuse PATTERN for matching\n"
					"\n-f, --file=FILE\t\tObtain PATTERN from file, the content of FILE is\n\t\t\tconsidered as the PATTERN to look for\n"
					"\n-i, --ignore-case\tIgnore case distinction\n"
					"\n-w, --word-regexp\tForce PATTERN to match only whole words\n"
					"\n-x, --line-regexp\tForce PATTERN to match only whole line\n"
					"\n-z, --null-data\t\tData lines end in 0 byte instead of a newline\n"
					"\nMiscellaneous :\n"
					"\n-s, --no-messages\tSuppress error messages\n"
					"\n-v, --invert-match\tSelect non-matching lines (uncompatible with -o)\n"
					"\n    --help\t\tDisplay this help and exit\n"
					"\nOutput control :\n"
					"\n-m, --max-count=NUM\tStop searching in a file after NUM matching lines\n"
					"\n-b, --byte-offset\tPrint the byte offset for each output lines,\n"
					"\t\t\twhen combined with -o print the offset of the match\n"
					"\n-n, --line-number\tPrint line number with outuput lines (starts at 1)\n"
					"\n-H, --with-filename\tPrint the filename for each match (default when having\n\t\t\tmore than one FILE)\n"
					"\n-h, --no-filename\tSuppress the file name prefix on output (default when\n\t\t\thaving only one FILE)\n"
					"\n-o, --only-matching\tDisplays only the part of a line matching the pattern,\n"
					"\t\t\tin the case of multiple matches per line, displays\n\t\t\tas many lines as matches\n"
					"\t\t\tuncompatible with -v, -e and -E\n"
					"\n-q, --quiet, --silent\tSuppress all normal output\n"
					"\n-R, -r, --recursive\tSearch recursively in each files contained in FILE\n"
					"\n--include=GLOB\t\tSearch only files whose base name matches GLOB\n"
					"\n--exclude=GLOB\t\tSkip   files  whose  base  name  matches  GLOB\n"
					"\n--exclude-dir=DIR\tExclude directories matching  the  pattern  DIR\n\t\t\tfrom  recursive searches\n"
					"\n-L, --files-without-match Print only names of FILEs containing no match\n"
					"\n-l, --file-with-matches\tPrint only names of FILEs containing matches\n"
					"\n-c, --count\t\tprint only a count of matching lines per FILE\n"
					"\n-Z, --null\t\tPrint 0 byte after FILE name\n"
					"\nSpecial handling : if '-' is given as PATTERN, PATTERN become the standard input"
					"\nExit status :\n\n" 
					"0 if no results were found\n"
					"1 if at least one result was found\n"
					"2 if an error was given\n\n"
					

				);
		quit = 1;
	}

	if (!quit && args->options != NULL &&  (*(Options*)args->options->data).name == 'V' && args->files == NULL && args->pattern == NULL)
	{
		printf( 
				"Grep command revised :\n\n"
				"version : %d.%d.%d\n\n"
				"authors :\n\tBASSET Cyril\n\tLAMBERTI Jean-Vincent\n\tPICARD David\n\n"
				,GREP_STATUS,GREP_MAJOR_VERSION,GREP_MINOR_VERSION);
		quit = 1;
	}


	if(!quit && args->pattern == NULL)
	{
		if(!hasOption('s', args->options) && !hasOption('q', args->options))
			printf("Pattern not found.\n");
		return_val = 2;
		quit = 1;
	}

	if(!quit && (!args->files || !args->pattern))
		quit = 1;

	if (!quit)
	{
		if (args->files != NULL)
		{

			Maillon* lines = NULL;
			int file_count = 0;
			if(hasOption('r',args->options))
			{
				Maillon* files = NULL;
				Maillon* next = args->files;
				while(next != NULL)
				{
					getFileFrom((char*)next->data,&files,args->options);
					next = next->next;
				}
				lines = nFileLoader(files, hasOption('z',args->options));
				file_count = listSize(files);
			}
			else
			{
				lines = nFileLoader(args->files, hasOption('z',args->options));
				file_count = listSize(args->files);
			}

			if (lines != NULL)
			{
				Maillon* results = extractWithPattern(lines, args->pattern, args->options);
				if (!hasOption('q', args->options))
					displayFileLine(results, file_count, args);
				return_val = listSize(results) > 0 ? 0 : 1 ;
				//listSize(results)>0?return_val=0:return_val=1;
			}
		}
	}

	if (args != NULL)
	{
		//freeList(&(args->options));
		// Do not free pattern!!! It's the argv[i] address
		//freeList(&(args->files));
		FREE(args);
	}

	return return_val;
}
示例#11
0
文件: array.c 项目: fmccabe/cafe
static retCode countEls(termPo el, integer ix, void *cl) {
  integer *count = (integer *) cl;
  listPo ll = C_LIST(el);
  (*count) += listSize(ll);
  return Ok;
}
示例#12
0
/**
 * do align specific drawing
 */
void alignDraw() {
  list *l, *cList = NULL;
  listNode *i,*j;
  vertex *t, *prev;
  quadri curPos;    /* to hold current pos image to be displayed */
  vector rc; /* world coords of rotation center */
  //char slicefile1[MAX_STR_LEN];
  float maxTexX, maxTexY;
  GLenum textureMethod = getTextureMethod();

  /* draw the current referrence image */
  if(curSlice != 0 && animate
     && displayImg == 0) { /* just display the reference image */

    maxTexX = (float) ref->width;
    maxTexY = (float) ref->height;

    if(curDataset->imageSource != VP_NOIMAGES) {
      /* turn on texture mapping */
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
      glEnable(textureMethod);

      /* bind the texture */
      glBindTexture(textureMethod, *refTex);

      /* get the window coordinates of the reference image */
      curPos = getWindowCoordsQ(refImgBounds);

      if(textureMethod == GL_TEXTURE_2D) {
        maxTexX = ref->width/(float)(ref->width+ref->padX);
        maxTexY = ref->height/(float)(ref->height+ref->padY);
      }

      /* make a quadrilateral and provide texture coords */
      glBegin(GL_QUADS); {
        glTexCoord2d(0.0,0.0);
        glVertex3d(curPos.v1.x, curPos.v1.y, 0.0);
        glTexCoord2d(maxTexX,0.0);
        glVertex3d(curPos.v2.x, curPos.v2.y, 0.0);
        glTexCoord2d(maxTexX,maxTexY);
        glVertex3d(curPos.v3.x, curPos.v3.y, 0.0);
        glTexCoord2d(0.0,maxTexY);
        glVertex3d(curPos.v4.x, curPos.v4.y, 0.0);
      } glEnd();
      glDisable(textureMethod);
    }
  }
  else if(curSlice == 0 || !animate
          || displayImg == 1) { /* apply the current rot & trans */
    /* calculate transformed coordinates based on current rot and trans */
    if(moving) {
      curPos = getQuadTranslation(movImgBounds, curTransAction);
    }
    else if(rotating) { /* rotate the movImg coords bu the current angle */
      curPos = getQuadRotation(movImgBounds, curRotCenter, curRotAngle);
    }
    else { /* no current transformation, draw at expected location */
      curPos = movImgBounds;
    }

    curPos = getWindowCoordsQ(curPos);

    maxTexX = (float) mov->width;
    maxTexY = (float) mov->height;

    if(curDataset->imageSource != VP_NOIMAGES) {
      if(textureMethod == GL_TEXTURE_2D) {
        maxTexX = mov->width/(float)(mov->width+mov->padX);
        maxTexY = mov->height/(float)(mov->height+mov->padY);
      }

      /* turn on texture mapping */
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
      glEnable(textureMethod);

      /* bind the texture */
      glBindTexture(textureMethod, *movTex);

      /* get the window coordinates of the moving image */
      //curPos = getWindowCoordsQ(curPos);

      /* make a quadrilateral and provide texture coords */
      glBegin(GL_QUADS); {
        glTexCoord2f(0,0);
        glVertex3d(curPos.v1.x, curPos.v1.y, 0);
        glTexCoord2f(maxTexX,0);
        glVertex3d(curPos.v2.x, curPos.v2.y, 0);
        glTexCoord2f(maxTexX,maxTexY);
        glVertex3d(curPos.v3.x, curPos.v3.y, 0);
        glTexCoord2f(0,maxTexY);
        glVertex3d(curPos.v4.x, curPos.v4.y, 0);
      } glEnd();
      glDisable(textureMethod);
    }
  }

  /* cur slice contours and markers */
  if(showCurTacks && listSize(curDataset->sliceContourLists) > curSlice) {
    glColor3fv(COLORS[DARK_GRAY]);

    /* iterate over contours, drawing each */
    l = (list*)getListNode(curDataset->sliceContourLists,curSlice)->data;
    for(i = getListNode(l,0); i; i = (listNode*) i->next) {
      /* get the contour at index */
      cList = ((contour*)i->data)->vertices;

      /* draw the contour lines, if we need to */
      glPointSize(pixelSize*tackWidth);
      glBegin(GL_LINES); {
        /* iterate over tacks, drawing lines between each */
        prev = listSize(cList) > 1 ? (vertex*) getListNode(cList,0)->data : NULL;
        for(j = getListNode(cList,1); prev && j; j = (listNode*) j->next) {
          t = (vertex*) j->data;
          drawLine(prev,t);
          prev = t;
        }
      } glEnd();

      /* draw the tacks in the contour */
      for(j = getListNode(cList,0); j; j = (listNode*) j->next) {
        t = (vertex*) j->data;
        /* draw the tack */
        drawTack(t);
      }
    }

    /* cur slice markers */
    glColor3fv(COLORS[GRAYED_LIGHT_ORANGE]);
    l = (list*)getListNode(curDataset->sliceMarkerLists,curSlice-1)->data;
    for(i = getListNode(l,0); i; i = (listNode*) i->next) {
      t = (vertex*) i->data;
      /* draw the tack */
      drawTack(t);
    }
  }

  /* prev slice contours and markers */
  if(showPrevTacks && curSlice > 0
     && listSize(curDataset->sliceContourLists) > curSlice-1) {
    glColor3fv(COLORS[GRAY]);

    /* iterate over contours, drawing each */
    l = ((contour*)getListNode(curDataset->sliceContourLists,curSlice-1)->data)->vertices;
    for(i = getListNode(l,0); i; i = (listNode*) i->next) {
      /* get the contour at index */
      cList = (list*)i->data;

      /* draw the contour lines, if we need to */
      glPointSize(pixelSize*tackWidth);
      glBegin(GL_LINES); {
        /* iterate over tacks, drawing lines between each */
        prev = listSize(cList) > 1 ? (vertex*) getListNode(cList,0)->data : NULL;
        for(j = getListNode(cList,1); prev && j; j = (listNode*) j->next) {
          t = (vertex*) j->data;
          drawLine(prev,t);
          prev = t;
        }
      } glEnd();

      /* draw the tacks in the contour */
      for(j = getListNode(cList,0); j; j = (listNode*) j->next) {
        t = (vertex*) j->data;
        /* draw the tack */
        drawTack(t);
      }
    }

    /* cur slice markers */
    glColor3fv(COLORS[GRAYED_LIGHT_ORANGE]);
    l = (list*)getListNode(curDataset->sliceMarkerLists,curSlice-1)->data;
    for(i = getListNode(l,0); i; i = (listNode*) i->next) {
      t = (vertex*)i->data;
      /* draw the tack */
      drawTack(t);
    }
  }

  /* draw the center of rotation */
  glPointSize(rotCenterSize);
  glBegin(GL_POINTS); {
    glColor3fv(COLORS[RED]);
    rc = getWindowCoordsV(curRotCenter);
    glVertex3d(rc.x, rc.y, 0);
  } glEnd();

  /* build info and alert strings */
  //getSliceFilename(curDataset, curSlice, slicefile1);
  //getSliceFilename(curDataset, curSlice+1, slicefile2);
  strcpy(modeString,"align: ");
  sprintf(modeString,"slice %d ",curSlice);
  //strcat(modeString,slicefile1);
  //strcat(modeString," to ");
  //strcat(modeString,slicefile1);
}
示例#13
0
文件: bundle.c 项目: manolaz/Wizznic
void bundle( const char* file, const char* inDir)
{
  FILE* f;
  entity* e;
  listItem* entryList = initList();
  listItem* it=entryList;
  bundleHeader_t header;
  bundleFileEntry* be;
  uint32_t dataOffset=0;
  header.version = bundleFileVersion;
  sprintf( header.ident, "%s", bundleFileIdentString );

  char endMark[] = bundleFileEndMarkString;

  e = malloc(sizeof(entity) );
  e->data=0;
  e->dataOffset=0;
  e->dataSize=0;
  strcpy( e->name, inDir );
  e->type = TYPE_DIR;
  listAddData( entryList, (void*)e );

  printf("Listing directories...\n");
  if( dirScan( inDir, TYPE_DIR, entryList ) )
  {
    header.numEntries = listSize(entryList);
    printf("Added %i directories.\n", header.numEntries );

    printf("Listing files...\n");
    if( dirScan( inDir, TYPE_FILE, entryList ) )
    {
      printf("Added %i files.\n", (listSize(entryList)-header.numEntries) );
      header.numEntries = listSize(entryList);
      printf("There are now %i entries.\n", header.numEntries);
      //First dataoffset is after the list of all entries
      dataOffset = sizeof(bundleHeader_t) + (sizeof(bundleFileEntry)*header.numEntries);


      printf("Bundling...\n");

      f = fopen( file, "wb" );

      if(f)
      {
        //Write header
        fwrite( (void*)(&header), sizeof(bundleHeader_t),1, f );

        //Write entries
        while( (it=it->next) )
        {
          e = (entity*)it->data;
          be = malloc( sizeof(bundleFileEntry) );
          be->type = e->type;
          be->nameLen = strlen( e->name );

          be->dataOffset = dataOffset;
          be->dataLen = e->dataSize;

          fwrite( (void*)be, sizeof(bundleFileEntry), 1, f );

          dataOffset += be->dataLen+be->nameLen;

          free(be);
        }

        it=entryList;
        //Write file data
        while( (it=it->next) )
        {
          e = (entity*)it->data;
          //Write file-name
          if( e->type == TYPE_DIR )
          {
            fwrite( (void*)e->name, sizeof(char)*strlen(e->name), 1, f);
            printf("Added Dir: %s\n", e->name);
          }
          //If it's a file, write content
          if( e->type == TYPE_FILE )
          {
            fwrite( e->data, e->dataSize+strlen(e->name), 1, f);
            printf("Added File: %s\n", e->name);
          }
        }

        fwrite( (void*)&endMark, strlen(endMark), 1, f );

        fclose(f);

      } else {
        printf("Could not open outputfile %s for writing.\n", file);
      }
    } else {
      printf("fileScan of %s failed.\n", inDir);
    }
  } else {
    printf("dirScan of %s failed.\n", inDir);
  }
}
示例#14
0
文件: list.c 项目: biran0079/Toy-Lang
void listSort(List *lst, Comparator cmp) {
  void **t = tlMalloc(listSize(lst) * sizeof(void *));
  msortInternal(lst->arr, 0, lst->size, cmp, t);
  tlFree(t);
}
示例#15
0
bool checkPalindrome(ListNode* head){
    int len = listSize(head);
    return check(head, len);
}
示例#16
0
文件: listops.c 项目: fmccabe/cafe
ReturnStatus g__list_nil(processPo p, ptrPo tos) {
  integer cap = integerVal(tos[0]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) createList(processHeap(p), cap)};
  return ret;
}

ReturnStatus g__list_empty(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);

  ReturnStatus ret = {.ret=Ok, .result=listSize(l) == 0 ? trueEnum : falseEnum};
  return ret;
}

ReturnStatus g__list_size(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) allocateInteger(processHeap(p), listSize(l))};
  return ret;
}

ReturnStatus g__list_nth(processPo p, ptrPo tos) {
  termPo Lhs = tos[0];
  integer ix = integerVal(tos[1]);
  listPo l = C_LIST(Lhs);

  assert(ix >= 0 && ix < listSize(l));

  ReturnStatus ret = {.ret=Ok, .result=nthEl(l, ix)};
  return ret;
}

ReturnStatus g__list_append(processPo p, ptrPo tos) {
  termPo Lhs = tos[0];
  termPo Rhs = tos[1];
  listPo l = C_LIST(Lhs);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) appendToList(processHeap(p), l, Rhs)};
  return ret;
}

ReturnStatus g__list_prepend(processPo p, ptrPo tos) {
  termPo Lhs = tos[0];
  termPo Rhs = tos[1];
  listPo l = C_LIST(Lhs);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) prependToList(processHeap(p), l, Rhs)};
  return ret;
}

ReturnStatus g__list_slice(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer from = integerVal(tos[1]);
  integer count = integerVal(tos[2]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) sliceList(processHeap(p), l, from, count)};
  return ret;
}

ReturnStatus g__list_front(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer count = integerVal(tos[1]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) sliceList(processHeap(p), l, 0, count)};
  return ret;
}

ReturnStatus g__list_back(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer from = integerVal(tos[1]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) sliceList(processHeap(p), l, from, listSize(l) - from)};
  return ret;
}

ReturnStatus g__list_concat(processPo p, ptrPo tos) {
  termPo Lhs = tos[0];
  termPo Rhs = tos[1];
  listPo l = C_LIST(Lhs);
  listPo r = C_LIST(Rhs);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) concatList(processHeap(p), l, r)};
  return ret;
}

ReturnStatus g__list_reverse(processPo p, ptrPo tos) {
  termPo Lhs = tos[0];
  listPo l = C_LIST(Lhs);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) reverseList(processHeap(p), l)};
  return ret;
}

ReturnStatus g__list_flatten(processPo p, ptrPo tos) {
  listPo ll = C_LIST(tos[0]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) flattenList(processHeap(p), ll)};
  return ret;
}

ReturnStatus g__list_insert(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer ix = integerVal(tos[1]);
  termPo vl = tos[2];

  ReturnStatus ret = {.ret=Ok, .result=(termPo) insertListEl(processHeap(p), l, ix, vl)};
  return ret;
}

ReturnStatus g__list_replace(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer ix = integerVal(tos[1]);
  termPo vl = tos[2];

  ReturnStatus ret = {.ret=Ok, .result=(termPo) replaceListEl(processHeap(p), l, ix, vl)};
  return ret;
}

ReturnStatus g__list_remove(processPo p, ptrPo tos) {
  listPo l = C_LIST(tos[0]);
  integer ix = integerVal(tos[1]);

  ReturnStatus ret = {.ret=Ok, .result=(termPo) removeListEl(processHeap(p), l, ix)};
  return ret;
}
示例#17
0
unsigned int stGetLevel(symtable *st)
{
    return listSize(st->blockList) - 1;
}
示例#18
0
int _getAndUseIFuseConn( iFuseConn_t **iFuseConn ) {
    int status;
    iFuseConn_t *tmpIFuseConn;

    *iFuseConn = NULL;

    while ( *iFuseConn == NULL ) {
        /* get a free IFuseConn */

        if ( listSize( ConnectedConn ) >= MAX_NUM_CONN && listSize( FreeConn ) == 0 ) {
            /* have to wait */
            _waitForConn();
            /* start from begining */
            continue;
        }
        else {
            tmpIFuseConn = ( iFuseConn_t * ) removeFirstElementOfConcurrentList( FreeConn );
            if ( tmpIFuseConn == NULL ) {
                if ( listSize( ConnectedConn ) < MAX_NUM_CONN ) {
                    /* may cause num of conn > max num of conn */
                    /* get here when nothing free. make one */
                    tmpIFuseConn = newIFuseConn( &status );
                    if ( status < 0 ) {
                        _freeIFuseConn( tmpIFuseConn );
                        return status;
                    }

                    _useFreeIFuseConn( tmpIFuseConn );
                    addToConcurrentList( ConnectedConn, tmpIFuseConn );

                    *iFuseConn = tmpIFuseConn;
                    break;

                }
                _waitForConn();
                continue;
            }
            else {
                useIFuseConn( tmpIFuseConn );
                *iFuseConn = tmpIFuseConn;
                break;
            }
        }


    }	/* while *iFuseConn */

    if ( ++ConnManagerStarted == HIGH_NUM_CONN ) {
        /* don't do it the first time */

#ifdef USE_BOOST
        ConnManagerThr = new boost::thread( connManager );
#else
        status = pthread_create( &ConnManagerThr, pthread_attr_default, ( void * ( * )( void * ) ) connManager, ( void * ) NULL );
#endif
        if ( status < 0 ) {
            ConnManagerStarted--;
            rodsLog( LOG_ERROR, "pthread_create failure, status = %d", status );
        }
    }
    return 0;
}
/**
 * read a set of slice contours from a file
 */
list *readSliceContours(char *filename) {
  list *slices, *slice, *nextSlice;
  contour *cont;
  listNode *sliceNode, *contNode, *adjNode, *lnAdj;
  intNode *in;
  vertex *v;
  char str[10*SR_MAX_STR_LEN];
  double sliceZ;
  int adjIndex;

  /* open the file */
  FILE *fp = fopen(filename,"r");

  /* validate */
  if(fp == NULL) {
    fprintf(stderr,"error: surfIO.c couldn't open the slice contour file %s for reading\n", filename);
    return NULL;
  }

  skipComments(fp,'#');

  /* create the slices */
  slices = newList(LIST);

  /* read the first string */
  fscanf(fp, "slice ");

  /* read the file */
  while(!feof(fp)) {
    /* read the z coordinate */
    fscanf(fp, "%lf", &sliceZ);

    slice = newList(LIST);
    enqueue(slices,slice);

    /* read the next string and test for new slice */
    fscanf(fp, "%s ", str);
    while(!strcmp(str,"contour")) { /* while we are still reading contours */
      cont = createContour();
      enqueue(slice,cont);

      /* read closure state */
      fscanf(fp, "%s", str);
      if(!strcmp(str,"closed")) {
        cont->closed = CLOSED;
      }

      /* read the first string on the next line, test for "adjacent" */
      fscanf(fp, "%s", str);

      while(strcmp(str,"adjacent")) {
        /* create and read this vertex */
        v = createVertex();
        v->x = atof(str);
        fscanf(fp, "%lf", &v->y);
        v->z = sliceZ;

        enqueue(cont->vertices,v);

        fscanf(fp, "%s", str);
      }

      /* read the adjacent contours as ints, convert to pointers later */
      fscanf(fp, "%d", &adjIndex);
      while(adjIndex != -1) {
        /* add this index to the list */
        in = (intNode*) malloc(sizeof(intNode));
        in->val = adjIndex;

        enqueue(cont->adjacentContours,in);

        fscanf(fp, "%d", &adjIndex);
      }

      fscanf(fp, "%s ", str);
    }
  }

  /* resolve the links from the ajacent contour indices */
  for(sliceNode = getListNode(slices,0);
      listSize(slices) > 1 &&((listNode*)sliceNode)->next;
      sliceNode = (listNode*) sliceNode->next) {

    /* get links to this slice list and the next, for searching */
    slice = (list*) sliceNode->data;
    nextSlice = (list*) ((listNode*) ((listNode*)sliceNode)->next)->data;

    /* iterate over the contours in this slice */
    for(contNode = getListNode(slice,0); contNode;
        contNode = (listNode*) contNode->next) {
      cont = (contour*) contNode->data;

      /* iterate over the adjacent contour indices */
      for(adjNode = getListNode(cont->adjacentContours,0); adjNode;
          adjNode = (listNode*) adjNode->next) {

        /* get the index, replace it with a link, or NULL */
        in = (intNode*) adjNode->data;
        lnAdj = getListNode(nextSlice,in->val);
        free(in);

        if(lnAdj == NULL) {
          markForDeletion(adjNode);
        }
        else {
          setListNodeData(adjNode, (void*) lnAdj->data);
        }
      }

      deleteMarkedNodes(cont->adjacentContours);
    }
  }

  fclose(fp);

  return slices;
}
示例#20
0
void
connManager() {
    time_t curTime;
    iFuseConn_t *tmpIFuseConn;
    ListNode *node;
    List *TimeOutList = newListNoRegion();

    while ( 1 ) {
        curTime = time( NULL );

        /* exceed high water mark for number of connection ? */
        if ( listSize( ConnectedConn ) > HIGH_NUM_CONN ) {

            LOCK_STRUCT( *ConnectedConn );
            int disconnTarget = _listSize( ConnectedConn ) - HIGH_NUM_CONN;
            node = ConnectedConn->list->head;
            while ( node != NULL ) {
                tmpIFuseConn = ( iFuseConn_t * ) node->value;
                if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) {
                    listAppendNoRegion( TimeOutList, tmpIFuseConn );

                }
                node = node->next;            
            }
            UNLOCK_STRUCT( *ConnectedConn );

            node = TimeOutList->head;
            int disconned = 0;
            while ( node != NULL && disconned < disconnTarget ) {
                tmpIFuseConn = ( iFuseConn_t * ) node->value;
                LOCK_STRUCT( *tmpIFuseConn );
                if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) {
                    removeFromConcurrentList2( FreeConn, tmpIFuseConn );
                    removeFromConcurrentList2( ConnectedConn, tmpIFuseConn );
                    if ( tmpIFuseConn->status == 0 ) { /* no struct is referring to it, we can unlock it and free it */
                        UNLOCK_STRUCT( *tmpIFuseConn );
                        /* rodsLog(LOG_ERROR, "[FREE IFUSE CONN] %s:%d %p", __FILE__, __LINE__, tmpIFuseConn); */
                        _freeIFuseConn( tmpIFuseConn );
                    }
                    else {   /* set to timed out */
                        _ifuseDisconnect( tmpIFuseConn );
                        UNLOCK_STRUCT( *tmpIFuseConn );
                    }
                    disconned ++;
                }
                else {
                    UNLOCK_STRUCT( *tmpIFuseConn );
                }
                node = node->next;
            }
            clearListNoRegion( TimeOutList );
        }

        while ( listSize( ConnectedConn ) <= MAX_NUM_CONN || listSize( FreeConn ) != 0 ) {
            /* signal one in the wait queue */
            connReqWait_t *myConnReqWait = ( connReqWait_t * ) removeFirstElementOfConcurrentList( ConnReqWaitQue );
            /* if there is no conn req left, exit loop */
            if ( myConnReqWait == NULL ) {
                break;
            }
            myConnReqWait->state = 1;
            notifyTimeoutWait( &myConnReqWait->mutex, &myConnReqWait->cond );
        }
#if 0
        rodsSleep( CONN_MANAGER_SLEEP_TIME, 0 );
#else
        timeoutWait( &ConnManagerLock, &ConnManagerCond, CONN_MANAGER_SLEEP_TIME );
#endif


    }
    deleteListNoRegion( TimeOutList );
}
示例#21
0
///////////////////////////////////////////////////////////////////////
// Set the name of the bot and update the userinfo
///////////////////////////////////////////////////////////////////////
void ACESP_SetName(edict_t *bot, char *name, char *skin, char *team)
{
	float rnd;
	char userinfo[MAX_INFO_STRING] = "";
	char bot_skin[MAX_INFO_STRING] = "";
	char bot_name[MAX_INFO_STRING] = "";
	int i, r;

	if (NUM_BOT_SKINS == 0)
		NUM_BOT_SKINS = listSize(skinnames);

	// Set the name for the bot.
	// name
	if (strlen(name) == 0)
	{
		// Randomly select from the name/skin table
		if (num_botinfo > 0)
		{
			//int numtries = 0;
			rnd = random();
			for (i = 0; i < num_botinfo; i++)
				if (rnd < ((float)(i+1)/(float)num_botinfo) )
				{	r=i; break; }
			// Search for an unused name starting at selected pos
			for (i = r; i < num_botinfo; i++)
				if (!bot_info[i].ingame_count)
				{
					Com_sprintf(bot_name, sizeof(bot_name), bot_info[i].name);
					bot_info[i].ingame_count++;
					break;
				}
			// If none found, loop back
			if (strlen(bot_name) == 0)
				for (i = 0; i < r; i++)
					if (!bot_info[i].ingame_count)
					{
						Com_sprintf(bot_name, sizeof(bot_name), bot_info[i].name);
						bot_info[i].ingame_count++;
						break;
					}
			// If no more free bots in table, use a numbered name
			if (strlen(bot_name) == 0)
				Com_sprintf(bot_name, sizeof(bot_name), "ACEBot_%d",bot->count);
		}
		else
			Com_sprintf(bot_name, sizeof(bot_name), "ACEBot_%d",bot->count);
	}
	else
	//	strncpy(bot_name, name);
		Q_strncpyz(bot_name, name, sizeof(bot_name));

	// skin
	if (strlen(skin) == 0)
	{	// check if this bot is in the table
		for (i = 0; i < num_botinfo; i++)
		{
			if (!Q_stricmp(bot_name, bot_info[i].name))
			{
				Com_sprintf(bot_name, sizeof(bot_name), bot_info[i].name); // fix capitalization
				Com_sprintf(bot_skin, sizeof(bot_skin), bot_info[i].skin);
				bot_info[i].ingame_count++;
				break;
			}
		}

		if (strlen(bot_skin) == 0)
		{	// randomly choose skin 
			rnd = random();
			for (i = 0; i < NUM_BOT_SKINS; i++)
				if (rnd < ((float)(i + 1) / (float)NUM_BOT_SKINS))
				{
					r = i; break;
				}
			Com_sprintf(bot_skin, sizeof(bot_skin), skinnames[r]);
		}
	}
	else
	//	strncpy(bot_skin, skin);
		Q_strncpyz(bot_skin, skin, sizeof(bot_skin));
	
	// initialise userinfo
	memset(userinfo, 0, sizeof(userinfo));

	// add bot's name/skin/hand to userinfo
	Info_SetValueForKey(userinfo, "name", bot_name);
	Info_SetValueForKey(userinfo, "skin", bot_skin);
	Info_SetValueForKey(userinfo, "hand", "2"); // bot is center handed for now!

	ClientConnect (bot, userinfo);
	// Knightmare- removed this
	//ACESP_SaveBots(); // make sure to save the bots
}
示例#22
0
文件: sizeo.c 项目: Distrotech/icmake
void fun_sizeoflist ()
{
    reg = *intConstructor_i((int)listSize(top()));
}
示例#23
0
文件: test.c 项目: arktur04/test_task
int main(void)
{
    ListNode* testList = NULL;
    ListNode* node = listPushBack(&testList);
    node->data = allocData(1);
    printf("test 1\nsize = %u, last id = %i\n", listSize(&testList), getId(listBack(&testList)->data));
    //--------
    for(int i = 0; i < 100; ++i) {
        node = listPushBack(&testList); //->data = allocData(i);
        node->data = allocData(i);
    }
    printf("test 2\nsize = %u, last id = %i\n", listSize(&testList), getId(listBack(&testList)->data));
    //--------
    for(int i = 0; i < 100; ++i) {
        node = listPushFront(&testList);
        node->data = allocData(i);
    }
    printf("test 3\nsize = %u, first id = %i\n", listSize(&testList), getId(listFront(&testList)->data));
    //--------
    for(int i = 0; i < 100; ++i) {
        node = listInsert(listNext(&testList, 50));
        node->data = allocData(i);
    }
    printf("test 4\nsize = %u, id(100) = %i\n", listSize(&testList), getId(listNext(&testList, 100)->data));
    //--------
    listFree(&testList);
    if(listEmpty(&testList))
        printf("test4: list empty\n");
    //--------
    for(int i = 0; i < 100; ++i) {
        node = listPushFront(&testList);
        node->data = allocData(i);
    }
    listErase(&testList, listFront(&testList));
    printf("test 5\nsize = %u, id(0) = %i\n", listSize(&testList), getId(listFront(&testList)->data));
    listErase(&testList, listFront(&testList));
    //--------------
    listEraseRange(&testList, listNext(testList, 10), listNext(testList, 20));
    node = testList;
    for(int i = 0; i < 30; ++i) {
        printf("id(%d) = %d\n", i, ((ListData*)(node->data))->id);
        node = node->next;
    }
    printf("test 6\nsize = %u, id(10) = %i\n", listSize(&testList), getId(listFront(&testList)->data));
    //--------------
    listPopBack(&testList);
    printf("test 7\nsize = %u, id(back) = %i\n", listSize(&testList), getId(listBack(&testList)->data));
    //--------------
    listPopFront(&testList);
    printf("test 8\nsize = %u, id(front) = %i\n", listSize(&testList), getId(listFront(&testList)->data));
    //--------------
    listResize(&testList, 10);
    printf("test 9\nsize = %u, id(back) = %i\n", listSize(&testList), getId(listBack(&testList)->data));
    //--------------
    listResize(&testList, 20);
    node = testList;
    for(int i = 0; i < 20; ++i) {
        node->data = allocData(i);
        node = node->next;
    }
    printf("test 10\nsize = %u, id(back) = %i\n", listSize(&testList), getId(listBack(&testList)->data));
    return 0;
}
示例#24
0
文件: kp8.c 项目: BlagoProg/MAI
int main(void)
{
	const int N = 10;
	int i, isFound, action, pos, arg;
	List list;
	Iterator it;

	listCreate(&list, N);

	do
	{
		printf("Меню:\n");
		printf("1) Вставить элемент\n");
		printf("2) Удалить элемент\n");
		printf("3) Печать списка\n");
		printf("4) Размер списка\n");
		printf("5) Выполнить задание над списком\n");
		printf("6) Выход\n");
		printf("Выберите действие: ");
		scanf("%d", &action);

		switch (action)
		{
			case 1:
			{
				printf("Введите позицию элемента: ");
				scanf("%d", &pos);
				printf("Введите значение элемента (1 - true, 0 - false): ");
				scanf("%d", &arg);

				if (arg != 0 && arg != 1)
					printf("Ошибка. Введено недопустимое значение\n");
				else
					listInsert(&list, pos - 1, arg);

				break;
			}

			case 2:
			{
				printf("Введите номер элемента: ");
				scanf("%d", &pos);

				listRemove(&list, pos - 1);

				break;
			}

			case 3:
			{	
				listPrint(&list);

				break;
			}

			case 4:
			{
				printf("Длина списка: %d\n", listSize(&list));

				break;
			}

			case 5:
			{
				printf("Введите значение: ");
				scanf("%d", &arg);
				
				if (arg != 0 && arg != 1)
					printf("Ошибка. Введено недопустимое значение\n");
				else
				{
					it = itFirst(&list);

					isFound = 0;

					for (i = 0; i < listSize(&list); i++)
					{
						if (itFetch(&it) == arg)
						{
							while (!listEmpty(&list))
								listRemove(&list, 0);

							isFound = 1;

							break;
						}

						itNext(&it);
					}

					if (isFound)
						printf("Список был очищен, так как в нем было найдено введенное значение\n");
					else
						printf("Список не был очищен, так как в нем не найдено введенное значение\n");
				}

				break;
			}

			case 6: break;

			default:
			{
				printf("Ошибка. Такого пункта меню не существует\n");

				break;
			}
		}
	}
	while (action != 6);

	listDestroy(&list);

	return 0;
}
示例#25
0
文件: socket.c 项目: KaSt/nereamud
void input_handler() {
  LIST_ITERATOR *sock_i = newListIterator(socket_list);
  SOCKET_DATA     *sock = NULL; 

  ITERATE_LIST(sock, sock_i) {
    // Close sockects we are unable to read from, or if we have no handler
    // to take in input
    if ((FD_ISSET(sock->control, &rFd) && !read_from_socket(sock)) ||
	listSize(sock->input_handlers) == 0) {
      close_socket(sock, FALSE);
      continue;
    }

    /* Ok, check for a new command */
    next_cmd_from_buffer(sock);
    
    // are we idling?
    if(!sock->cmd_read)
      sock->idle +=  1.0 / PULSES_PER_SECOND;
    /* Is there a new command pending ? */
    else if (sock->cmd_read) {
      sock->idle = 0.0;
      IH_PAIR *pair = listGet(sock->input_handlers, 0);
      if(pair->python == FALSE) {
	void (* handler)(SOCKET_DATA *, char *) = pair->handler;
	char *cmddup = strdup(bufferString(sock->next_command));
	handler(sock, cmddup);
	free(cmddup);
      }
      else {
	PyObject *arglist = Py_BuildValue("Os", socketGetPyFormBorrowed(sock),
					  bufferString(sock->next_command));
	PyObject *retval  = PyEval_CallObject(pair->handler, arglist);

	// check for an error:
	if(retval == NULL)
	  log_pyerr("Error with a Python input handler");
	
	// garbage collection
	Py_XDECREF(retval);
	Py_XDECREF(arglist);
      }

      // append our last command to the command history. History buffer is
      // 100 commands, so pop off the earliest command if we're going over
      listPut(sock->command_hist, strdup(bufferString(sock->next_command)));
      if(listSize(sock->command_hist) > 100)
	free(listRemoveNum(sock->command_hist, 100));
      bufferClear(sock->next_command);

      // we save whether or not we read a command until our next call to
      // input_handler(), at which time it is reset to FALSE if we didn't read
      // sock->cmd_read = FALSE;
    }

#ifdef MODULE_ALIAS
    // ACK!! this is so yucky, but I can't think of a better way to do it...
    // if this command was put in place by an alias, decrement the alias_queue
    // counter by one. This counter is in place mainly so aliases do not end
    // up calling eachother and making us get stuck in an infinite loop.
    if(sock->player) {
      int alias_queue = charGetAliasesQueued(sock->player);
      if(alias_queue > 0)
	charSetAliasesQueued(sock->player, --alias_queue);
    }
#endif
  } deleteListIterator(sock_i);
}
/**
 * write a set of slice contours to a file
 */
int writeSliceContours(list *slices, char *filename) {
  listNode *sliceNode, *contNode, *vertNode, *adjNode;
  contour *cont;
  vertex *v;
  int i;

  /* open the file */
  FILE *fp = fopen(filename,"w");


  /* validate */
  if(fp == NULL) {
    fprintf(stderr,"error: surfIO.c couldn't open the slice contour file %s for writing\n", filename);
    return SR_FAILURE;
  }

  //fprintf(fp,"# slice contour file created by libsr\n# %s\n\n", SURF_IO_VERSION_C);

  /* write each slice */
  for(sliceNode = getListNode(slices,0), i = 0; sliceNode;
      sliceNode = (listNode*) sliceNode->next, i++) {
    if(sliceEmpty((list*) sliceNode->data)) continue;

    fprintf(fp,"slice %lf\n",
            ((vertex*) getListNode(((contour*)
                                    getListNode((list*) sliceNode->data,
                                                0)->data)->vertices,
                                   0)->data)->z);

    /* iterate over the contours in this slice */
    for(contNode = getListNode((list*) sliceNode->data,0); contNode;
        contNode = (listNode*) contNode->next) {
      cont = (contour*) contNode->data;

      /* print the info for this contour */
      fprintf(fp, "contour ");
      switch(cont->closed) {
        case OPEN:
          fprintf(fp,"open");
          break;
        case CLOSED:
          fprintf(fp,"closed");
          break;
      }
      fprintf(fp,"\n");

      /* iterate over the vertices, writing each */
      for(vertNode = getListNode(cont->vertices,0); vertNode;
          vertNode = (listNode*) vertNode->next) {
        v = (vertex*) vertNode->data;

        fprintf(fp,"%lf %lf\n", v->x, v->y);
      }


      fprintf(fp,"adjacent\n");
      /* iterate over the adjacent contours, writing the indices */
      for(adjNode = getListNode(cont->adjacentContours,0);
          i+1 < listSize(slices)&& adjNode;
          adjNode = (listNode*) adjNode->next) {
        fprintf(fp, "%d ", findInListI((list*) getListNode(slices,i+1)->data,
                                       adjNode->data));
      }
      fprintf(fp,"-1\n");

    }
  }

  fclose(fp);

  return SR_SUCCESS;
}
Cipher::Cipher(int index, int public_cipher): QDialog()
{
    setFixedSize(800, 400);
    this->setWindowTitle("Cipher");

    labelPlain = new QLabel("Choose file to cipher :",this);
    labelCipher = new QLabel("Name the output file :",this);    
    if(public_cipher)
        labelKey = new QLabel("Choose which key to use :",this);
    else
        labelKey = new QLabel("Type in your passphrase :", this);
    labelMode = new QLabel("Block chaining mode and size :");
    labelIv = new QLabel("Enter IV :", this);

    buttonBrowsePlain = new QPushButton("Browse", this);
    if(public_cipher)
        buttonBrowseKey = new QPushButton("Browse", this);
    buttonCancel = new QPushButton("Cancel", this);
    buttonCompute = new QPushButton("Compute", this);

    //QStringList listMode(QStringList() << "CBC");
    QStringList listSize(QStringList() << "128" << "256");

    if(index == 4)
    {
        comboSize->addItem("128", GCRY_CIPHER_AES);
        comboSize->addItem("256", GCRY_CIPHER_AES256);
    }

    comboMode = new QComboBox(this);
    //comboMode->addItems(listMode);

    comboMode->addItem("CBC", GCRY_CIPHER_MODE_CBC);

    comboSize = new QComboBox(this);
    comboSize->addItems(listSize);

    lePlain = new QLineEdit(this);
    leCipher = new QLineEdit(this);
    leKey = new QLineEdit(this);

    // EchoMode(1) sets a password type of echo
    if(!public_cipher)
        leKey->setEchoMode(QLineEdit::Password);

    leIv = new QLineEdit(this);
    leIv->setEnabled(false);

    radioIv = new QRadioButton(tr("Manually enter IV"));

    fdPlain = new QFileDialog(this);
    fdKey = new QFileDialog(this);

    fdPlain->setDirectory("../ressources/");
    fdKey->setDirectory("../ressources/");

    QStringList listFilters;

    if(public_cipher)
        listFilters << "*.puKey" << "*";
    else
        listFilters << "*.key" << "*";

    fdKey->setNameFilters(listFilters);

    gl = new QGridLayout(this);

    gl->addWidget(labelPlain, 0, 0);
    gl->addWidget(lePlain, 0, 1);
    gl->addWidget(buttonBrowsePlain, 0, 2);

    gl->addWidget(labelKey, 1, 0);
    gl->addWidget(leKey, 1, 1);

    if(public_cipher)
        gl->addWidget(buttonBrowseKey, 1, 2);

    gl->addWidget(labelMode, 2, 0);
    gl->addWidget(comboMode, 2, 1);
    gl->addWidget(comboSize, 2, 2);

    gl->addWidget(labelIv, 3, 0);

    // index == 4 is AES; we want a 128 bits IV only
    if(index == 4)
        leIv->setMaxLength(gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES));
    // index = 5 3DES, IV is 64 bits
    else if(index == 5)
        leIv->setMaxLength(gcry_cipher_get_algo_blklen(GCRY_CIPHER_3DES));

    gl->addWidget(leIv, 3, 1);
    gl->addWidget(radioIv, 3, 2);

    gl->addWidget(labelCipher, 4, 0);
    gl->addWidget(leCipher, 4, 1);

    gl->addWidget(buttonCancel, 5, 1);
    gl->addWidget(buttonCompute, 5, 2);

    this->setLayout(gl);

    QObject::connect(radioIv,SIGNAL(clicked()), this, SLOT(hideIvBox()));

    QObject::connect(buttonCancel,SIGNAL(clicked()),this,SLOT(close()));
    QObject::connect(buttonBrowsePlain, SIGNAL(clicked()), fdPlain, SLOT(exec()));

    if(public_cipher)
        QObject::connect(buttonBrowseKey, SIGNAL(clicked()), fdKey, SLOT(exec()));

    QObject::connect(fdPlain, SIGNAL(fileSelected(QString)), lePlain, SLOT(setText(QString)));
    QObject::connect(fdKey, SIGNAL(fileSelected(QString)), leKey, SLOT(setText(QString)));

    switch(index){
        case 0:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRSA()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 1:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeElGamal()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 2:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRabin()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 3:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeRSAOAEP()));
            comboMode->setEnabled(false);
            comboSize->setEnabled(false);
            leIv->setEnabled(false);
            break;
        case 4:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeAES()));
            break;
        case 5:
            QObject::connect(buttonCompute, SIGNAL(clicked()), this, SLOT(computeDES()));
            break;
        default:
            this->close();
            break;
    }
}
示例#28
0
/*Build Minimax Tree for Best Difficulty using BFS Algorithm*/
MinimaxNode *getMinimaxTreeBestDepth(Game *game, Color uCol) {
    MinimaxNode *root = (MinimaxNode*)malloc(sizeof(MinimaxNode));
    if (root == NULL)exitOnError("malloc");
    root->game = (Game*)malloc(sizeof(Game));
    if (root->game == NULL) exitOnError("malloc");
    root->val = 0;
    MinimaxNode *curr;
    ListNode *moves;
    int i;
    int leavesLocal = 1;
    Queue *q = setQueue(); /*Create empty Queue for BFS Traversing*/
    int size = 0;
    root->depth = 0;
    root->move = NULL;
    copyGame(game, root->game);
    root->sons = NULL;
    root->sonsK = 0;
    enqueue(q, root);
    /*While Queue is not empty and there are less than MAX_BOARDS_TO_EVAL Leaves in Tree*/
    while (q->size&&leavesLocal + size <= MAX_BOARDS_TO_EVAL) {
        curr = dequeue(q); /*Pop from Queue*/
        if (curr->depth % 2 == 0)moves = getMoves(curr->game, uCol); /*Get possible Moves at current Board state*/
        else moves = getMoves(curr->game, oppositeCol(uCol));
        size = listSize(moves);
        if (!size) {
            free(moves);
            continue;
        }
        curr->sons = (MinimaxNode**)malloc(sizeof(MinimaxNode)*size);
        if (curr->sons == NULL) exitOnError("malloc");
        curr->sonsK = size;
        ListNode *temp = moves;
        for (i = 0; i < size; i++) { /*Add Nodes for each possible Move*/
            curr->sons[i] = (MinimaxNode*)malloc(sizeof(MinimaxNode));
            if (curr->sons[i] == NULL) exitOnError("malloc");
            curr->sons[i]->game = (Game*)malloc(sizeof(Game));
            if (curr->sons[i]->game == NULL) exitOnError("malloc");
            curr->sons[i]->val = 0;
            copyGame(curr->game, curr->sons[i]->game);
            Move* tMove = copyMove(temp->move);
            updateBoard(curr->sons[i]->game, tMove);
            curr->sons[i]->depth = curr->depth + 1;
            if (curr->sons[i]->depth == 1) {
                curr->sons[i]->move = tMove;
            }
            else {
                freeMove(tMove);
                curr->sons[i]->move = NULL;
            }
            curr->sons[i]->sons = NULL;
            curr->sons[i]->sonsK = 0;
            enqueue(q, curr->sons[i]); /*Push to Queue*/
            temp = temp->next;
        }
        /*Update amount of Leaves in Tree*/
        freeList(moves);
        leavesLocal += size;
        if (size) leavesLocal--;
    }
    freeQueue(q);
    return root;
}
示例#29
0
文件: kp8.c 项目: BlagoProg/MAI
int main(void)
{
	const int N = 10;
	int i, isFound, action, pos, arg;
	List list;
	Iterator it1, it2;

	listCreate(&list, N);

	do
	{
		printf("Меню:\n");
		printf("1) Вставить элемент\n");
		printf("2) Удалить элемент\n");
		printf("3) Печать списка\n");
		printf("4) Подсчет длины списка\n");
		printf("5) Выполнить задание над списком\n");
		printf("6) Выход\n");
		printf("Выберите действие: ");
		scanf("%d", &action);

		switch (action)
		{
			case 1:
			{
				printf("Введите позицию элемента: ");
				scanf("%d", &pos);
				printf("Введите значение элемента (1 - true, 0 - false): ");
				scanf("%d", &arg);

				if (arg != 0 && arg != 1)
					printf("Ошибка. Введено недопустимое значение\n");
				else
					listInsert(&list, pos - 1, arg);

				break;
			}

			case 2:
			{
				printf("Введите номер элемента: ");
				scanf("%d", &pos);

				listRemove(&list, pos - 1);

				break;
			}

			case 3:
			{
				if (listEmpty(&list))
					printf("Список пуст\n");
				else
					listPrint(&list);

				break;
			}

			case 4:
			{
				printf("Длина списка: %d\n", listSize(&list));

				break;
			}

			case 5:
			{
				it1 = itFirst(&list);
				it2 = it1;

				itNext(&it2);

				for (i = 0; i < listSize(&list) / 2; i++)
				{
					listSwapElems(&it1, &it2);

					itNext(&it1);
					itNext(&it1);
					itNext(&it2);
					itNext(&it2);
				}

				break;
			}

			case 6: break;

			default:
			{
				printf("Ошибка. Такого пункта меню не существует\n");

				break;
			}
		}
	}
	while (action != 6);

	listDestroy(&list);

	return 0;
}