Beispiel #1
0
RBTree<KEY>::~RBTree()
{
    MakeEmpty();
}
VJSObject::VJSObject( const VJSObject& inParent, const XBOX::VString& inPropertyName, JS4D::PropertyAttributes inAttributes):fContext(inParent.fContext) // build an empty object as a property of a parent object
{
	MakeEmpty();
	inParent.SetProperty(inPropertyName, *this, inAttributes);
}
Beispiel #3
0
void DisposeStack (Stack S) {
	MakeEmpty (S);
//	free (S);
}
Beispiel #4
0
  bool ClipAgainst (iClipper2D* clipper)
  {
    size_t clipOutputVerts = dest.GetVertexCount() + clipper->GetVertexCount();
    CS_ALLOC_STACK_ARRAY(csVector2, clipOut, clipOutputVerts);
    CS_ALLOC_STACK_ARRAY(csVertexStatus, clipOutStatus, clipOutputVerts);
    size_t outNum;
    csPoly2D destPx;
    destPx.SetVertexCount (dest.GetVertexCount());
    for (size_t p = 0; p < dest.GetVertexCount(); p++)
    {
      destPx[p].Set (dest[p].x, dest[p].y);
    }
    uint8 clipRes = clipper->Clip (
      destPx.GetVertices(), destPx.GetVertexCount(), clipOut, outNum,
      clipOutStatus);
    CS_ASSERT(outNum <= clipOutputVerts);
    if (clipRes == CS_CLIP_OUTSIDE) return false;
    if (clipRes == CS_CLIP_INSIDE) return true;
    
    csPoly2D orgDest2D (destPx);
    csPoly3D orgDest3D (dest3D);
    MakeEmpty ();
      
    for (size_t i = 0 ; i < outNum; i++)
    {
      dest.AddVertex (csVector2 (clipOut[i].x, clipOut[i].y));
      switch (clipOutStatus[i].Type)
      {
	case CS_VERTEX_ORIGINAL:
	  {
	    const size_t vt = clipOutStatus[i].Vertex;
	    dest3D.AddVertex (orgDest3D[vt]);
          }
	  break;
	case CS_VERTEX_ONEDGE:
	  {
	    const size_t vt = clipOutStatus[i].Vertex;
	    const size_t vt2 = (vt+1) % orgDest3D.GetVertexCount();
	    const float t = clipOutStatus[i].Pos;

            dest3D.AddVertex (LerpPC (orgDest3D[vt], orgDest3D[vt2], t));
	  }
          break;
	case CS_VERTEX_INSIDE:
	  {
	    float x = clipOut[i].x;
	    float y = clipOut[i].y;
	    size_t edge[2][2];
	    int edgeToFind = 0;
	    // Determine edges from which to interpolate the vertex data
	    size_t lastVert = orgDest2D.GetVertexCount() - 1;
	    for (size_t v = 0; v < orgDest2D.GetVertexCount(); v++)
	    {
	      if ((fabs(orgDest2D[lastVert].y - orgDest2D[v].y) > SMALL_EPSILON) 
		&& ((y >= orgDest2D[lastVert].y && y <= orgDest2D[v].y)
		|| (y <= orgDest2D[lastVert].y && y >= orgDest2D[v].y)))
	      {
		edge[edgeToFind][0] = lastVert;
		edge[edgeToFind][1] = v;
		edgeToFind++;
		if (edgeToFind >= 2) break;
	      }
	      lastVert = v;
	    }
	    CS_ASSERT(edgeToFind >= 2);
	    const csVector2& A = orgDest2D[edge[0][0]];
	    const csVector2& B = orgDest2D[edge[0][1]];
	    const csVector2& C = orgDest2D[edge[1][0]];
	    const csVector2& D = orgDest2D[edge[1][1]];
	    // Coefficients
	    const float t1 = (y - A.y) / (B.y - A.y);
	    const float t2 = (y - C.y) / (D.y - C.y);
	    const float x1 = A.x + t1 * (B.x - A.x);
	    const float x2 = C.x + t2 * (D.x - C.x);
	    const float dx = (x2 - x1);
	    const float t = dx ? ((x - x1) / dx) : 0.0f;
	    
	    dest3D.AddVertex (LerpPC (
	      LerpPC (orgDest3D[edge[0][0]], orgDest3D[edge[0][1]], t1),
	      LerpPC (orgDest3D[edge[1][0]], orgDest3D[edge[1][1]], t2),
	      t));
          }
	  break;
	default:
	  CS_ASSERT(false);
      }
    }
      
    return true;
  }
