Esempio n. 1
0
/**
 * Pops and returns the top element of the stack.
 */
void* pop(struct stack_pointer* stack) {
    if (is_empty(stack)) {
        fatal_error("Cannot pop an empty stack\n");
    }
    return stack->stack[(stack->stack_pointer_m)--];
}
Esempio n. 2
0
File: main.c Progetto: spamela/dlist
int main(int argc, char** argv) {
    IntList* list1 = mk_list();
    print_list(list1);
    printf("is_empty(list1) = 1? %d\n", is_empty(list1)); 
    printf("length(list1) = 0? %d\n", length(list1));
    free_list(list1);
    IntList* list2 = mk_list();
    push_back(list2, 4);
    push_back(list2, 5);
    printf("is_empty(list2) = 0? %d\n", is_empty(list2));
    printf("length(list2) = 2? %d\n", length(list2));
    print_list(list2);
    printf("sum(list2) = 9? %d\n", sum(list2));
    int ret1, ret2, ret3;
    printf("index_of(list2, 4, ret1) = true? %d\n", index_of(list2, 4, &ret1));
    printf("index_of(list2, 5, ret2) = true? %d\n", index_of(list2, 5, &ret2));
    printf("index_of(list2, 6, ret3) = false? %d\n", index_of(list2, 6, &ret3));
    printf("index_of(list2, 4, ret1), ret1 = 0? %d\n", ret1);
    printf("index_of(list2, 5, ret2), ret2 = 1? %d\n", ret2);

    push_front(list2, 6);
    print_list(list2);

    printf("index_of(list2, 4, ret1) = true? %d\n", index_of(list2, 4, &ret1));
    printf("index_of(list2, 5, ret2) = true? %d\n", index_of(list2, 5, &ret2));
    printf("index_of(list2, 6, ret3) = true? %d\n", index_of(list2, 6, &ret3));
    printf("index_of(list2, 4, ret1), ret1 = 1? %d\n", ret1);
    printf("index_of(list2, 5, ret2), ret2 = 2? %d\n", ret2);
    printf("index_of(list2, 6, ret3), ret2 = 0? %d\n", ret3);

    insert(list2, 8, 0);
    print_list(list2);
    insert(list2, 9, 2);
    print_list(list2);
    insert(list2, 7, 4);
    print_list(list2);

    intersperse(list2, 3);
    print_list(list2);

    IntList* list3 = mk_list();
    push_back(list3, 4);
    push_back(list3, 5);
    intersperse(list3, 2);
    print_list(list3);

    int pop;
    pop_front(list3, &pop);
    print_list(list3);
    printf("pop = %d\n", pop);

    pop_front(list3, &pop);
    print_list(list3);
    printf("pop = %d\n", pop);

    pop_front(list3, &pop);
    print_list(list3);
    printf("pop = %d\n", pop);

    printf("list3 = ");
    print_list(list3);

    printf("\nfree_list(list2)...\n");
    free_list(list2);
    printf("free_list(list3)...\n");
    free_list(list3);
 
    return 0;
}
Esempio n. 3
0
/**
 * Parse Identifier (ECMA-262 v5, 7.6) or ReservedWord (7.6.1; 7.8.1; 7.8.2).
 *
 * @return TOK_NAME - for Identifier,
 *         TOK_KEYWORD - for Keyword or FutureReservedWord,
 *         TOK_NULL - for NullLiteral,
 *         TOK_BOOL - for BooleanLiteral
 */
static token
lexer_parse_identifier_or_keyword (void)
{
  ecma_char_t c = LA (0);

  JERRY_ASSERT (lexer_is_char_can_be_identifier_start (c));

  new_token ();

  bool is_correct_identifier_name = true;
  bool is_escape_sequence_occured = false;
  bool is_all_chars_were_lowercase_ascii = true;

  while (true)
  {
    c = LA (0);

    if (c == LIT_CHAR_BACKSLASH)
    {
      consume_char ();

      is_escape_sequence_occured = true;

      bool is_unicode_escape_sequence = (LA (0) == LIT_CHAR_LOWERCASE_U);
      consume_char ();

      if (is_unicode_escape_sequence)
      {
        /* UnicodeEscapeSequence */

        if (!lexer_convert_escape_sequence_digits_to_char (&src_iter,
                                                           true,
                                                           &c))
        {
          is_correct_identifier_name = false;
          break;
        }
        else
        {
          /* c now contains character, encoded in the UnicodeEscapeSequence */

          // Check character, converted from UnicodeEscapeSequence
          if (!lexer_is_char_can_be_identifier_part (c))
          {
            is_correct_identifier_name = false;
            break;
          }
        }
      }
      else
      {
        is_correct_identifier_name = false;
        break;
      }
    }
    else if (!lexer_is_char_can_be_identifier_part (c))
    {
      break;
    }
    else
    {
      if (!(c >= LIT_CHAR_ASCII_LOWERCASE_LETTERS_BEGIN
            && c <= LIT_CHAR_ASCII_LOWERCASE_LETTERS_END))
      {
        is_all_chars_were_lowercase_ascii = false;
      }

      consume_char ();
    }
  }

  if (!is_correct_identifier_name)
  {
    PARSE_ERROR (JSP_EARLY_ERROR_SYNTAX, "Illegal identifier name", lit_utf8_iterator_get_pos (&src_iter));
  }

  const lit_utf8_size_t charset_size = TOK_SIZE ();

  token ret = empty_token;

  if (!is_escape_sequence_occured
      && is_all_chars_were_lowercase_ascii)
  {
    /* Keyword or FutureReservedWord (TOK_KEYWORD), or boolean literal (TOK_BOOL), or null literal (TOK_NULL) */
    ret = lexer_parse_reserved_word (TOK_START (), charset_size);
  }

  if (is_empty (ret))
  {
    /* Identifier (TOK_NAME) */

    if (!is_escape_sequence_occured)
    {
      ret = lexer_create_token_for_charset (TOK_NAME,
                                            TOK_START (),
                                            charset_size);
    }
    else
    {
      ret = lexer_create_token_for_charset_transform_escape_sequences (TOK_NAME,
                                                                       TOK_START (),
                                                                       charset_size);
    }
  }

  is_token_parse_in_progress = false;

  return ret;
} /* lexer_parse_identifier_or_keyword */
Esempio n. 4
0
// 피크 함수
element peak(LinkedStackType *s){
    if(is_empty(s)){
        fprintf(stderr, "스택 공백 에러\n");
        exit(1);
    }else return s->top->item;
}
Esempio n. 5
0
Item peek(Stack s)
{
  if (is_empty(s))
    terminate("Error in peek: stack is empty.");
  return s->contents[s->top - 1];
}
Esempio n. 6
0
/*******************************************************************************
  Return the minimum number of items that can appear in an instance of the
  type. Returned value may be 0 or 1.
********************************************************************************/
int XQType::min_card() const
{
  return (is_empty() ? 0 : RootTypeManager::QUANT_MIN_CNT[get_quantifier()]);
}
Esempio n. 7
0
void infix_to_postfix(char exp[])
{
	Stack s;

	int i, n, strlength;

	char* newstr;
	
	strlength = strlen(exp);

	newstr = (char*) malloc(strlength);

	stack_init(&s);

	n = 0;

	for (i = 0; i < strlength; ++i)
	{
		char temp = exp[i];

		if (temp == '(')
			stack_push(&s, temp);
		else if (temp == ')')
		{
			char topOp = (char) stack_pop(&s);

			while (topOp != '(')
			{
				newstr[n++] = topOp;
				topOp = (char) stack_pop(&s);
			}
		}
		else if (is_operend(temp))
		{
			char topOp = (char)stack_peek(&s);

			while (!is_empty(&s) && get_operend_priority(topOp) >= get_operend_priority(temp))
			{
				newstr[n++] = (char) stack_pop(&s);
				topOp = (char)stack_peek(&s);
			}

			stack_push(&s, temp);
		}
		else
		{
			newstr[n++] = exp[i];
		}
		//next
	}


	while (!is_empty(&s))
	{
		newstr[n++] = (char) stack_pop(&s);
	}

	memset(exp, 0, strlength);

	for (i = 0; i < n; ++i)
	{
		exp[i] = newstr[i];
	}

	stack_destroy(&s);
	free(newstr);
}
Esempio n. 8
0
bool Stack::pop(char& elem){
	if (is_empty()) return false;    //you can't bleed a stone
	elem = dat_ptr[--the_top];      //move back to pop the highest value off the stack  
}
Esempio n. 9
0
bool Stack::top(char& elem){
	if (is_empty()) return false;    //nothing in here
	elem = dat_ptr[elem - 1];        //what's on top?
	return true;                    //a successful look at the top value
}
Esempio n. 10
0
 double  mixing_tank::get_mix( ) const
 {
   assert (!is_empty());
   return ((quantity_a / get_volume ()));
 }
Esempio n. 11
0
void test_board_is_empty() {
  Board* board = new_board(3);
  assert(is_empty(board));
  destroy_board(board);
}
Esempio n. 12
0
File: main.c Progetto: PyHDI/PyCoRAM
//------------------------------------------------------------------------------
int is_frontier_empty()
{
  return is_empty(&pqueue);
}
Esempio n. 13
0
/**@return true if node is literal
*******************************************************************************/
inline bool is_literal(const Node_id nid, Triple_store const& ts) {
   Node const& node = ts[nid];
   return is_empty(node.ns_id());
}
Esempio n. 14
0
/* Return whether the queue is empty */
bool queueEmpty(Queue *queue) {
  return is_empty(queue->stk_ptr);
}
Esempio n. 15
0
void *peek_end(RB)
{if (!RB || is_empty(RB)) return NULL;
  return data[prev(RB,e)];
}
Esempio n. 16
0
	queue = NULL;
	front  = 1;
	rear  = 0;
}
//	insert,插入队列,从队尾插入
void insert( QUEUE_TYPE value )
{
	assert( !is_full( ) );
	rear		   = ( rear + 1 ) % ARRAY_SIZE;
	queue[rear]	   = value;
}

//	delete 从队头删除
void delete( void )
{
	assert( !is_empty( ) );
	front = ( front + 1 ) % ARRAY_SIZE;
}

//	first,队头元素
QUEUE_TYPE first( void )
{
	assert( !is_empty( ) );
	return queue[front];
}

//	is_empty
int is_empty( void )
{
	return ( rear + 1 ) % ARRAY_SIZE == front;
}
Esempio n. 17
0
void *get_end(RB)
{ CHKRB; if (is_empty(RB)) return -1;
  e=prev(RB,e);
  return data[e];
}
Esempio n. 18
0
/**
 * @brief Creates the text surface.
 *
 * This function is called when there is a change.
 */