Beispiel #5
0
main ( int argc, char **argv)
{
   struct sockaddr_in sa;
   struct sockaddr_in caller;
   int ssd, csd, length, flag = 1 ;
   char cnt_name[ 20 ] ;
   int i, n, key, savesig ;
   pid_t pid, loop_pid ;
   struct client_ds *c_data ;
   struct sigaction usr2act ;
   sigset_t usr2mask, savemask, zeromask ;

   if ( argc != 2 ) 
	   err_quit ( "Usage: %s <port>", argv[0] ) ;

   if ( signal ( SIGUSR1, SIG_IGN ) == SIG_ERR ) 
	   err_sys ( "signal error" ) ;
   if ( signal ( SIGINT, sig_term ) == SIG_ERR ) 
	   err_sys ( "signal error" ) ;
   usr2act.sa_handler = sigusr2 ;
   usr2act.sa_flags = SA_NOMASK ;
   if ( sigaction ( SIGUSR2, &usr2act, NULL ) == -1 )
	   err_sys ( "sigaction error" ) ;
   sigemptyset ( &zeromask ) ;
   sigemptyset ( &usr2mask ) ;
   sigaddset ( &usr2mask, SIGUSR2 ) ;

   atexit ( end_func ) ;
   
   key = p_key = atoi(argv[1]) ;
   sa.sin_family= AF_INET;
   sa.sin_addr.s_addr = INADDR_ANY;
   sa.sin_port= htons((u_short)atoi(argv[1])) ;
   
   if ((ssd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
     err_sys ("socket error");
   if (bind(ssd, (struct sockaddr *)&sa, sizeof sa) < 0)
     err_sys ("bind error");

   if ( ( p_semid = semget ( p_key, 1, IPC_CREAT | 0700 ) ) == -1 )
		err_sys ( "semget error" ) ;
   init ( p_semid, 0 ) ;
   if ( ( p_shmid = shmget ( p_key, 8192, IPC_CREAT | 0700 ) ) == -1 )
		err_sys ( "shmget" ) ;
   write_shm ( p_semid, p_shmid, "No Data" ) ;

   if ( listen (ssd, MAXCLIENT) )
	   err_quit ( "listen error" ) ;
   length = sizeof(sa);
   L_Client = MakeEmpty ( L_Client ) ;

   i = 0 ;
   while ( flag )  {
	   sigsetjmp ( s_env, savesig ) ;
	   printf ( "Waiting for Connection...\n" ) ;
	   if ((csd = accept(ssd, (struct sockaddr *)&caller, &length)) < 0)
		   err_sys ( "acccept" ) ;

	   if ( sigprocmask ( SIG_BLOCK, &usr2mask, &savemask ) < 0 )
		   err_quit ( "sigprocmask error" ) ;
		   if ( c_count == MAXCLIENT ) {
			  send ( csd, "server is too busy!!!\n", 23, MSG_DONTWAIT ) ;
	   	      if ( sigprocmask ( SIG_SETMASK, &savemask, NULL ) < 0 )
	   		   	   err_quit ( "sigprocmask error" ) ;
			  close( csd ) ;
			  siglongjmp ( s_env, 0 ) ;
		   }
		   c_data = malloc ( sizeof ( struct client_ds ) ) ;

		   if ( ( n = recv ( csd, cnt_name, sizeof(cnt_name), 0 ) ) < 0 )
			   err_sys ( "read error" ) ;
		   if ( cnt_name[ n-1 ] == '\n' )
			   cnt_name[ n-1 ] = 0 ;
		   cnt_name[ n ] = 0 ;
		   strcpy ( c_data->c_name, cnt_name ) ;
		   if ( ( c_data->c_semid = semget ( ++key, 1, IPC_CREAT | 0700 ) ) == -1 )
				err_sys ( "semget error" ) ;
		   init ( c_data->c_semid, 0 ) ;
		   if ( ( c_data->c_shmid = shmget ( key, 8192, IPC_CREAT | 0700 ) ) == -1 )
				err_sys ( "shmget" ) ;
		   write_shm ( c_data->c_semid, c_data->c_shmid, "No Data" ) ;
		   c_data->c_fd = csd ;
		   c_data->c_pid = 0 ;

		   printf (  "Client is connected %d\n", csd ) ;
		   if ( ( pid = fork ( ) ) ==  -1 )
			   err_sys ( "fork error" ) ;
		   else if ( pid == 0 ) {
			   close( ssd ) ;
			   if ( handle_client ( c_data ) != 0 )
				   err_sys ( "error handling client" ) ;
			   printf ( "Exiting\n" ) ;
			   exit ( 0 ) ;
		   }
		   c_data->c_pid = pid ;
		   if ( waitpid ( pid, NULL, WNOHANG ) == -1 )
			   err_sys ( "waitpid error"  );
		   Insert ( c_data, L_Client, L_Client ) ;
		   c_count++ ;

	   if ( sigprocmask ( SIG_SETMASK, &savemask, NULL ) < 0 )
		   err_quit ( "sigprocmask error" ) ;
   }
   close(ssd);

   printf ( "Removing Public Shared memory\n" ) ;
   semdel ( p_semid ) ;
   shmdel ( p_shmid ) ;

   exit(0);
}
Beispiel #6
0
SStringArray::~SStringArray()
{
	MakeEmpty();
}
Beispiel #7
0
int main(int argc, char *argv[]){
	
	FILE *net_file; //Input network file
	char filename_in[100]; //Input network file path
	char prefix_out[100]; //Input network file path

	int nodes, edges, starting_node, variation, hierarchy;
	
	int display = 2;
		
	struct timeval start, end;
	gettimeofday(&start, NULL);
	
	float diff;
	
	parse_args(argc,argv,&nodes,&edges,&starting_node,&display,&variation,&hierarchy,filename_in,prefix_out);
	
	net_file = fopen(filename_in, "r");
	if(display >= 1){
		printf("Reading network from file %s...\n", filename_in);
	}
	if (net_file == NULL){
		printf("Error while reading network from %s.\n", filename_in);
		return 0;
	}
	
		
	if(display >= 1){
		printf("Network successfully read: %d nodes and %d edges. ", nodes, edges);
		printf("Here we go!\n");
	 	  	printf("Generating data structures (AVL)... \n");
   	}
    
    double *k;
    k = (double*) malloc(sizeof(double)*nodes); // free OK
    int i;
    for(i = 0 ; i < nodes ; i++){
    	k[i] = 0;
    }
    
  	AvlTree *AvlNet;
	AvlNet = (AvlTree*) malloc(sizeof(AvlTree) * nodes); // free OK
	ReadNetworkToAVL(net_file, nodes, edges, display, AvlNet,k);
	
	printf("Running CNM... \n");
	
	char out_filename[100];
	sprintf(out_filename,"out/%s_out.txt",prefix_out);
	FILE *out_file;
	out_file = fopen(out_filename, "w");
	
	CNM(AvlNet,k,nodes,edges,variation,display,hierarchy,prefix_out,out_file);
   
   	fclose(net_file);
   	
	   
    gettimeofday(&end, NULL);
    diff = end.tv_sec - start.tv_sec + (double)(end.tv_usec - start.tv_usec)/CLOCKS_PER_SEC;
    
    if(display >= 1){
    	printf("Done. (Total time: %.2f seconds)\n", diff);
	}
	
	fprintf(out_file,"Done. Total time: %.2f seconds \n", diff);
	
	
	fclose(out_file);
		
	
	for(i = 0 ; i < nodes ; i++){
		MakeEmpty(AvlNet[i]);
	}
	free(AvlNet);
	free(k);
	return 0;
}
Beispiel #8
0
        /* memError:
	 * Function that safely exits
	 * program
	 */
	void memError(SearchTree head)
	{
		fprintf(stderr,"I can't allocate that ... much... mem-ahhhh...");
		MakeEmpty(head);
		exit(1);
	}/*end memError*/
Beispiel #9
0
void CSelection::EnsureVisible( BOOL bScrollIfNeccessary, BOOL bCanCenter, BOOL bPreserveSelIfPossible )
{
    int nTopIndex = m_pView->GetTopIndex();
    int nBottomIndex = m_pView->GetBottomIndex( TRUE );
    int nLeftIndex = m_pView->GetLeftIndex();
    int nRightIndex = m_pView->GetRightIndex( TRUE );

    if ( bScrollIfNeccessary )
    {
        int nViewWidth = nRightIndex - nLeftIndex;
        BOOL bNeedToScroll = FALSE;
        if ( bCanCenter && ( m_nStartRow == m_nEndRow ) && !IsEmpty() )
        {
            // entire selection is on one line -- if can fit within entire view, do so.
            int nSelWidth = m_nEndViewCol - m_nStartViewCol;
            if ( nSelWidth < 0 )
            {
                nSelWidth = -nSelWidth;
            }
            if ( nSelWidth < nViewWidth )
            {
                nLeftIndex = ( m_nEndViewCol < nViewWidth ) ? 0 : m_nStartViewCol - ( nViewWidth - nSelWidth ) / 2;
                bNeedToScroll = TRUE;
            }
        }
        if ( !bNeedToScroll )
        {
            if ( m_nEndViewCol < nLeftIndex )
            {
                // try to scroll all the way back to col 0
                nLeftIndex = ( m_nEndViewCol < nViewWidth ) ? 0 : m_nEndViewCol;
                bNeedToScroll = TRUE;
            }
            else if ( m_nEndViewCol > nRightIndex )
            {
                int nTemp = m_nEndViewCol - MulDiv( nViewWidth, 3, 4 );
                nLeftIndex = max( 0, nTemp );
                bNeedToScroll = TRUE;
            }
        }
        if ( m_nEndRow < nTopIndex )
        {
            nTopIndex = m_nEndRow;
            bNeedToScroll = TRUE;
        }
        else if ( m_nEndRow > nBottomIndex )
        {
            int nTemp = m_nEndRow - ( nBottomIndex - nTopIndex );
            nTopIndex = max( 0, nTemp );
            bNeedToScroll = TRUE;
        }

        if ( bNeedToScroll )
        {
            // if one-char increment, do smooth scrolling
            int nLeft = m_pView->GetLeftIndex();
            int nTop = m_pView->GetTopIndex();
            BOOL bSmooth = ( ( nLeftIndex == nLeft && ( nTop - nTopIndex ) * ( nTop - nTopIndex ) == 1 ) ||
                             ( nTopIndex == nTop && ( nLeft - nLeftIndex ) * ( nLeft - nLeftIndex ) == 1 ) );
            m_pView->ScrollTo( nLeftIndex, nTopIndex, bSmooth );
        }
    }
    else
    {
        BOOL bWasEmpty = IsEmpty();
        BOOL bSelChanged = FALSE;
        if ( m_nEndViewCol < nLeftIndex )
        {
            m_nEndViewCol = nLeftIndex;
            bSelChanged = TRUE;
        }
        else if ( m_nEndViewCol > nRightIndex )
        {
            m_nEndViewCol = nRightIndex;
            bSelChanged = TRUE;
        }
        if ( m_nEndRow < nTopIndex )
        {
            m_nEndRow = nTopIndex;
            bSelChanged = TRUE;
        }
        else if ( m_nEndRow > nBottomIndex )
        {
            m_nEndRow = nBottomIndex;
            bSelChanged = TRUE;
        }

        // update the buffer position, regardless of the selection bounding setting.
        m_nEndCol = m_pCtrl->GetBuffer()->ConvertViewColToBufferCol( m_nEndRow, m_nEndViewCol );

        if ( bSelChanged || !bPreserveSelIfPossible )
        {
            MakeEmpty( !bWasEmpty );
        }
    }

    UpdateCaretPosition();
}
Beispiel #10
0
status_t SettingsFile::Load()
{
	status_t ret;
	BFile file(path.Path(), B_READ_ONLY);
	ret = file.InitCheck();
	if (ret != B_OK) {
		return ret;
	}
	ret = file.Lock();
	if (ret != B_OK) {
		return ret;
	}
	ret = Unflatten(&file);
	if (ret != B_OK) {
		file.Unlock();
		MakeEmpty();
		return ret;
	}

	if (vision_app->fDebugSettings) PrintToStream();
	/*
		ret=file.RewindAttrs();
		if (ret!=B_OK) {
			file.Unlock();
			MakeEmpty();
			return ret;
		}
		char attr_name[B_ATTR_NAME_LENGTH];
		while ((ret=file.GetNextAttrName(attr_name))!=B_ENTRY_NOT_FOUND) { // walk all the
	   attributes of the settings file
			if (ret!=B_OK) {
				file.Unlock();
				return ret;
			}
				// found an attribute
			attr_info ai;
			ret=file.GetAttrInfo(attr_name,&ai);
			if (ret!=B_OK) {
				file.Unlock();
				return ret;
			}
			switch (ai.type) {
				case B_CHAR_TYPE :
				case B_STRING_TYPE :
				case B_BOOL_TYPE :
				case B_INT8_TYPE :
				case B_INT16_TYPE :
				case B_INT32_TYPE :
				case B_INT64_TYPE :
				case B_UINT8_TYPE :
				case B_UINT16_TYPE :
				case B_UINT32_TYPE :
				case B_UINT64_TYPE :
				case B_FLOAT_TYPE :
				case B_DOUBLE_TYPE :
				case B_OFF_T_TYPE :
				case B_SIZE_T_TYPE :
				case B_SSIZE_T_TYPE :
				case B_POINT_TYPE :
				case B_RECT_TYPE :
				case B_RGB_COLOR_TYPE :
				case B_TIME_TYPE :
				case B_MIME_TYPE : {
					char*partial_name=strdup(attr_name);
					if (partial_name==NULL) {
						file.Unlock();
						return B_NO_MEMORY;
					}
					ret=_ExtractAttribute(this,&file,attr_name,partial_name,&ai);
					free(partial_name);
					if (ret!=B_OK) {
						file.Unlock();
						return ret;
					}
					break;
				}
			}
		}
	*/
	file.Unlock();
	return B_OK;
}
Beispiel #11
0
//------------------------------------------------------------------------------
PortQueue::~PortQueue(void)
{
	MakeEmpty();
}
Beispiel #12
0
		AreaLinkHeader() { MakeEmpty(); fLock = B_NAME_NOT_FOUND; }
Beispiel #13
0
nsSelectionState::~nsSelectionState() 
{
  MakeEmpty();
}
Beispiel #14
0
void RBTree<KEY>::MakeEmpty()
{
    MakeEmpty(m_root);
    delete m_null;
}
/**
 * main
 * Initilises an tree with a single node with a null value.
 *
 * @param
 * @return 0
 */
int main()
{
	SearchTree Tree;
	char menuChoice;
	int intElement;
	int i=0;
	char stringElement [22];
	int stringValue=0;

	// Initilise tree with a null element
	Tree = MakeEmpty( NULL );

	Tree = readFromFile(Tree);

	temparray = ((char*)malloc(22*sizeof(char)));
	strcpy(temparray,"null");

	Print(Tree);
	writeToFile(Tree);

	//printf("\n Temp Array : %s\n",temparray);

	/*
	do { 	// Do while the user does not want to exit the program
		menuChoice =  menu(menuChoice);
		stringValue=0;

		switch( menuChoice )  {
			case 'a': {

				printf("\n Inserting String : ");
				scanf(" %s",stringElement);

				for(i=0;i<strlen(stringElement);i++)
				{
					stringValue += *stringElement;
				}
				printf("\n String  : %s\n",stringElement);
				printf(" At Node : %d\n",stringValue);

				strcpy(temparray,stringElement);

				Tree = Insert( stringElement, stringValue, Tree );
				break;
			}
			case 'b': { // Searcing the tree for an integer
				int valueAtTree;
				printf("\n Search for integer : ");
				scanf(" %d",&intElement);
				Tree = Find( intElement, Tree );
				if(Tree!=NULL) {
					valueAtTree = Retrieve( Tree );
					printf("\n Element : %d is present in Tree \n",valueAtTree );
				}
				else {
					printf("\n Element : %d is not present in Tree \n",intElement );
				}
				break;
			}
			case 'c': { // Printing the current tree inorder
				printf("\n Printing Current Tree inorder :\n");
				Print(Tree);
				writeToFile(Tree);
				break;
			}
			case 'd': { // Emptying tree and creating a new tree
				printf("\n Emptying Tree and initialising new tree.");
				Tree = MakeEmpty( NULL );
				printf("\n");
				break;
			}
			case 'e': {
				printf(" \n Exit.");
				break;
			}
			default : {
				printf("\n Invalid Selection %d",menuChoice);
				break;
			}
		}
	}while(menuChoice!='E');
	*/

	printf("\n\n Program Complete.");
return 0;
}
Beispiel #16
0
void CSelection::SelectWord()
{
    MakeEmpty( FALSE );
    Extend( CSelection::eOutward, CSelection::eWord, FALSE, FALSE, FALSE );
}
Beispiel #17
0
QueueType<ItemType>::~QueueType()
{
    MakeEmpty();
}
Beispiel #18
0
StackType<ItemType>::~StackType()
{
  MakeEmpty();
}
Beispiel #19
0
 void
 Destroy( PairHeap H )
 {
     MakeEmpty( H );
 }
nsresult nsContentSubtreeIterator::Init(nsIDOMRange* aRange)
{
  if (!aRange) 
    return NS_ERROR_NULL_POINTER; 

  mIsDone = PR_FALSE;

  mRange = aRange;
  
  // get the start node and offset, convert to nsINode
  nsCOMPtr<nsIDOMNode> commonParent;
  nsCOMPtr<nsIDOMNode> startParent;
  nsCOMPtr<nsIDOMNode> endParent;
  nsCOMPtr<nsINode> nStartP;
  nsCOMPtr<nsINode> nEndP;
  nsCOMPtr<nsINode> n;
  nsINode *firstCandidate = nsnull;
  nsINode *lastCandidate = nsnull;
  PRInt32 indx, startIndx, endIndx;

  // get common content parent
  if (NS_FAILED(aRange->GetCommonAncestorContainer(getter_AddRefs(commonParent))) || !commonParent)
    return NS_ERROR_FAILURE;
  mCommonParent = do_QueryInterface(commonParent);

  // get start content parent
  if (NS_FAILED(aRange->GetStartContainer(getter_AddRefs(startParent))) || !startParent)
    return NS_ERROR_FAILURE;
  nStartP = do_QueryInterface(startParent);
  aRange->GetStartOffset(&startIndx);

  // get end content parent
  if (NS_FAILED(aRange->GetEndContainer(getter_AddRefs(endParent))) || !endParent)
    return NS_ERROR_FAILURE;
  nEndP = do_QueryInterface(endParent);
  aRange->GetEndOffset(&endIndx);

  // short circuit when start node == end node
  if (startParent == endParent)
  {
    nsINode* nChild = nStartP->GetChildAt(0);
  
    if (!nChild) // no children, must be a text node or empty container
    {
      // all inside one text node - empty subtree iterator
      MakeEmpty();
      return NS_OK;
    }
    else
    {
      if (startIndx == endIndx)  // collapsed range
      {
        MakeEmpty();
        return NS_OK;
      }
    }
  }
  
  // cache ancestors
#if 0
  nsContentUtils::GetAncestorsAndOffsets(startParent, startIndx,
                                         &mStartNodes, &mStartOffsets);
#endif
  nsContentUtils::GetAncestorsAndOffsets(endParent, endIndx,
                                         &mEndNodes, &mEndOffsets);

  // find first node in range
  aRange->GetStartOffset(&indx);

  if (!nStartP->GetChildCount()) // no children, start at the node itself
  {
    n = nStartP;
  }
  else
  {
    nsINode* nChild = nStartP->GetChildAt(indx);
    if (!nChild)  // offset after last child
    {
      n = nStartP;
    }
    else
    {
      firstCandidate = nChild;
    }
  }
  
  if (!firstCandidate)
  {
    // then firstCandidate is next node after cN
    firstCandidate = GetNextSibling(n, nsnull);

    if (!firstCandidate)
    {
      MakeEmpty();
      return NS_OK;
    }
  }
  
  firstCandidate = GetDeepFirstChild(firstCandidate, nsnull);
  
  // confirm that this first possible contained node
  // is indeed contained.  Else we have a range that
  // does not fully contain any node.
  
  PRBool nodeBefore, nodeAfter;
  if (NS_FAILED(nsRange::CompareNodeToRange(firstCandidate, aRange,
                                            &nodeBefore, &nodeAfter)))
    return NS_ERROR_FAILURE;

  if (nodeBefore || nodeAfter)
  {
    MakeEmpty();
    return NS_OK;
  }

  // cool, we have the first node in the range.  Now we walk
  // up its ancestors to find the most senior that is still
  // in the range.  That's the real first node.
  if (NS_FAILED(GetTopAncestorInRange(firstCandidate, address_of(mFirst))))
    return NS_ERROR_FAILURE;

  // now to find the last node
  aRange->GetEndOffset(&indx);
  PRInt32 numChildren = nEndP->GetChildCount();

  if (indx > numChildren) indx = numChildren;
  if (!indx)
  {
    n = nEndP;
  }
  else
  {
    if (!numChildren) // no children, must be a text node
    {
      n = nEndP;
    }
    else
    {
      lastCandidate = nEndP->GetChildAt(--indx);
      NS_ASSERTION(lastCandidate,
                   "tree traversal trouble in nsContentSubtreeIterator::Init");
    }
  }
  
  if (!lastCandidate)
  {
    // then lastCandidate is prev node before n
    lastCandidate = GetPrevSibling(n, nsnull);
  }
  
  lastCandidate = GetDeepLastChild(lastCandidate, nsnull);
  
  // confirm that this last possible contained node
  // is indeed contained.  Else we have a range that
  // does not fully contain any node.
  
  if (NS_FAILED(nsRange::CompareNodeToRange(lastCandidate, aRange, &nodeBefore,
                                            &nodeAfter)))
    return NS_ERROR_FAILURE;

  if (nodeBefore || nodeAfter)
  {
    MakeEmpty();
    return NS_OK;
  }

  // cool, we have the last node in the range.  Now we walk
  // up its ancestors to find the most senior that is still
  // in the range.  That's the real first node.
  if (NS_FAILED(GetTopAncestorInRange(lastCandidate, address_of(mLast))))
    return NS_ERROR_FAILURE;
  
  mCurNode = mFirst;

  return NS_OK;
}
Beispiel #21
0
/*
======================
CreateStaticInteraction

Called by idRenderWorldLocal::GenerateAllInteractions
======================
*/
void idInteraction::CreateStaticInteraction() {
	// note that it is a static interaction
	staticInteraction = true;
	const idRenderModel *model = entityDef->parms.hModel;
	if ( model == NULL || model->NumSurfaces() <= 0 || model->IsDynamicModel() != DM_STATIC ) {
		MakeEmpty();
		return;
	}

	const idBounds bounds = model->Bounds( &entityDef->parms );

	// if it doesn't contact the light frustum, none of the surfaces will
	if ( R_CullModelBoundsToLight( lightDef, bounds, entityDef->modelRenderMatrix ) ) {
		MakeEmpty();
		return;
	}

	//
	// create slots for each of the model's surfaces
	//
	numSurfaces = model->NumSurfaces();
	surfaces = (surfaceInteraction_t *)R_ClearedStaticAlloc( sizeof( *surfaces ) * numSurfaces );

	bool interactionGenerated = false;

	// check each surface in the model
	for ( int c = 0 ; c < model->NumSurfaces() ; c++ ) {
		const modelSurface_t * surf = model->Surface( c );
		const srfTriangles_t * tri = surf->geometry;
		if ( tri == NULL ) {
			continue;
		}

		// determine the shader for this surface, possibly by skinning
		// Note that this will be wrong if customSkin/customShader are
		// changed after map load time without invalidating the interaction!
		const idMaterial * const shader = R_RemapShaderBySkin( surf->shader, 
												entityDef->parms.customSkin, entityDef->parms.customShader );
		if ( shader == NULL ) {
			continue;
		}

		// try to cull each surface
		if ( R_CullModelBoundsToLight( lightDef, tri->bounds, entityDef->modelRenderMatrix ) ) {
			continue;
		}

		surfaceInteraction_t *sint = &surfaces[c];

		// generate a set of indexes for the lit surfaces, culling away triangles that are
		// not at least partially inside the light
		if ( shader->ReceivesLighting() ) {
			srfTriangles_t * lightTris = R_CreateInteractionLightTris( entityDef, tri, lightDef, shader );
			if ( lightTris != NULL ) {
				// make a static index cache
				sint->numLightTrisIndexes = lightTris->numIndexes;
				sint->lightTrisIndexCache = vertexCache.AllocStaticIndex( lightTris->indexes, ALIGN( lightTris->numIndexes * sizeof( lightTris->indexes[0] ), INDEX_CACHE_ALIGN ) );

				interactionGenerated = true;
				R_FreeStaticTriSurf( lightTris );
			}
		}

		// if the interaction has shadows and this surface casts a shadow
		if ( HasShadows() && shader->SurfaceCastsShadow() && tri->silEdges != NULL ) {

			// if the light has an optimized shadow volume, don't create shadows for any models that are part of the base areas
			if ( lightDef->parms.prelightModel == NULL || !model->IsStaticWorldModel() || r_skipPrelightShadows.GetBool() ) {
				srfTriangles_t * shadowTris = R_CreateInteractionShadowVolume( entityDef, tri, lightDef );
				if ( shadowTris != NULL ) {
					// make a static index cache
					sint->shadowIndexCache = vertexCache.AllocStaticIndex( shadowTris->indexes, ALIGN( shadowTris->numIndexes * sizeof( shadowTris->indexes[0] ), INDEX_CACHE_ALIGN ) );
					sint->numShadowIndexes = shadowTris->numIndexes;
#if defined( KEEP_INTERACTION_CPU_DATA )
					sint->shadowIndexes = shadowTris->indexes;
					shadowTris->indexes = NULL;
#endif
					if ( shader->Coverage() != MC_OPAQUE ) {
						// if any surface is a shadow-casting perforated or translucent surface, or the
						// base surface is suppressed in the view (world weapon shadows) we can't use
						// the external shadow optimizations because we can see through some of the faces
						sint->numShadowIndexesNoCaps = shadowTris->numIndexes;
					} else {
						sint->numShadowIndexesNoCaps = shadowTris->numShadowIndexesNoCaps;
					}
					R_FreeStaticTriSurf( shadowTris );
				}
				interactionGenerated = true;
			}
		}
	}

	// if none of the surfaces generated anything, don't even bother checking?
	if ( !interactionGenerated ) {
		MakeEmpty();
	}
}
nsresult
nsContentIterator::Init(nsIRange* aRange)
{
  NS_ENSURE_ARG_POINTER(aRange);

  mIsDone = PR_FALSE;

  // get common content parent
  mCommonParent = aRange->GetCommonAncestor();
  NS_ENSURE_TRUE(mCommonParent, NS_ERROR_FAILURE);

  // get the start node and offset
  PRInt32 startIndx = aRange->StartOffset();
  nsINode* startNode = aRange->GetStartParent();
  NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);

  // get the end node and offset
  PRInt32 endIndx = aRange->EndOffset();
  nsINode* endNode = aRange->GetEndParent();
  NS_ENSURE_TRUE(endNode, NS_ERROR_FAILURE);

  PRBool startIsData = startNode->IsNodeOfType(nsINode::eDATA_NODE);

  // short circuit when start node == end node
  if (startNode == endNode)
  {
    // Check to see if we have a collapsed range, if so,
    // there is nothing to iterate over.
    //
    // XXX: CharacterDataNodes (text nodes) are currently an exception,
    //      since we always want to be able to iterate text nodes at
    //      the end points of a range.

    if (!startIsData && startIndx == endIndx)
    {
      MakeEmpty();
      return NS_OK;
    }

    if (startIsData)
    {
      // It's a textnode.
      NS_ASSERTION(startNode->IsNodeOfType(nsINode::eCONTENT),
                   "Data node that's not content?");

      mFirst   = static_cast<nsIContent*>(startNode);
      mLast    = mFirst;
      mCurNode = mFirst;

      RebuildIndexStack();
      return NS_OK;
    }
  }
  
  // Find first node in range.

  nsIContent *cChild = nsnull;

  if (!startIsData && NodeHasChildren(startNode))
    cChild = startNode->GetChildAt(startIndx);

  if (!cChild) // no children, must be a text node
  {
    // XXXbz no children might also just mean no children.  So I'm not
    // sure what that comment above is talking about.
    if (mPre)
    {
      // XXX: In the future, if start offset is after the last
      //      character in the cdata node, should we set mFirst to
      //      the next sibling?

      if (!startIsData)
      {
        mFirst = GetNextSibling(startNode, nsnull);

        // Does mFirst node really intersect the range?
        // The range could be 'degenerate', ie not collapsed 
        // but still contain no content.
  
        if (mFirst &&
            !NodeIsInTraversalRange(mFirst, mPre, startNode, startIndx,
                                    endNode, endIndx)) {
          mFirst = nsnull;
        }
      }
      else {
        NS_ASSERTION(startNode->IsNodeOfType(nsINode::eCONTENT),
                   "Data node that's not content?");

        mFirst = static_cast<nsIContent*>(startNode);
      }
    }
    else {
      // post-order
      if (startNode->IsNodeOfType(nsINode::eCONTENT)) {
        mFirst = static_cast<nsIContent*>(startNode);
      } else {
        // What else can we do?
        mFirst = nsnull;
      }
    }
  }
  else
  {
    if (mPre)
      mFirst = cChild;
    else // post-order
    {
      mFirst = GetDeepFirstChild(cChild, nsnull);

      // Does mFirst node really intersect the range?
      // The range could be 'degenerate', ie not collapsed 
      // but still contain no content.
  
      if (mFirst &&
          !NodeIsInTraversalRange(mFirst, mPre, startNode, startIndx,
                                  endNode, endIndx))
        mFirst = nsnull;
    }
  }


  // Find last node in range.

  PRBool endIsData = endNode->IsNodeOfType(nsINode::eDATA_NODE);

  if (endIsData || !NodeHasChildren(endNode) || endIndx == 0)
  {
    if (mPre) {
      if (endNode->IsNodeOfType(nsINode::eCONTENT)) {
        mLast = static_cast<nsIContent*>(endNode);
      } else {
        // Not much else to do here...
        mLast = nsnull;
      }
    }
    else // post-order
    {
      // XXX: In the future, if end offset is before the first
      //      character in the cdata node, should we set mLast to
      //      the prev sibling?

      if (!endIsData)
      {
        mLast = GetPrevSibling(endNode, nsnull);

        if (!NodeIsInTraversalRange(mLast, mPre, startNode, startIndx,
                                    endNode, endIndx))
          mLast = nsnull;
      }
      else {
        NS_ASSERTION(endNode->IsNodeOfType(nsINode::eCONTENT),
                     "Data node that's not content?");

        mLast = static_cast<nsIContent*>(endNode);
      }
    }
  }
  else
  {
    PRInt32 indx = endIndx;

    cChild = endNode->GetChildAt(--indx);

    if (!cChild)  // No child at offset!
    {
      NS_NOTREACHED("nsContentIterator::nsContentIterator");
      return NS_ERROR_FAILURE; 
    }

    if (mPre)
    {
      mLast  = GetDeepLastChild(cChild, nsnull);

      if (!NodeIsInTraversalRange(mLast, mPre, startNode, startIndx,
                                  endNode, endIndx)) {
        mLast = nsnull;
      }
    }
    else { // post-order 
      mLast = cChild;
    }
  }

  // If either first or last is null, they both
  // have to be null!

  if (!mFirst || !mLast)
  {
    mFirst = nsnull;
    mLast  = nsnull;
  }
  
  mCurNode = mFirst;
  mIsDone  = !mCurNode;

  if (!mCurNode)
    mIndexes.Clear();
  else
    RebuildIndexStack();

  return NS_OK;
}
Beispiel #23
0
	~GlNodePrivate()		{ MakeEmpty(); }
GlAlgoNbrInList::~GlAlgoNbrInList()
{
	MakeEmpty();
}
Beispiel #25
0
main() {

  int e = 0;
unsigned char my_mac[5] = {0xE7,0xD3,0xF0,0x35,0xAA};
  QueueRecord *Q;
  QueueRecord sa;
  Q = &sa;
 int *p;
  DTNMsg* mp;
  DTNMsg m; 
  int i;

  MakeEmpty(Q);
  printf("Enqueue 20 elements...\n");
  for (i=0; i<20; i++) {
   m.prob = rand()%100;
   Enqueue(m, Q);
 }

PrintQueue(Q);
mp = Front(Q);
mp->prob = 10;
SortQueue(Q);

PrintQueue(Q);




/* 
printf("\n Dequeing.......\n");
for (i=0; i<7; i++)
printf(" %d ",(FrontAndDequeue(Q)).prob);

printf("\n Enqueing.......\n");
for (i=0; i<5; i++) {
m.prob = rand()%100;
printf(" %d ",m.prob);
Enqueue(m, Q);
}


PrintQueue(Q); 
SortQueue(Q);
for (i=0; i<5; i++)
printf(" %d ",(FrontAndDequeue(Q)).prob);
*/

printf("\n\n");

unsigned char* mac;
mac = my_mac;
for(i=0;i<5;i++)
printf("%x",mac[i]);

unsigned int x;
x= 0x0000000F;
x=(x<<4)|0xF;
unsigned int xx = 0x00000000;
for(i = 0 ;i<=5;i++){
x = ((0x00000000 | 0x89B0)<<16) | xx++;

printf("\n\nx = %x\n",x);}













}
Beispiel #26
0
          // Class destructor.
QueType::~QueType()
{
  MakeEmpty();
}
Beispiel #27
0
int main() {

	/* Question 1. */
	puts(KBLU "\n1. Read in numbers in data 100 one by one and insert them into an initially empty heap. Print out the elements in the array (you should check the output to see if the heap order is satisfied)." RESET);

	// open file
	FILE * fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	PriorityQueue H = Initialize( 100 );
	// insert data
	int i, cur;
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintHeap( H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );


	/* Question 2. */
	puts(KBLU "\n2. Write a function to print out elements that are smaller than 15000 (not necessary in sorted order). The function should run in O(K), where K is the number of the elements you print out. " RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintSmaller( 15000, H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 3. */
	puts(KBLU "\n3. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 4. */
	puts(KBLU "\n4. Find the 30th smallest element by repeatly using DeleteMin. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );

	// first 30 smallest number
	int tmp;

	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 5. */
	puts(KBLU "\n5. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Insert( cur, H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* EXPERIMENT */
	puts(KBLU "\n6. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a 4-heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	/* Question 7. */
	puts(KBLU "\n7. Find the 30th smallest element by repeatly using DeleteMin. (4-heap)\n" RESET);

	// first 30 smallest number
	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 8. */
	puts(KBLU "\n8. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. (4-heap)\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Append( cur, H );
			BuildHeap( H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));
	puts("");

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	return 0;
}
Beispiel #28
0
/*
====================
idInteraction::CreateInteraction

Called when a entityDef and a lightDef are both present in a
portalArea, and might be visible.  Performs cull checking before doing the expensive
computations.

References tr.viewCount so lighting surfaces will only be created if the ambient surface is visible,
otherwise it will be marked as deferred.

The results of this are cached and valid until the light or entity change.
====================
*/
void idInteraction::CreateInteraction( const idRenderModel *model ) {
    const idMaterial *	lightShader = lightDef->lightShader;
    const idMaterial*	shader;
    bool				interactionGenerated;
    idBounds			bounds;

    tr.pc.c_createInteractions++;

    bounds = model->Bounds( &entityDef->parms );

    // if it doesn't contact the light frustum, none of the surfaces will
    if ( R_CullLocalBox( bounds, entityDef->modelMatrix, 6, lightDef->frustum ) ) {
        MakeEmpty();
        return;
    }

    // use the turbo shadow path
    shadowGen_t shadowGen = SG_DYNAMIC;

    // really large models, like outside terrain meshes, should use
    // the more exactly culled static shadow path instead of the turbo shadow path.
    // FIXME: this is a HACK, we should probably have a material flag.
    if ( bounds[1][0] - bounds[0][0] > 3000 ) {
        shadowGen = SG_STATIC;
    }

    //
    // create slots for each of the model's surfaces
    //
    numSurfaces = model->NumSurfaces();
    surfaces = (surfaceInteraction_t *)R_ClearedStaticAlloc( sizeof( *surfaces ) * numSurfaces );

    interactionGenerated = false;

    // check each surface in the model
    for ( int c = 0 ; c < model->NumSurfaces() ; c++ ) {
        const modelSurface_t	*surf;
        srfTriangles_t	*tri;

        surf = model->Surface( c );

        tri = surf->geometry;
        if ( !tri ) {
            continue;
        }

        // determine the shader for this surface, possibly by skinning
        shader = surf->shader;
        shader = R_RemapShaderBySkin( shader, entityDef->parms.customSkin, entityDef->parms.customShader );

        if ( !shader ) {
            continue;
        }

        // try to cull each surface
        if ( R_CullLocalBox( tri->bounds, entityDef->modelMatrix, 6, lightDef->frustum ) ) {
            continue;
        }

        surfaceInteraction_t *sint = &surfaces[c];

        sint->shader = shader;

        // save the ambient tri pointer so we can reject lightTri interactions
        // when the ambient surface isn't in view, and we can get shared vertex
        // and shadow data from the source surface
        sint->ambientTris = tri;

        // "invisible ink" lights and shaders
        if ( shader->Spectrum() != lightShader->Spectrum() ) {
            continue;
        }

        // generate a lighted surface and add it
        if ( shader->ReceivesLighting() ) {
            if ( tri->ambientViewCount == tr.viewCount ) {
                sint->lightTris = R_CreateLightTris( entityDef, tri, lightDef, shader, sint->cullInfo );
            } else {
                // this will be calculated when sint->ambientTris is actually in view
                sint->lightTris = LIGHT_TRIS_DEFERRED;
            }
            interactionGenerated = true;
        }

        // if the interaction has shadows and this surface casts a shadow
        if ( HasShadows() && shader->SurfaceCastsShadow() && tri->silEdges != NULL ) {

            // if the light has an optimized shadow volume, don't create shadows for any models that are part of the base areas
            if ( lightDef->parms.prelightModel == NULL || !model->IsStaticWorldModel() || !r_useOptimizedShadows.GetBool() ) {

                // this is the only place during gameplay (outside the utilities) that R_CreateShadowVolume() is called
                sint->shadowTris = R_CreateShadowVolume( entityDef, tri, lightDef, shadowGen, sint->cullInfo );
                if ( sint->shadowTris ) {
                    if ( shader->Coverage() != MC_OPAQUE || ( !r_skipSuppress.GetBool() && entityDef->parms.suppressSurfaceInViewID ) ) {
                        // if any surface is a shadow-casting perforated or translucent surface, or the
                        // base surface is suppressed in the view (world weapon shadows) we can't use
                        // the external shadow optimizations because we can see through some of the faces
                        sint->shadowTris->numShadowIndexesNoCaps = sint->shadowTris->numIndexes;
                        sint->shadowTris->numShadowIndexesNoFrontCaps = sint->shadowTris->numIndexes;
                    }
                }
                interactionGenerated = true;
            }
        }

        // free the cull information when it's no longer needed
        if ( sint->lightTris != LIGHT_TRIS_DEFERRED ) {
            R_FreeInteractionCullInfo( sint->cullInfo );
        }
    }

    // if none of the surfaces generated anything, don't even bother checking?
    if ( !interactionGenerated ) {
        MakeEmpty();
    }
}
Beispiel #29
0
/******main starts ***********/
int main(int argc, char *argv[]) {
  
  int       sockfd,new_fd;             /*variables for socket*/
  int     portnum;            /*variable for port numb if provided*/
  struct sockaddr_in     server_addr;    /*structure to hold server's address */
  struct sockaddr_in     client_addr;    /*structure to hold client's address */
  int     cli_size,z;            /*length of address */
  pthread_t     thr;            /*variable to hold thread ID */
  int     yes=1;
  addr a;                    /*variable of type struct addr*/
  
  printf("\n\t*-*-*-*SERVER STARTED*-*-*-*\n");
  /*=optional or default port argument=*/
  if( argc == 2 )   
    portnum = atoi(argv[1]);
  else
    portnum = PORT;  //if port number not given as argument then using default port
  printf("PORT NO.:\t%d\n",portnum);

  h = MakeEmpty( NULL );        //frees the list
           

  /*=set info of server =*/
  server_addr.sin_family=AF_INET;        /* set family to Internet     */
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* set IP address */
  server_addr.sin_port=htons(portnum);
  printf("IP ADDRESS:\t%s\n",inet_ntoa(server_addr.sin_addr));

  /*=creating socket=*/
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if(sockfd == -1){
    printf("server- socket() error");    // debugging
    exit(1);
  }else
    printf("socket\t\tcreated.\n");

  if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) {
    printf("setsockopt error");    // debugging
    exit(1);
  }else printf("reusing\t\tport\n");

  /*=binding socket=*/
  if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))==-1){
    printf("binding failed\n");    // debugging
    exit(1);}
  else
    printf("binding\t\tsuccess.\n\n");
  printf("\t\tPRESS CTRL+z TO VIEW ONLINE CLIENTS\n\n");
  /*=socket on listening mode=*/
  listen(sockfd, BACKLOG);
  printf("waiting for clients......\n");

  if (signal(SIGINT,(void *)Quitproc)==0)    //signal handler
    if(signal(SIGTSTP, zzz)==0)            //signal handler

      while(1){
	cli_size=sizeof(struct sockaddr_in); //cli_size necessary as an argument for pthread_create
	new_fd = accept(sockfd, (struct sockaddr *)&client_addr,&cli_size); //accepting connection from client
	a =h ;
       
        /*=sign in with name=*/
        bzero(username,10);       
        if(recv(new_fd,username,sizeof(username),0)>0);
	username[strlen(username)-1]=':';
	printf("\t%d->%s JOINED chatroom\n",new_fd,username);
	sprintf(buffer,"%s IS ONLINE\n",username);
	Insert( new_fd,username, h, a );            //inserting newly accepted client socked fd in list
	a = a->next;

        /*=notify all clients about newly joining clients=*/
	a = h ;
        do{
	  a = a->next;
	  sf2 = a->port;
	  if(sf2!=new_fd)
	    send(sf2,buffer ,sizeof(buffer),0);
        } while( a->next != NULL );

	printf("server got connection from %s & %d\n\n",inet_ntoa(client_addr.sin_addr),new_fd); // debugging

	struct Node args;                     //struct to pass multiple arguments to server function
	args.port=new_fd;
	strcpy(args.username,username);
           
	pthread_create(&thr,NULL,server,(void*)&args);     //creating thread for every client connected
	pthread_detach(thr);
      } /*while end*/

  DeleteList(h);                     //deleting all clients when server closes
  close(sockfd);

}/********main ends***********/
Beispiel #30
0
void PointerListTest::BinarySearchIndexTest()
{
	_PointerList_ list;
	Initialize(list, 10);
	list.SortItems(Item::Compare);
	assert(IsSorted(list));
	
	Item notInListLow(NOT_USED_ID);
	Item notInListHigh(NOT_USED_ID_HIGH);
	gData = (void*)0x4711;
	
	for (int32 i = 0; i < 10; i ++) {
		Item* item = (Item*)list.ItemAt(i);
		assert(item != NULL);
		Value value(item->Value());

		int index = IndexOf(list, item->Value());
		int searchIndex;
		searchIndex = list.BinarySearchIndex(item, Item::Compare);
		assert(index == searchIndex);

		searchIndex = list.BinarySearchIndex(item, ::Compare, gData);
		assert(index == searchIndex);
		
		searchIndex = list.BinarySearchIndexByPredicate(&value, ValuePredicate);
		assert(index == searchIndex);

		// notInListLow
		searchIndex = list.BinarySearchIndex(&notInListLow, Item::Compare);
		assert(searchIndex == -1);

		searchIndex = list.BinarySearchIndex(&notInListLow, ::Compare, gData);
		assert(searchIndex == -1);
		
		value.value = notInListLow.Value();
		searchIndex = list.BinarySearchIndexByPredicate(&value, ValuePredicate);
		assert(searchIndex == -1);

		// notInListHigh
		searchIndex = list.BinarySearchIndex(&notInListHigh, Item::Compare);
		assert(searchIndex == -(list.CountItems()+1));

		searchIndex = list.BinarySearchIndex(&notInListHigh, ::Compare, gData);
		assert(searchIndex == -(list.CountItems()+1));
		
		value.value = notInListHigh.Value();
		searchIndex = list.BinarySearchIndexByPredicate(&value, ValuePredicate);
		assert(searchIndex == -(list.CountItems()+1));
	}

	MakeEmpty(list);
	
	for (int i = 0; i < 3; i ++) {
		list.AddItem(new Item(2 * i));
	}
	Item notInList(3);
	assert(IndexOf(list, 3) == -1);
	
	int index = list.BinarySearchIndex(&notInList, Item::Compare);
	assert (index == -3);
	
	index = list.BinarySearchIndex(&notInList, ::Compare, gData);
	assert (index == -3);
	
	Value value(notInList.Value());
	index = list.BinarySearchIndexByPredicate(&value, ValuePredicate);
	assert (index == -3);
		
	MakeEmpty(list);
}