void TextSurface::rebuild() {

  if (surface != NULL) {
    // another text was previously set: delete it
    SDL_FreeSurface(surface->get_internal_surface());
    delete surface;
    surface = NULL;
  }

  if (is_empty()) {
    // empty string: no surface to create
    return;
  }

  // create the text surface

  SDL_Surface *internal_surface = NULL;
  switch (rendering_mode) {

  case TEXT_SOLID:
    internal_surface = TTF_RenderUTF8_Solid(fonts[font_id].internal_font, text.c_str(), *text_color.get_internal_color());
    break;

  case TEXT_SHADED:
    internal_surface = TTF_RenderUTF8_Shaded(fonts[font_id].internal_font, text.c_str(), *text_color.get_internal_color(),
	*background_color.get_internal_color());
    break;

  case TEXT_BLENDED:
    internal_surface = TTF_RenderUTF8_Blended(fonts[font_id].internal_font, text.c_str(), *text_color.get_internal_color());
    break;
  }

  Debug::check_assertion(internal_surface != NULL, StringConcat()
      << "Cannot create the text surface for string '" << text << "': " << SDL_GetError());
  surface = new Surface(internal_surface);

  // calculate the coordinates of the top-left corner
  int x_left = 0, y_top = 0;

  switch (horizontal_alignment) {

  case ALIGN_LEFT:
    x_left = x;
    break;

  case ALIGN_CENTER:
    x_left = x - surface->get_width() / 2;
    break;

  case ALIGN_RIGHT:
    x_left = x - surface->get_width();
    break;
  }

  switch (vertical_alignment) {

  case ALIGN_TOP:
    y_top = y;
    break;

  case ALIGN_MIDDLE:
    y_top = y - surface->get_height() / 2;
    break;

  case ALIGN_BOTTOM:
    y_top = y - surface->get_height();
    break;
  }

  text_position.set_xy(x_left, y_top);
}
Esempio n. 19
0
void convertPostfix(char infix[], char postfix[])
{


     /*  parenCount checks for paren errors */
     int inCount, postCount, check, check2, parenCount;
     int tmpCount, errorLevel = 0;
     char *tmpString, mesg[256];
     char oper;
     STACK st;
     char *prog_name = "postfix module";


     inCount = 0;
     postCount = 0;
     check2 = 0;
     parenCount = 0;
     check = 20;
     postfix[0] = '\0';


     init_stack(&st);

     for(inCount = 0; infix[inCount] != '\0'; inCount++)
     {
              /* if it's a number or a char, just pass it on */
              /* need to check for '.' also!!! */
              if(isalnum(infix[inCount]) || infix[inCount] == '.' || infix[inCount] == '_')
              {
	           postfix[postCount++] = infix[inCount];
                   postfix[postCount] = '\0';
                   #ifdef DEBUG_POST
                   printf("postfix=%s\n", postfix);
                   #endif
              }   
              else if(infix[inCount] == '(')
              {

                   parenCount++;
                   push('(', &st);
                   /*postfix[postCount++] = ' ';*/
                   /*postfix[postCount] = '\0';*/
                   #ifdef DEBUG_POST
                   printf("postfix=%s\n", postfix);
                   #endif

              }
              else if(infix[inCount] == ')')
              {

                  parenCount--;

                  while((oper = pop(&st)) != '('  && is_empty(st) != 1)
                  {
                      if(oper != '(')
                      {
                           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
                           #ifdef DEBUG_POST
                           printf(") detected postfix=%s\n", postfix);
                           #endif


                           postfix[postCount++] = oper;
		           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
                           #ifdef DEBUG_POST
                           printf(") detected postfix=%s\n", postfix);
                           #endif
		      }
                      else
                      {
                           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
                           #ifdef DEBUG_POST
                           printf(") detected postfix=%s\n", postfix);
                           #endif
		      }
                  }
              }
              else if(infix[inCount] == '-')
              {
                   check2 = 4;
                   if(check2 >= check && is_empty(st) != 1)
                   {
                       postfix[postCount++] = ' ';
                       postfix[postCount] = '\0';
                       #ifdef DEBUG_POST
                       printf("postfix=%s\n", postfix);
                       #endif
                       oper =  pop(&st);
                       if(oper != '(')
                       { 
                           postfix[postCount++] = oper;

		           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
                           #ifdef DEBUG_POST
                           printf("postfix=%s\n", postfix);
                           #endif
                       }
                   }
                   else
                   {
                        postfix[postCount++] = ' ';
                        postfix[postCount] = '\0';
                        #ifdef DEBUG_POST
                        printf("postfix=%s\n", postfix);
                        #endif
                   }
                  push('-', &st);
                   check = check2;
                }
                else if(infix[inCount] == '+')
                {
                     check2 = 3;

                     if(check2 >= check && is_empty(st) != 1)
                     {
                           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
                           #ifdef DEBUG_POST
                           printf("Before+pop\n");   
                           #endif
                           oper = pop(&st);
                           #ifdef DEBUG_POST
                           printf("oper=%c\n",oper);
                           #endif
			   if(oper != '(')
                           {
                                postfix[postCount++] = oper;
		                postfix[postCount++] = ' ';
                                postfix[postCount] = '\0';
                           }


		     }
		     else
		     {
		           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
		     }
	             push('+', &st);
                     #ifdef DEBUG_POST
                     printf("postfix=%s\n", postfix);
                     #endif
	             check = check2;
               }
               else if(infix[inCount] == '*')
               {
	             check2 = 1;

                     if(check2 >= check && is_empty(st) != 1)
		     {
                          postfix[postCount++] = ' ';
                          postfix[postCount] = '\0';

		          oper = pop(&st);
		          if(oper != '(')
                          {
                              postfix[postCount++] = oper;
                              postfix[postCount++] = ' ';
                              postfix[postCount] = '\0';
                          }

		     }
                     else
                     {
                          postfix[postCount++] = ' ';
                          postfix[postCount] = '\0';
		     }
		     push('*', &st);
                     #ifdef DEBUG_POST
                     printf("postfix=%s\n", postfix);
                     #endif
                     check = check2;
               }
               else if(infix[inCount] == '/')
               {
                    check2 = 2;
                    if(check2 >= check && is_empty(st) != 1)
		    {
                           postfix[postCount++] = ' ';
                           postfix[postCount] = '\0';
			   oper = pop(&st);
		           if(oper != '(')
                           {
                                postfix[postCount++] = oper;
		                postfix[postCount++] = ' ';
                                postfix[postCount] = '\0';
                           }
                    }
                    else
                    {
                            postfix[postCount++] = ' ';
                            postfix[postCount] = '\0';
                            #ifdef DEBUG_POST
                            printf("postfix=%s\n", postfix);
                            #endif
                    }
		    push('/', &st);
                    #ifdef DEBUG_POST
                    printf("postfix=%s\n", postfix);
                    #endif
                    check =  check2;
               }
               else if(infix[inCount] == ' ')
               {
                    continue; /* ingore spaces in infix for now */ 
               }
               else
               {
                       /* error condition */
	            errorLevel = 1;
                    sprintf(mesg,"%s is not a valid character in the expression", infix[inCount]);
                    ERROR(prog_name, mesg, 1);
               }


        }     /*  end of for loop  */

        /* now pop the rest of the operators off of the stack */
        while(is_empty(st) != 1)
        {
             oper = pop(&st);

             if(oper != '(')
             {
                  postfix[postCount++] = ' ';
                  postfix[postCount] = '\0';
                  #ifdef DEBUG_POST
                  printf("popping operator %c\n", oper);
                  #endif

                  postfix[postCount++] = oper;
                  postfix[postCount] = '\0';
             }
             #ifdef DEBUG_POST
             printf("postfix=%s\n", postfix);
             #endif
        }

        /* adds the last operator to the postfix string */
        /*if(oper != '(')
        {
             postfix[postCount++] = ' ';
             postfix[postCount] = '\0';
             #ifdef DEBUG_POST
             printf("popping operator %c\n", oper);
             #endif

             postfix[postCount++] = oper;

             postfix[postCount] = '\0';
             #ifdef DEBUG_POST
             printf("postfix=%s\n", postfix);
             #endif
        }*/

        /* checks to see that there was an equal number of left and
           right parentheses */

        if(parenCount != 0)
        {
            errorLevel = 2;
            ERROR(prog_name, "Mismatched parentheses in mathematical equation", 1);
        }

        #ifdef DEBUG_POST
        printf("convertPostfix completed\n");
        #endif
}  /*  end of convertPostfix()  */
Esempio n. 20
0
int main( int argc, char ** argv )
{
  stk f, s, t;
  int i;

  if( argc == 2 )
    n = atoi(argv[1]);
  else
    n = 3;

  init_stack( &f );
  init_stack( &s );
  init_stack( &t );

  for( i = n; i > 0; --i )
    push( &f, i );

#ifdef __DEBUG__
  printf("\n");
  p( f, s, t ); 
#endif 

  i = 0;
  while( ( !is_empty( f ) || !is_empty( s ) ) )
    {
      i++; // counter to keep from inf loops
      int moved;
      if( ( moved = move( &f, &s ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d first to second\n", moved );
#endif
	}
      else if( ( moved = move( &f, &t ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d first to third\n", moved );
#endif
	}
      else if( ( moved = move( &s, &t ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d second to third\n", moved );
#endif
	}
      else if( ( moved = move( &t, &f ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d third to first\n", moved );
#endif
	}
      else if( ( moved = move( &t, &s ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d third to second\n", moved );
#endif
	}
      else if( ( moved = move( &s, &f ) ) > 0 )
	{
#ifdef __DEBUG__
	  printf("moved %d second to first\n", moved );
#endif
	}
      else
	{
#ifdef __DEBUG__
	printf("NOP\n");
#endif
	}

      last_moved = moved;
      p( f, s, t );
    }
  

  print_stacks( f, s, t );

  printf("\n\nTook %d moves\n", i );
  return 0;
}
Esempio n. 21
0
command_t make_command_tree(token_stream_t t)
{
  token_t sub_head = t->head;//the sub_head is t->head 
  token_t token_now = sub_head;
  stack_t operators = (stack_t)checked_malloc(sizeof(Stack));
  stack_t operands = (stack_t)checked_malloc(sizeof(Stack));//build two stacks to hold operands and operators
  command_t comm;//one command
  command_t prev = NULL;
  int line = token_now->line; 
  while(token_now!=NULL)
  {
    if( !(token_now->t_type == LEFT_DERCTION || token_now->t_type == RIGHT_DERCTION) )
      {
        // make new command
        comm = checked_malloc(sizeof( struct command ));
      }
    switch(token_now->t_type)
    
    {
      case AND:
      comm->type = AND_COMMAND;
      while (  !is_empty(operators) &&( top(operators)->type == PIPE_COMMAND || top(operators)->type == OR_COMMAND || top(operators)->type == AND_COMMAND ))
          {
            command_t pop_ops = pop(operators);//pop until the top ops has smaller presendence than
            if (!make_command_branch(pop_ops, operands))
              {
                error(2, 0, "Line %d: Syntax error. Not enough children to create new tree.", line);
                return NULL;
              }
          }
          push(operators,comm);//push ADD command to ops
          break;

        case OR:
      comm->type = OR_COMMAND;
      while (  !is_empty(operators) &&( top(operators)->type == PIPE_COMMAND || top(operators)->type == OR_COMMAND || top(operators)->type == AND_COMMAND ))
          {
            command_t pop_ops = pop(operators);//pop until the top ops has smaller presendence than
            if (!make_command_branch(pop_ops, operands))
              {
                error(2, 0, "Line %d: Syntax error. Not enough children to create new tree.", line);
                return NULL;
              }
          }
          push(operators,comm);//push ADD command to ops
          break;

        // push OR to ops
        push(operators,comm);
        break;

        case PIPELINE:
      comm->type = PIPE_COMMAND;
      while (  !is_empty(operators) && top(operators)->type == PIPE_COMMAND )
          {
            command_t pop_ops = pop(operators);//pop until the top ops has smaller presendence than
            if (!make_command_branch(pop_ops, operands))
              {
                error(2, 0, "Line %d: Syntax error. Not enough children to create new tree.", line);
                return NULL;
              }
          }
          push(operators,comm);//push PIPE command to ops
          break;

        case SEMICOLON:
          comm->type = SEQUENCE_COMMAND;

        // always pop since SEMICOLON <= all ops
          while (!is_empty(operators))
          {
            command_t pop_ops = pop(operators);
              if (!make_command_branch(pop_ops, operands))
              {
                error(2, 0, "Line %d: Syntax error. Not enough children to create new tree.", line);
                return NULL;
              }
          }

        // push SEMICOLON to ops
          push(operators,comm);
          break;

        case WORD:
          comm->type = SIMPLE_COMMAND;
          //seprated by word
          int num_words = 1;
          token_t count = token_now;
          while(count!=NULL&&count->next!=NULL&&count->next->t_type==WORD)//while next is still word
          {
            count = count ->next;
            num_words++;
          }
          comm->u.word[0] = token_now->text;
          int i =1;
          while(i< num_words)
          {
            token_now = token_now->next;
            comm->u.word[i] = token_now->text;
            i++;
            //if(i == num_words)
          }
          comm->u.word[num_words] = NULL;
          push(operators,comm);
          break;
        case SUBSHELL:
        comm->type = SUBSHELL_COMMAND;

        // process subshell command tree
        comm->u.subshell_command = 
        make_command_tree(
          convert_buffer_to_token_stream(token_now->text, strlen(token_now->text))
          );

        // push SUBSHELL tree to operands
        push(operands, comm);
        break;

      case LEFT_DERCTION:
        // check that previous command is a subshell or word
        if (prev== NULL || !(prev->type == SIMPLE_COMMAND || prev->type == SUBSHELL_COMMAND))
        {
          error(2, 0, "Line %d: Syntax error. ONLY words and SUBSHELL can follow redirection", line);
          return NULL;
        }
        else if (prev->output != NULL)
        {
          error(2, 0, "Line %d: Syntax error. Previous command already has output. ", line);
          return NULL;
        }
        else if (prev->input != NULL)
        {
          error(2, 0, "Line %d: Syntax error. Previous command already has input.", line);
          return NULL;
        }

        token_now= token_now->next;
        if (token_now->t_type == WORD) // followed by a word
        {
          //which is valid input
            prev->input = token_now->text;
        }
        else
        {
          error(2, 0, "Line %d: Syntax error. Redirects must be followed by words.", line);
          return NULL;
        }

        // no pushing required
        break;

        case RIGHT_DERCTION:
        // check that previous command is a subshell or word
        if (prev== NULL || !(prev->type == SIMPLE_COMMAND || prev->type == SUBSHELL_COMMAND))
        {
          error(2, 0, "Line %d: Syntax error. ONLY words and SUBSHELL can follow redirection", line);
          return NULL;
        }
        else if (prev->output != NULL)
        {
          error(2, 0, "Line %d: Syntax error. Previous command already has output. ", line);
          return NULL;
        }
        else if (prev->input != NULL)
        {
          error(2, 0, "Line %d: Syntax error. Previous command already has input.", line);
          return NULL;
        }

        token_now= token_now->next;
        if (token_now->t_type == WORD) // followed by a word
        {
          //which is valid output
            prev->output = token_now->text;
        }
        else
        {
          error(2, 0, "Line %d: Syntax error. Redirects must be followed by words.", line);
          return NULL;
        }

        // no pushing required
        break;
        default:
        break;
      };
      prev = comm;
  }

  while(size(operators) > 0)
    {
      command_t pop_ops = pop(operators);

      if (!make_command_branch(pop_ops, operands))
      {
          error(2, 0, "Line %d: Syntax error. Not enough children to create new tree.", line);
          return NULL;
      }
    }

  // check for single root
    if (size(operands) != 1)
    {
      error(2, 0, "Line %d: Syntax error. Tree did not converge into single root.", line);
      return NULL;
    }

    command_t root = pop(operands); // the root should be the final tree left in operands

    return root;
}
double farmer(int numprocs) {
	
	MPI_Status status;
	int i, flag, source, w_id;
	double result, incoming[5], *derp;
	
	int w_out[numprocs-1];
	
	// Set up stack
	stack *stack = new_stack();
	double data[5] = {A, B, F(A), F(B), (F(A)+F(B)) * (B-A)/2};
	push(data, stack);
	
	// Set up queue
	queue *queue = new_queue();
	for (i=1; i<numprocs; i++) {
	  push_queue(i, queue);
		w_out[i-1] = 0;
	}
	
	while (1) {
		if (!is_empty(stack)) {
			derp = pop(stack);
			w_id = pop_queue(queue);
			w_out[w_id] = 1;
			MPI_Send(derp, 5, MPI_DOUBLE, w_id, TAG_DO_TASK, MPI_COMM_WORLD);
			tasks_per_process[w_id]++;
		}
		
		// peek for messages
		MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
			
		// if there is a message
		if (flag) {
			switch(status.MPI_TAG) {
				case TAG_ADD_TASK:
				  
				  // receive data and push onto stack 
				  source = status.MPI_SOURCE;
				  MPI_Recv(&incoming, 5, MPI_DOUBLE, source, TAG_ADD_TASK, MPI_COMM_WORLD, &status);
					push(incoming, stack);
          if (w_out[source]) {
			      push_queue(source, queue);
						w_out[source] = 0;
          }
				  break;
			  case TAG_RESULT:
				  source = status.MPI_SOURCE;
				  MPI_Recv(&incoming, 5, MPI_DOUBLE, source, TAG_RESULT, MPI_COMM_WORLD, &status);
					result += incoming[4];
          if (w_out[source]) {
			      push_queue(source, queue);
						w_out[source] = 0;
          }
					break;
			}
		}
		
		// ready to finish?
	  if (workers_available(queue) == numprocs-1 && is_empty(stack)) { break; }	
	}
	
	// kill and free
  for (i=1; i<numprocs; i++) {
    MPI_Send(&data, 5, MPI_DOUBLE, i, TAG_KILL, MPI_COMM_WORLD);
  }
	free_stack(stack);
	free_queue(queue);
	return result;
}
Esempio n. 23
0
Item pop(Stack s)
{
  if (is_empty(s))
    terminate("Error in pop: stack is empty.");
  return s->contents[--s->top];
}
Esempio n. 24
0
int main(int argn, char** argv) {
	
	int xsize, ysize;
	char c, c2;
	int i, i2;
	int x, y;

	WINDOW* wnd;
	char buf[50];
	tile* temp_tile; 

	/* Inicjalizacja generatora liczb losowych */
	srand(time(0));

	wnd = initscr();
	start_color();
	
	if(has_colors()) {

		enable_tile_colors();
		use_default_colors();

		/* Przyporządkuj każdej płytce kolor */
		init_pair(1, COLOR_YELLOW, -1);
		init_pair(2, COLOR_GREEN, -1);
		init_pair(3, COLOR_RED, -1);
		init_pair(4, COLOR_YELLOW, -1);
		init_pair(5, COLOR_WHITE, -1);
		init_pair(6, COLOR_RED, -1);
		init_pair(7, COLOR_GREEN, -1);
		init_pair(8, COLOR_BLUE, -1);
		init_pair(9, COLOR_CYAN, -1);
		init_pair(10, COLOR_MAGENTA, -1);

	}
	else {

		disable_tile_colors();

	}

	cbreak();
	echo();
	nonl();
	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);

	getmaxyx(wnd, ysize, xsize);

	/* Pobierz docelowy rozmiar */
	while(1) {

		werase(wnd);

		draw_frame(wnd);

		wmove(wnd, ysize/2-(MAX_SIZE-MIN_SIZE+2), 20);	

		wprintw(wnd, "Available pool size:");

		for(i=MIN_SIZE;i<=MAX_SIZE;i++) {

			wmove(wnd, ysize/2-(MAX_SIZE-MIN_SIZE+2)+(i-MIN_SIZE+1), 20);
			attron(COLOR_PAIR(5) | A_BOLD);
			wprintw(wnd, "%d", i);
			attroff(COLOR_PAIR(5) | A_BOLD);
			wprintw(wnd, " for %dx%d", i, i);
			
		}

		wmove(wnd, ysize-2, 2);
		wprintw(wnd, "Saephir (c), 2010");

		wmove(wnd, ysize/2+1, 20);
		wprintw(wnd, "Type the desired number: ");

		c = getch();

		buf[0] = c;
		buf[1] = 0;

		i2 = atoi(buf);

		if(i2 >= MIN_SIZE && i2 <= MAX_SIZE) {
			TILES_COUNT = i2;
			init();
			break;
		}

	}

	while(1) {

		werase(wnd);

		draw_frame(wnd);

		/* Wygrana gra */
		if(verify()) {

			print_game(wnd);

			wmove(wnd, ysize/2, 40);
			wprintw(wnd, "Well done!");
			wmove(wnd, ysize/2+1, 40);
			wprintw(wnd, "Press ENTER to exit...");
			getch();
			break;

		}

		print_game(wnd);
		print_pool(wnd);

		wmove(wnd, ysize-2, 1);

		wgetnstr(wnd, buf, 49);
		buf[49] = 0;

		if(strcmp(buf, "exit") == 0 || strcmp(buf, "quit") == 0 || strcmp(buf, "q") == 0) {

			break;

		}
		else if(strcmp(buf, "help") == 0 || strcmp(buf, "?") == 0) {

			wmove(wnd, ysize-2, 1);
			wclrtoeol(wnd);
			draw_frame(wnd);
			wmove(wnd, ysize-2, 1);
			wprintw(wnd, HELP_LINE);
			getch();
			wmove(wnd, ysize-2, 1);
			wclrtoeol(wnd);
			draw_frame(wnd);
			wmove(wnd, ysize-2, 1);
			wprintw(wnd, HELP_LINE2);
			getch();

		}

		else if(strcmp(buf, "<<") == 0) {

			push_left();

		}

		else if(strcmp(buf, ">>") == 0) {

			push_right();

		}

		else if(strcmp(buf, "^^") == 0) {

			push_top();

		}

		else if(strcmp(buf, "vv") == 0) {

			push_bottom();

		}
		else if(sscanf(buf, "%c%d<%c%d", &c, &i, &c2, &i2) == 4) {

			i--;
			i2--;

			if(c == c2 && i == i2)
				continue;

			if(c-'a' < 0 || c-'a' >= 2*TILES_COUNT)
				continue;

			if(c2-'a' < 0 || c2-'a' >= 2*TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			if(i2 < 0 || i2 >= TILES_COUNT)
				continue;

			/* Przesuwamy na pole gry */
			if(c-'a' < TILES_COUNT) {

				temp_tile = &game[i][c-'a'];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* przesuwamy z puli do gry */
				if(c2-'a' >= TILES_COUNT)
					temp_tile = &pool[i2][c2-'a'-TILES_COUNT];
				/* przesuwamy z gry do gry */
				else
					temp_tile = &game[i2][c2-'a'];

				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&game[i][c-'a'], temp_tile);

			}
			/* Przesuwamy do puli */
			else {

				temp_tile = &pool[i][c-'a'-TILES_COUNT];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z pola gry do puli */
				if(c2-'a' < TILES_COUNT)
					temp_tile = &game[i2][c2-'a'];
				/* Przesuwamy z puli do puli */
				else
					temp_tile = &pool[i2][c2-'a'-TILES_COUNT];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&pool[i][c-'a'-TILES_COUNT], temp_tile);

			}
			


		}
		else if(sscanf(buf, "%c%d>%c%d", &c, &i, &c2, &i2) == 4) {

			i--;
			i2--;

			if(c == c2 && i == i2)
				continue;

			if(c-'a' < 0 || c-'a' >= 2*TILES_COUNT)
				continue;

			if(c2-'a' < 0 || c2-'a' >= 2*TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			if(i2 < 0 || i2 >= TILES_COUNT)
				continue;

			/* Przesuwamy do puli */
			if(c2-'a' >= TILES_COUNT) {

				temp_tile = &pool[i2][c2-'a'-TILES_COUNT];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z pola gry */
				if(c-'a' < TILES_COUNT)
					temp_tile = &game[i][c-'a'];
				/* Przesuwamy z puli */
				else
					temp_tile = &pool[i][c-'a'-TILES_COUNT];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&pool[i2][c2-'a'-TILES_COUNT], temp_tile);

			}
			/* Przesuwamy na pole gry */
			else {

				temp_tile = &game[i2][c2-'a'];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z puli na pole gry */
				if(c-'a' >= TILES_COUNT)
					temp_tile = &pool[i][c-'a'-TILES_COUNT];
				/* Przesuwamy z pola gry na pole gry */
				else
					temp_tile = &game[i][c-'a'];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&game[i2][c2-'a'], temp_tile);

			}

		}
		else if(sscanf(buf, "%c%d>pool", &c, &i) == 2 || sscanf(buf, "pool<%c%d", &c, &i) == 2) {

			i--;

			if(strcmp(&buf[2], ">pool") != 0) {
				buf[5] = 0;
				if(strcmp(buf, "pool<") != 0)
					continue;
			}

			if(c-'a' < 0 || c-'a' >= TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			/* Żródło nie może być puste */
			if(is_empty(&game[i][c-'a']))
				continue;

			/* Jeżeli źródło nie jest puste, to istnieją wolne miejsca w puli */
			/* znajdujemy więc pierwsze wolne miejsce */
			for(y=0;y<TILES_COUNT;y++) {
				for(x=0;x<TILES_COUNT;x++) {
					
					if(is_empty(&pool[x][y])) {
						
						move_tile(&pool[x][y], &game[i][c-'a']);
						break;
					}

				}
			}
			

		}

	}

	endwin();

	return 0;
}
Esempio n. 25
0
static void send_presence_soap(struct sipe_core_private *sipe_private,
                               gboolean do_publish_calendar,
                               gboolean do_reset_status)
{
    struct sipe_calendar* cal = sipe_private->calendar;
    gchar *body;
    gchar *tmp;
    gchar *tmp2 = NULL;
    gchar *res_note = NULL;
    gchar *res_oof = NULL;
    const gchar *note_pub = NULL;
    gchar *states = NULL;
    gchar *calendar_data = NULL;
    gchar *epid = get_epid(sipe_private);
    gchar *from = sip_uri_self(sipe_private);
    time_t now = time(NULL);
    gchar *since_time_str = sipe_utils_time_to_str(now);
    const gchar *oof_note = cal ? sipe_ews_get_oof_note(cal) : NULL;
    const char *user_input;
    gboolean pub_oof = cal && oof_note && (!sipe_private->note || cal->updated > sipe_private->note_since);

    if (oof_note && sipe_private->note) {
        SIPE_DEBUG_INFO("cal->oof_start           : %s", asctime(localtime(&(cal->oof_start))));
        SIPE_DEBUG_INFO("sipe_private->note_since : %s", asctime(localtime(&(sipe_private->note_since))));
    }

    SIPE_DEBUG_INFO("sipe_private->note  : %s", sipe_private->note ? sipe_private->note : "");

    if (!SIPE_CORE_PRIVATE_FLAG_IS(INITIAL_PUBLISH) ||
            do_reset_status)
        sipe_status_set_activity(sipe_private, SIPE_ACTIVITY_AVAILABLE);

    /* Note */
    if (pub_oof) {
        note_pub = oof_note;
        res_oof = SIPE_SOAP_SET_PRESENCE_OOF_XML;
        cal->published = TRUE;
    } else if (sipe_private->note) {
        if (SIPE_CORE_PRIVATE_FLAG_IS(OOF_NOTE) &&
                !oof_note) { /* stale OOF note, as it's not present in cal already */
            g_free(sipe_private->note);
            sipe_private->note = NULL;
            SIPE_CORE_PRIVATE_FLAG_UNSET(OOF_NOTE);
            sipe_private->note_since = 0;
        } else {
            note_pub = sipe_private->note;
            res_oof = SIPE_CORE_PRIVATE_FLAG_IS(OOF_NOTE) ? SIPE_SOAP_SET_PRESENCE_OOF_XML : "";
        }
    }

    if (note_pub)
    {
        /* to protocol internal plain text format */
        tmp = sipe_backend_markup_strip_html(note_pub);
        res_note = g_markup_printf_escaped(SIPE_SOAP_SET_PRESENCE_NOTE_XML, tmp);
        g_free(tmp);
    }

    /* User State */
    if (!do_reset_status) {
        if (sipe_status_changed_by_user(sipe_private) &&
                !do_publish_calendar &&
                SIPE_CORE_PRIVATE_FLAG_IS(INITIAL_PUBLISH)) {
            const gchar *activity_token;
            int avail_2007 = sipe_ocs2007_availability_from_status(sipe_private->status,
                             &activity_token);

            states = g_strdup_printf(SIPE_SOAP_SET_PRESENCE_STATES,
                                     avail_2007,
                                     since_time_str,
                                     epid,
                                     activity_token);
        }
        else /* preserve existing publication */
        {
            if (sipe_private->ocs2005_user_states) {
                states = g_strdup(sipe_private->ocs2005_user_states);
            }
        }
    } else {
        /* do nothing - then User state will be erased */
    }
    SIPE_CORE_PRIVATE_FLAG_SET(INITIAL_PUBLISH);

    /* CalendarInfo */
    if (cal && (!is_empty(cal->legacy_dn) || !is_empty(cal->email)) && cal->fb_start && !is_empty(cal->free_busy))
    {
        char *fb_start_str = sipe_utils_time_to_str(cal->fb_start);
        char *free_busy_base64 = sipe_cal_get_freebusy_base64(cal->free_busy);
        calendar_data = g_strdup_printf(SIPE_SOAP_SET_PRESENCE_CALENDAR,
                                        !is_empty(cal->legacy_dn) ? cal->legacy_dn : cal->email,
                                        fb_start_str,
                                        free_busy_base64);
        g_free(fb_start_str);
        g_free(free_busy_base64);
    }

    user_input = (sipe_status_changed_by_user(sipe_private) ||
                  sipe_is_user_available(sipe_private)) ?
                 "active" : "idle";

    /* generate XML */
    body = g_strdup_printf(SIPE_SOAP_SET_PRESENCE,
                           sipe_private->username,
                           sipe_ocs2005_availability_from_status(sipe_private),
                           sipe_ocs2005_activity_from_status(sipe_private),
                           (tmp = g_ascii_strup(g_get_host_name(), -1)),
                           res_note ? res_note : "",
                           res_oof ? res_oof : "",
                           states ? states : "",
                           calendar_data ? calendar_data : "",
                           epid,
                           since_time_str,
                           since_time_str,
                           user_input);
    g_free(tmp);
    g_free(tmp2);
    g_free(res_note);
    g_free(states);
    g_free(calendar_data);
    g_free(since_time_str);
    g_free(epid);

    sip_soap_raw_request_cb(sipe_private, from, body, NULL, NULL);

    g_free(body);
}
Esempio n. 26
0
File: cchk.c Progetto: DevCool/C_Dev
/* check_source:  checks source code for syntax errors */
int check_source(void)
{
	extern char line[];
	extern stack_t stack;
	extern state_t state;
	extern int comments;
	extern int quotes;
	extern int error;
	int c, d, i;
	int ln, len;

	error = 0;
	ln = 0;
	comments = quotes = 0;
	while ((len = getln()) > 0) {
		++ln;
		i = 0;
		while (i < len && (c = line[i++]) != EOF) {
			switch (state) {
			case CODE:
				if (c == '\'' || c == '"') {
					state = QUOTES;
					break;
				}
				if (c == '/') {
					d = line[i++];
					if (d == '*') {
						state = COMMENT;
						break;
					}
				}
				if (c == '(' || c == '[' || c == '{') {
					push(&stack, c, ln);
				} else if (c == ')' || c == ']' || c == '}') {
					if (is_empty(&stack)) {
						printf("Syntax error line %d: '%c' doesn't have match.\n",
							ln, c);
						error = 1;
					} else {
						int val, pos;
						pop(&stack, &val, &pos);
						if ((val != '(' && c == ')') ||
							(val != '[' && c == ']') ||
							(val != '{' && c == '}')) {
							printf("Syntax error line %d: '%c' does not match"
								" '%c'.\n", pos, val, c);
							error = 1;
						}
					}
				}
			break;
			case QUOTES:
				if (c == '\\')
					continue;
				else if (c == '\'' || c == '"') {
					quotes++;
					state = CODE;
				}
			break;
			case COMMENT:
				if (c == '*') {
					d = line[i++];
					if (d == '/') {
						comments++;
						state = CODE;
					}
				}
			break;
			}
		}
	}

	report();
	return 0;
}
inline bool
basic_cstring<CharT>::empty() const
{
    return is_empty();
}
Esempio n. 28
0
void *peek(RB)
{CHKRB; if (is_empty(RB)) return NULL;
  return data[s];
}
void ContiguousSpace::object_iterate(ObjectClosure* blk) {
  if (is_empty()) return;
  WaterMark bm = bottom_mark();
  object_iterate_from(bm, blk);
}
Esempio n. 30
0
void InterpretedIC::clear_without_deallocation_pic() {
  if (is_empty()) return;
  set(Bytecodes::original_send_code_for(send_code()), oop(selector()), smiOop_zero);
}