int main() {
    struct vector_t vec;
    vector_init(&vec);
    vector_push_back(&vec, 5);
    int i, value;
    for (i = 0; i < vector_get_size(vec); i++)
    {
        value = vector_at(vec, i);
        printf("%d \n", value);
    }
    
    value = vector_pop_back(&vec);
    printf("%d\n", value);
    
    value = vector_at(vec, 456);
    printf("%d\n", value);
    vector_destroy(&vec);
    return 0;
}
int main() {
	struct vector_t x;
	vector_init(&x);
	vector_push_back(&x, 1);
	vector_push_back(&x, 2);
	vector_push_back(&x, 3);
	vector_pop_back(&x);
	vector_resize(&x);
	vector_at(x, 2);

	struct vector_t y;
	vector_copy(&x, &y);
	vector_pop_back(&y);
	vector_pop_back(&y);
	if (vector_get_size == 0)
		vector_destroy(&y);

	return 0;
}
Ejemplo n.º 3
0
/**
 * @brief 输入事件模块初始化
 *
 * @param keybd_device_path 鼠标路径
 * @param mouse_device_path 键盘路径
 * @param double_click_delay 双击时间间隔
 *
 * @return 成功返回0 否则返回-1
 **/
static si_t event_init(char* keybd_device_path, char* mouse_device_path, si_t double_click_delay)
{
	struct input_device device;

	/**
	 * 初始化输入设备数组
	 **/
	vector_init(&global_wm.input_device_vector);

	/**
	 * 初始化键盘输入设备
	 **/
	if(keybd_init(&device, keybd_device_path) < 0)
	{
		EGUI_PRINT_ERROR("failed to init keybd device");
		return -1;
	}
	/**
	 * 将键盘输入设备添加到输入设备队列中
	 **/
	vector_push_back(&global_wm.input_device_vector, &device, sizeof(device));

	/**
	 * 初始化鼠标输入设备
	 **/
	if(mouse_init(&device, mouse_device_path, double_click_delay) < 0)
	{
		EGUI_PRINT_ERROR("failed to init mouse device");
		return -1;
	}
	/**
	 * 将键盘输入设备添加到输入设备队列中
	 **/
	vector_push_back(&global_wm.input_device_vector, &device, sizeof(device));

	/**
	 * 初始化消息队列
	 **/
	list_init(&global_wm.message_list);

	return 0;
}
Ejemplo n.º 4
0
void test_iterator_begin(){
	Vector* vec = vector_init(1);
	int a = 1, b = 2, c = 3, d = 4;

	vector_push_back(vec, &a);
	vector_push_back(vec, &b);
	vector_push_back(vec, &c);
	vector_push_back(vec, &d);

	Iterator* it = iterator_init(vec);
	assert(iterator_element(it) == &a);
	iterator_next(it);
	iterator_next(it);
	iterator_next(it);
	iterator_begin(it);
	assert(iterator_element(it) == &a);

	iterator_destroy(it);
	vector_destroy(vec);
}
Ejemplo n.º 5
0
/**
 * Initialize hashtable container.
 */
void _hashtable_init(_hashtable_t* pt_hashtable, size_t t_bucketcount, unary_function_t ufun_hash, binary_function_t bfun_compare)
{
    assert(pt_hashtable != NULL);
    assert(_hashtable_is_created(pt_hashtable));

    /* initialize the bucket vector and node count */
    vector_init(&pt_hashtable->_vec_bucket);
    if(t_bucketcount > 0)
    {
        vector_resize(&pt_hashtable->_vec_bucket, _hashtable_get_prime(t_bucketcount));
    }
    else
    {
        vector_resize(&pt_hashtable->_vec_bucket, _hashtable_get_prime(_HASHTABLE_DEFAULT_BUCKET_COUNT));
    }
    pt_hashtable->_t_nodecount = 0;

    /* initialize the hash, compare and destroy element function */
    pt_hashtable->_ufun_hash = ufun_hash != NULL ? ufun_hash : _hashtable_default_hash;
    pt_hashtable->_bfun_compare = bfun_compare != NULL ? bfun_compare : _GET_HASHTABLE_TYPE_LESS_FUNCTION(pt_hashtable);
}
Ejemplo n.º 6
0
void test_iterator_valid(){
	Vector* vec = vector_init(1);
	int a = 1, b = 2, c = 3, d = 4;

	vector_push_back(vec, &a);
	vector_push_back(vec, &b);
	vector_push_back(vec, &c);
	vector_push_back(vec, &d);

	Iterator* it = iterator_init(vec);
	assert(iterator_valid(it) == 1);
	iterator_before(it);
	assert(iterator_valid(it) == 0);
	iterator_end(it);
	assert(iterator_valid(it) == 1);
	iterator_next(it);
	assert(iterator_valid(it) == 0);

	iterator_destroy(it);
	vector_destroy(vec);
}
Ejemplo n.º 7
0
int main(int argc, char **argv) {
  atexit(on_client_exit);

  const char *cargs_file = CARGS_FILE;
  cargs = MALLOC(client_args);
  if (read_cargs((const char *)cargs_file, cargs)) {
      exit(1);
  }
  
  utils_init();
  perhaps_init();
  vector_init(&interfaces, sizeof(struct ifi_info));

  // Initialize the receiving window
  rwindow_init(&rwin, cargs->sw_size);

  get_all_interfaces();

  // Call print_ifi_info().
  print_ifi_info((struct ifi_info*)vector_at(&interfaces, 0));

  conn = MALLOC(client_conn);
  file_name_pkt = MALLOC(packet_t);
  memset(file_name_pkt, 0, sizeof(packet_t));
  file_name_pkt->ack = 0;
  file_name_pkt->seq = 0;
  file_name_pkt->flags = FLAG_SYN;
  file_name_pkt->datalen = strlen(cargs->file_name);
  strcpy(file_name_pkt->data, cargs->file_name);

  get_conn(conn);
  INFO("Server is %s\nIPServer: %s\nIPClient: %s\n", 
       (conn->is_local ? "Local" : "Not Local"),
       sa_data_str(conn->serv_sa),
       sa_data_str(conn->cli_sa));
  initiate_tx();
  return 0;
}
Ejemplo n.º 8
0
static void hashtbl_rehash(hashtbl_t *h) {
  if (!h) return;
  size_t bktnum;
  if (h->size >= h->bktnum)
    bktnum = 2 * h->bktnum;
  else if (h->size >= 2 * HASHTBL_INIT_BUCKETS && h->size < h->bktnum / 3)
    bktnum = h->bktnum / 2;
  else return;
#ifndef NDEBUG
#ifdef _VERBOSE_
  fprintf(stderr, "hashtbl debug: rehashing... ");
#endif
#endif
  vector_t **buckets = (vector_t**)zmalloc(sizeof(vector_t*) * bktnum);
  for (size_t i = 0; i < h->bktnum; ++i) {
    vector_t *ob = h->buckets[i];
    if (!ob) continue;
    size_t obsz = vector_size(ob);
    for (size_t j = 0; j < obsz; ++j) {
      hash_elem_t *e = (hash_elem_t*)vector_get(ob, j);
      size_t bnum = h->hash(e->key) % bktnum;
      vector_t *nb = buckets[bnum];
      if (!nb)
        nb = vector_init((free_func_t)hashtbl_elem_free, (cmp_func_t)hashtbl_keycmp);
      nb = buckets[bnum] = vector_append(nb, e);
    }
    vector_set_free(ob, NULL);
    vector_destroy(ob);
  }
  free(h->buckets);
  h->buckets = buckets;
#ifndef NDEBUG
#ifdef _VERBOSE_
  fprintf(stderr, " done, oldbkts %zu newbkts %zu\n", h->bktnum, bktnum);
#endif
#endif
  h->bktnum = bktnum;
}
Ejemplo n.º 9
0
Archivo: json.c Proyecto: mlmhl/cWeb
static int unmarshal_array(const char **str_ptr, json_node *n) {
	int retCode;
	const char *str = *str_ptr + 1; // skip '['
	if (*str == ']') {	
		n->type = Array;
		n->arr = NULL;
		return 0;
	}
	n->arr = malloc(sizeof(vector));
	vector_init(n->arr, 0);
	
	while (1) {
		json_node *elem = new_json_node();
		if ((retCode = unmarshal_tag(&str, elem)) > 0) {
			return retCode;
		}

		if ((retCode = unmarshal_recursive(&str, elem)) > 0) {
			return retCode;
		}
		if ((retCode = v_push_ptr(n->arr, (void*)elem)) > 0) {
			return retCode;
		}
		
		if (*str == ']') {
			break;
		}
		else if (*str != ',') {
			return ERR_JSON_INVALID_ARRAY;
		}
		++str;
	}

	n->type = Array;
	*str_ptr = str + 1;
	return 0;
}
Ejemplo n.º 10
0
int main() {
  // declare and initialize a new vector
  Vector vector;
  vector_init(&vector);

  // fill it up with 150 arbitrary values
  // this should expand capacity up to 200
  int i;
  for (i = 200; i > -50; i--) {
    vector_append(&vector, i);
  }

  // set a value at an arbitrary index
  // this will expand and zero-fill the vector to fit
  vector_set(&vector, 4452, 21312984);

  // print out an arbitrary value in the vector
  printf("Heres the value at 27: %d\n", vector_get(&vector, 27));

  // we're all done playing with our vector, 
  // so free its underlying data array
  vector_free(&vector); // so free its underlying data array

}
Ejemplo n.º 11
0
/*
 * Unit test for the vector_remove function. Runs some example
 * operations and checks that results are as expected, writing
 * messages to the terminal so that errors can be detected and
 * pinpointed.
 *
 * \return zero on success.
 */
int test_remove (void)
{
  static unsigned long const remlist[] = { 9, 0, 4, 4 };
  static unsigned long const remlistlen = sizeof(remlist) / sizeof(*remlist);
  
  static int const check[] = { 101, 102, 103, 104, 107, 108 };
  static unsigned long const checklen = sizeof(check) / sizeof(*check);
  
  Vector vec;
  int ii;
  
  printf ("\nrunning test_remove...\n");
  
  vector_init (&vec);
  printf ("initialized: ");
  vector_dump (&vec);
  
  if (0 == vector_remove(&vec, 11)) {
    printf ("test_remove ERROR: should not have been able to remove at invalid index\n");
    vector_destroy (&vec);
    return -1;
  }
  
  for (ii = 0; ii < 10; ++ii) {
    if (0 != vector_append (&vec, 100+ii)) {
      printf ("test_remove ERROR: could not append %d\n", 100+ii);
      vector_destroy (&vec);
      return -1;
    }
    printf ("appended %2d: ", 100+ii);
    vector_dump (&vec);
  }
  
  for (ii = 0; ii < remlistlen; ++ii) {
    if (0 != vector_remove (&vec, remlist[ii])) {
      printf ("test_remove ERROR: could not remove pos %lu\n", remlist[ii]);
      vector_destroy (&vec);
      return -1;
    }
    printf ("removed pos %lu: ", remlist[ii]);
    vector_dump (&vec);
  }
  
  if (0 == vector_remove(&vec, vec.len)) {
    printf ("test_remove ERROR: should not have been able to remove beyond end\n");
    vector_destroy (&vec);
    return -1;
  }
  
  if (checklen != vec.len) {
    printf ("test_remove ERROR: vector length should be %lu but is %lu\n", checklen, vec.len);
    vector_destroy (&vec);
    return -2;
  }
  
  for (ii = 0; ii < checklen; ++ii)
    if (vec.arr[ii] != check[ii]) {
      printf ("test_remove ERROR: arr[%d] should be %d but is %d\n", ii, check[ii], vec.arr[ii]);
      vector_destroy (&vec);
      return -1;
    }
  
  printf ("test_remove SUCCESS\n");
  
  vector_destroy (&vec);
  return 0;
}
Ejemplo n.º 12
0
void command(vector_t *** vecs)
{
int terminated = 0;
int i = 0;
int N = 0, rc = 0;
int fr = 0, fsk = 0, fpr = 0, fskkv = 0, fkav = 0, max = 0;
char input[N_MAX];
char *p, *p2, *output;
vector_t * vec, * vec1;
double val;

vector_t ** vectors = *vecs;

while (!terminated) {

  printf("\n> ");
  gets( input );
  
  fr = fsk = fpr = fskkv = 0;
  for (i = 0; i < strlen(input); i ++) {
    if (input[i] == '=') fr = 1;
    if ((input[i] == '(') || (input[i] == ')')) fsk = 1;
    if (input[i] == ' ') fpr = 1;
    if (input[i] == '[') fskkv = 1;
    if (input[i] == '"') fkav = 1;
  }
    
  if ((fr == 0) && (fsk == 0) && (fpr == 0) && (fskkv == 0)) {
    if (strcmp("ls", input) == 0) 
	ls(vectors);

    else if (strcmp("help", input) == 0) 
	help();

    else if (strcmp("quit", input) == 0)
	terminated = 1;

    else printf("Command is not found\n");
  }


  if ((fr == 0) && (fsk == 1)) {
    p = strtok(input, "(");

    if (strcmp(p, "disp") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec)
	  printf("dispersion %s = %f\n", p, disp(vec->size, vec->vals));
        else
          printf("ERROR: Parameter '%s' not found\n", p );
    }

    else if (strcmp(p, "avg") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec)
	  printf("average %s = %f\n", p, avg(vec->size, vec->vals));
        else
          printf("ERROR: Parameter '%s' not found\n", p );
 
    }

    else if (strcmp(p, "print") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec) {
	  printf("Vector %s: \n", p);
	  vector_print(vec);
        }
        else
          printf("ERROR: Parameter '%s' not found\n", p );
 
    }
    
    else if (strcmp(p, "load") == 0)
    {
      p = strtok(NULL, ")");
      rc = load_csv(&vectors, p);
      if (rc == -1) printf("Failed to load file: %s \n", p);
    }

    else if (strcmp(p, "save") == 0)
    {
      p = strtok(NULL, ")");
      rc = save_csv(vectors, p);
      if (rc == -1) printf("Failed to save file: %s \n", p);
    }


    else if (strcmp(p, "delete") == 0)
    {
      p = strtok(NULL, ")");
      vec = vectors_search( vectors, p);
	if (vec) {
	  vectors_remove(&vectors, vec);
        }
        else
          printf("ERROR: Parameter '%s' not found\n", p );
    }

    else if (strcmp(p, "gnuplot") == 0)
    {
      p = strtok(NULL, ")");
      gcmd(p);
    }

    else printf("Command is not found\n");
  } 


  if ((fr == 1) && (fskkv == 1)) {
    p = strtok(input, " =");

    vec = (vector_t*) malloc (sizeof( vector_t ) );
    vector_init( p, 0, vec );
    
    p = strtok(NULL, "= [,]");
    while ( p )
    {
      val = strtod( p, &p2 );
      if ( p == p2 )
      { 
        vector_clear( vec );
        free( vec );
        vec = 0;
        printf( "ERROR: Input data is invalid\n" );
        break;
      }
      else
      {
         vector_append( vec, 1, &val );
      }
      p = strtok(NULL, " ,]");
    }	

    if ( vec )
    {
      vec1 = vectors_search( vectors, vec->name );
      if (vec1) 
      {
	vector_clear( vec1 );
        vector_append( vec1, vec->size, vec->vals );
        vector_clear( vec );
        free( vec );
        vec = 0;
      }
      else
      { 
        vectors_add( &vectors, vec );

      }   
    }		
  }

  if ((fr == 1) && (fskkv == 0))
  {
    for (i = 0; i < vectors_count(vectors); i ++)
      if (max < vectors[i]->size) max = vectors[i]->size;
    printf("%d\n", max);
    printf("%d\n", vectors_count(vectors));
    sergey(vectors, input, max, vectors_count(vectors));
  }

  if ((fpr == 1) && (fskkv == 0) && (fsk == 0))
  {
    p = strtok(input, " ");
    if (strcmp(p, "plot") == 0)
    {
      p = strtok(NULL, " ");
      vec = vectors_search(vectors, p);
      if (vec)
      {
        p = strtok(NULL, " ");
        vec1 = vectors_search(vectors, p);
        if (vec1)
        {
          p = strtok(NULL, " ");
          output = p;
          if (strcmp(p, "wxt") == 0) { output = NULL; }
          p = strtok(NULL, ".");
          N = atoi(p);
          gplot_vector(vec, vec1, output, N);
        }
      }
   }
   else printf("Command is not found\n");
  }
}
 *vecs = vectors;
}
Ejemplo n.º 13
0
Archivo: state.c Proyecto: pdziepak/rcl
rcl_status init_state(const char* owner, uint32_t length, uint64_t verifier,
	state_t* state_id)
{
	uint64_t id;
	struct client_state* state;
	rcl_status error = RCL_OK;

	char owner_buffer[256];
	memset(owner_buffer, 0, 256);
	strncpy(owner_buffer, owner, min(255, length));
	log_print(log_notice, "Initializing new state:\n\towner: %s\n\t"	\
		"verifier: %#" PRIx64 "", owner_buffer, verifier);

	state = malloc(sizeof(struct client_state));
	if (!state)
		return RCL_HOST_RESOURCE;

	state->owner = malloc(length);
	if (!state->owner) {
		error = RCL_HOST_RESOURCE;
		goto out_alloc;
	}
	memcpy(state->owner, owner, length);
	state->owner_length = length;
	state->verifier = verifier;
	state->cluster_state = cluster_state;

	state->last_sequence = 0;

	error = cl_init_state(state);
	if (error)
		goto out_alloc;

	pthread_mutex_init(&state->lock, NULL);
	vector_init(&state->buffers, sizeof(struct buffer_state*));
	vector_init(&state->programs, sizeof(struct program_state*));
	vector_init(&state->kernels, sizeof(struct kernel_state*));

	pthread_mutex_lock(&states_lock);
	do {
		id = random_uint64();
	} while (bst_insert(&states_tree, &state->node, id));

	state->state_id = id;
	state->expire_epoch = current_epoch;
	list_add(renewed_states, &state->expire);
	pthread_mutex_unlock(&states_lock);

	*state_id = id;

	error = relay_init_state(state, owner, length, verifier);
	if (error)
		quit_state(id, 1);

	return error;

out_alloc:
	if (state)
		free(state->owner);
	free(state);
	return error;
}
Ejemplo n.º 14
0
int main()
{
	/************************************
	 *        INITIALIZATIONS
	 ************************************/
	// Set up Camera VDMA
	VDMAInit(FrameBuffer);

	// Set up Compositor
	unsigned int threshold = 0x0CCC0FFF;
	CompositorInit(FrameBuffer, DrawBuffer, DisplayBuffer, threshold);

	// Initialize Buffers
	FillBuffer(FrameBuffer,0x00ff0000); //black
	FillBuffer(DrawBuffer,0x0); //black
	FillBuffer(DisplayBuffer,0x0); //black

	// Turn on Display
	Display(DisplayBuffer);

	/************************************
	 *           MAIN LOOP
	 ************************************/
	while(1){

	// Capture a Frame
	// -We are guaranteed a single frame because Microblaze is faster than
	//  30Hz, so as long as we don't sleep to early, we are guaranteed
	//  VDMA will write a single frame and stop, decreasing the sleep
	//  value more will not make a difference, may cause no frame to be written
	// -If there is a compositor/VMDA race condition, use VDMAStopAndWait()
	VDMAStart();
	sleep(500000);
	VDMAStop();


	// Run Compositor
	// -Super slow, need to accelerate
	CompositorRun();

	// LED Detection & Draw on Drawing Buffer
	// -Currently this appears to give very large unchanging values
	//unsigned int x = CompositorGetXPos();
	//unsigned int y = CompositorGetYPos();

	// find the white blobs
	Vector blobList;
	vector_init(&blobList);
	// search region: 80 pix box at the center
	OnePass(&blobList, (char*) FrameBuffer, 640/2, 480/2, 240);


	// draw the found blobs
	int i, avg_x, avg_y, radius;
	struct Blob blob;
	for (i = 0; i < blobList.size; i ++){

		blob = vector_get(&blobList, i);
		avg_x = blob.total_x/blob.count;
		avg_y = blob.total_y/blob.count;
		radius = sqrt(blob.count)/2;

		//DrawSqure(avg_x, avg_y, radius, 2, (char*) DrawBuffer, 15, 15, 15);
		FillColor(avg_x-radius, avg_y-radius, avg_x+radius, avg_y+radius, (char*) DrawBuffer, 0, 0, 15);
	}


	}
}
Ejemplo n.º 15
0
static inline void vector_sub(vector v1, vector v2, vector v)
{
    vector_init(v, v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]);
}
Ejemplo n.º 16
0
expression_t parse_expr() {
    expression_t parsed_expr;
    stack_sym_t top;
    stack_sym_t next;
    vector_char_t* stack = vector_init(VI_CHAR);
    vector_token_t* token_buffer = vector_init(VI_TOKEN);
    vector_expr_t* expr_buffer = vector_init(VI_EXPR);
    vector_push(stack, S_END);

    bool use_cached = cached_identificator.type != TT_NONE;
    token_t last_token;
    token_t expr_token = use_cached ? cached_identificator : next_token ;
    next = token_to_sym(&expr_token);

    do {
        top = vector_find(stack, top_term_cmp);
        switch (prec_table[top][next]) {
            case TAB_SP:
                vector_insert_after(stack, S_SEP, top_term_cmp);
            case TAB_P:
                vector_push(stack, next);
                //next is now top terminal on stack
                top = next;
                //store last token
                vector_push(token_buffer, expr_token);
                //choose between cached_identificator and next_token
                if (use_cached) {
                    use_cached = false;
                    cached_identificator.type = TT_NONE;
                    expr_token = next_token;
                } else {
                    expr_token = next_token = get_next_token(token_stream);
                }
                //convert next token to table symbol
                next = token_to_sym(&expr_token);
                break;
            case TAB_R:
                last_token = vector_pop(token_buffer);
                switch (reduce_sequence(stack)) {
                    case RULE_REL:
                        check_rule_rel(last_token.op_rel, expr_buffer);
                        break;
                    case RULE_ADDSUB:
                        check_rule_arith(last_token.op_arith, expr_buffer);
                        break;
                    case RULE_MULDIV:
                        check_rule_arith(last_token.op_arith, expr_buffer);
                        break;
                    case RULE_PAR:
                        //only pop next token(TT_PARENTHESES_OPEN) from token buffer
                        vector_pop(token_buffer);
                        break;
                    case RULE_ID:
                        check_rule_id(&last_token, expr_buffer);
                        break;
                    default:
                        error("Syntactic error: Failed to parse the expression", ERROR_SYN);
                }
                vector_push(stack, S_EXPR);
                break;
            case TAB_END:
                if (vector_pop(stack) != S_EXPR) {
                    error("Syntactic error: Failed to parse the expression", ERROR_SYN);
                }
                parsed_expr = vector_top(expr_buffer);
                break;
            case TAB_ERR:
            default:
                error("Syntactic error: Failed to parse the expression", ERROR_SYN);
        }
    } while (top != S_END || next != S_END);

    ifj15_free(stack);
    ifj15_free(token_buffer);
    ifj15_free(expr_buffer);
    return parsed_expr;
}
Ejemplo n.º 17
0
vector_t vector_init_empty(size_t size, size_t count)
{
    // Implemented using vector_init().
    return vector_init(NULL, size, count);
}
Ejemplo n.º 18
0
si_t application_init(si_t video_access_mode, si_t application_type, char* name)
{
	/**
	 * 加载配置项
	 **/
	if(0 != application_load_config())
	{
		EGUI_PRINT_ERROR("failed to load config.");
		return -1;
	}

	/**
	 * 初始化客户端通信句柄
	 **/
	if(0 != uds_init(&global_application.uds, SOCK_STREAM, global_application.server_path, PEER_ROLE_CLIENT))
	{
		EGUI_PRINT_ERROR("Failed to init client uds");
		return -1;
	}
	/**
	 * 初始化消息队列
	 **/
	queue_init(&global_application.message_queue);
	client_lib_init(&global_application.uds, &global_application.message_queue);

	/**
	 * 初始化event_listener
	 **/
	event_listener_init(&global_application.app_event_listener);
	global_application.exec_flag = 0;

    /**
     * init focus list
     **/
    list_init(&(global_application.focus_list));

    /* 初始化向量 */
    vector_init(&(global_application.window_vector));

	/**
	 * 应用程序名称
	 **/
	global_application.name = malloc(strlen(name) + 1);
	if(NULL == global_application.name)
	{
		EGUI_PRINT_SYS_ERROR("failed to malloc for application name %s. malloc()", name);
		return -1;
	}
	strncpy(global_application.name, name, strlen(name) + 1);
	global_application.application_type = application_type;

	if(0 != register_application(video_access_mode, application_type, name))
	{
		EGUI_PRINT_ERROR("failed to register application %s.", name);
		return -1;
	}

    global_application.focus = NULL;
    global_application.main_window = NULL;

	global_application.desktop_ptr = NULL;
	global_application.desktop_msg_handler = NULL;

    term_init();

    return 0;
}
Ejemplo n.º 19
0
/*===========================================================================*
 *				main                                         *
 *===========================================================================*/
int main(int argc, char **argv)
{
/* This is the main routine of this service. The main loop consists of 
 * three major activities: getting new work, processing the work, and
 * sending the reply. The loop never terminates, unless a panic occurs.
 */
  message m_in;
  int result;                 
  
  sef_startup();

	vector_init(&sem_list);
    Qvector_init(&waiting_list);
	stackInit(&sem_stack,5);

  /* Main loop - get work and do it, forever. */         
  while (TRUE) {              


	
      /* Wait for incoming message, sets 'callnr' and 'who'. */
    get_work(&m_in);
	//printf("SEM recieved message %d\n",callnr);
      if (is_notify(callnr)) {
          printf("SEM: warning, got illegal notify from: %d\n", m_in.m_source);
          result = EINVAL;
          goto send_reply;
      }

	int arg = m_in.m1_i1;
	switch(callnr)
	{	
		case SEM_INIT:
			//printf("Sem_init called, semaphore size 3%d.\n",arg);			
			result = sem_init(arg);			
			break;
		case SEM_UP:
			//printf("Sem_up called on semaphore %d.\n",arg);
			result = sem_up(arg);
			break;
		case SEM_DOWN:
			//printf("Sem_down called on semaphore %d. source: %d\n",arg,who_e);
			result  = sem_down(arg,m_in.m_source);
			break;
		case SEM_RELEASE:
			//printf("Sem_release called on semaphore %d.\n",arg);
			result = sem_release(arg);
			break;
		default: 
          		printf("SEMAPHORE: warning, got illegal request from %d\n", m_in.m_source);
          		result = EINVAL;
	}	



send_reply:
    	/* Finally send reply message, unless disabled. */
    	if (result != EDONTREPLY) {
        	m_in.m_type = result;  		/* build reply message */
			reply(who_e, &m_in);		/* send it away */
      }
	}
	Qvector_free(&waiting_list);
	vector_free(&sem_list);
	return(OK);				/* shouldn't come here */
}
Ejemplo n.º 20
0
// Called once at startup by webC_init();
void wload_WebcVirtualFileSystemInitialize(void)
{
static int webcVfInitialized=0;
	vector_init(&gWebcVTableContainerVector, sizeof(WebcVTableContainer));
}
Ejemplo n.º 21
0
error_t net_layer_init(uint32 layer_ind, uint32 proto_count)
{
	net_layers[layer_ind].layer_ind = layer_ind;
	return vector_init(&net_layers[layer_ind].protocols, proto_count);
}
Ejemplo n.º 22
0
TEngine::TEngine(AnsiString FileName)
{
   util_init();
   my_random_init();
   square_init();
   piece_init();
   pawn_init_bit();
   value_init();
   vector_init();
   attack_init();
   move_do_init();
   random_init();
   hash_init();

   Reversed = true;
   board_from_fen(&StartBoard,StartFen);
   board_from_fen(&Board,StartFen);
   GameStarted = false;

   StateNewGame = false;
   LastCommitMove[0] = 0;
   Process = new TProcess(FileName);
   Process->Send("uci");
   char buf[10000];
   do {
      Sleep(10);
      if (Process->Get(buf)) {
        char *next_line = buf;
        while (true) {
           char *cur_line = next_line;
           if (cur_line[0] == 0)
             break;
           char *end = strstr(cur_line,"\r\n");
           end[0] = 0;
           end[1] = 0;
           next_line = end + 2;
           char *cur_word;
           while (cur_line) {
             cur_word = get_cur_word_str(&cur_line);
             int pos;
             if (string_equal(cur_word,"id")) {
               cur_word = get_cur_word_str(&cur_line);
               if (string_equal(cur_word,"name")) {
                   AnsiString EngineName = cur_line;
                   MainForm->lbEngineName->Caption = EngineName;
               }
             }
             if (string_equal(cur_word,"uciok")) {
                if (MainForm->MultiPV > 1) {
                   Process->Send("setoption name MultiPV value " + IntToStr(MainForm->MultiPV));
                   Sleep(100);
                   Process->Get(buf);
                }
                Process->Send("setoption name Hash value " + IntToStr(MainForm->HashSize));
                return;
             }
           }
        }
      }
   }
   while (true);
}
Ejemplo n.º 23
0
/***********************************************************************
 * Creates and links a new module to a process
 */
struct module* module_new(struct process* pcs, const WCHAR* name,
                          enum module_type type, BOOL virtual,
                          DWORD64 mod_addr, DWORD64 size,
                          unsigned long stamp, unsigned long checksum)
{
    struct module*      module;
    unsigned            i;

    assert(type == DMT_ELF || type == DMT_PE || type == DMT_MACHO);
    if (!(module = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*module))))
	return NULL;

    module->next = pcs->lmodules;
    pcs->lmodules = module;

    TRACE("=> %s %s-%s %s\n",
          get_module_type(type, virtual),
	  wine_dbgstr_longlong(mod_addr), wine_dbgstr_longlong(mod_addr + size),
          debugstr_w(name));

    pool_init(&module->pool, 65536);

    module->process = pcs;
    module->module.SizeOfStruct = sizeof(module->module);
    module->module.BaseOfImage = mod_addr;
    module->module.ImageSize = size;
    module_set_module(module, name);
    module->module.ImageName[0] = '\0';
    lstrcpynW(module->module.LoadedImageName, name, sizeof(module->module.LoadedImageName) / sizeof(WCHAR));
    module->module.SymType = SymNone;
    module->module.NumSyms = 0;
    module->module.TimeDateStamp = stamp;
    module->module.CheckSum = checksum;

    memset(module->module.LoadedPdbName, 0, sizeof(module->module.LoadedPdbName));
    module->module.CVSig = 0;
    memset(module->module.CVData, 0, sizeof(module->module.CVData));
    module->module.PdbSig = 0;
    memset(&module->module.PdbSig70, 0, sizeof(module->module.PdbSig70));
    module->module.PdbAge = 0;
    module->module.PdbUnmatched = FALSE;
    module->module.DbgUnmatched = FALSE;
    module->module.LineNumbers = FALSE;
    module->module.GlobalSymbols = FALSE;
    module->module.TypeInfo = FALSE;
    module->module.SourceIndexed = FALSE;
    module->module.Publics = FALSE;

    module->reloc_delta       = 0;
    module->type              = type;
    module->is_virtual        = virtual;
    for (i = 0; i < DFI_LAST; i++) module->format_info[i] = NULL;
    module->sortlist_valid    = FALSE;
    module->sorttab_size      = 0;
    module->addr_sorttab      = NULL;
    module->num_sorttab       = 0;
    module->num_symbols       = 0;

    vector_init(&module->vsymt, sizeof(struct symt*), 128);
    /* FIXME: this seems a bit too high (on a per module basis)
     * need some statistics about this
     */
    hash_table_init(&module->pool, &module->ht_symbols, 4096);
    hash_table_init(&module->pool, &module->ht_types,   4096);
    vector_init(&module->vtypes, sizeof(struct symt*),  32);

    module->sources_used      = 0;
    module->sources_alloc     = 0;
    module->sources           = 0;
    wine_rb_init(&module->sources_offsets_tree, &source_rb_functions);

    return module;
}
Ejemplo n.º 24
0
int ptr_vector_init(vector_t *vector, int allocation_count)
{
	return vector_init(vector, sizeof(void *), allocation_count);
}
Ejemplo n.º 25
0
Pipeline *
parse_cmd(String *line) {
    Pipeline *pipeline = (Pipeline *)alloc(sizeof(Pipeline), pipeline_free);
    pipeline->ground = FOREGROUND;
    Vector *vector = vector_init();
    pipeline->commands = vector;
    Command *cmd = alloc(sizeof(Command), cmd_free);
    vector_append(vector, cmd);
    release(cmd);

    int inString = 0;
    int isEscaped = 0;

    ParseState state = 0; // program, arguments

    cmd = (Command*)vector->objs[vector->count-1];
    cmd->program = str_init();
    cmd->arguments = vector_init();
    for (int i = 0; i < line->len; i++) {
        char c = line->string[i];
        if (!inString && !isEscaped) {
            if (c == ' ') {
                if (state == PROGRAM && cmd->program->len) {
                    state = ARGUMENTS;
                }
                if (state == ARGUMENTS) {
                    if (cmd->arguments->count) {
                        String *lastArgument = (String *)cmd->arguments->objs[cmd->arguments->count - 1];
                        if (lastArgument->len == 0) {
                            continue;
                        }
                    }
                    String *s = str_init();
                    vector_append(cmd->arguments, s);
                    release(s);
                }
                continue;
            }
            if (c == '|') {
                cmd = alloc(sizeof(Command), cmd_free);
                cmd->program = str_init();
                cmd->arguments = vector_init();
                vector_append(vector, cmd);
                release(cmd);
                state = PROGRAM;
                continue;
            }
            if (c == '&') {
                pipeline->ground = BACKGROUND;
            }
        }
        if ((c == '\"' || c == '\'') && !isEscaped) {
            inString = !inString;
            continue;
        }
        if (c == '\\' && !isEscaped) {
            isEscaped = 1;
            continue;
        }
        switch (state) {
            case PROGRAM: {
                str_append_char(cmd->program, c);
                continue;
            }
            case ARGUMENTS: {
                String *argument = (String *)cmd->arguments->objs[cmd->arguments->count - 1];
                str_append_char(argument, c);
                break;
            }
        }
    }

    for (int i = 0; i < vector->count; i++) {
        Command *cmd = (Command *)vector->objs[i];
        for (int j = cmd->arguments->count - 1; j >= 0; j--) {
            String *argument = (String *)cmd->arguments->objs[j];
            if (argument->len == 0) {
                vector_remove(cmd->arguments, j);
            }
        }
    }
    return pipeline;
}
Ejemplo n.º 26
0
void prepare_npc_lists()
{
	vector_init(&comms_npc_lines, COMMS_NPC_COUNT);
	vector_fill(&comms_npc_lines, NULL);

	//Allocate all the space we'll need for the default library of npc dialogue (anything else we can allocate as we go)
	for (int i = 0; i < COMMS_NPC_COUNT; i++) //npc lines 0 to 9
	{
		Vector **lines = malloc(4 * sizeof(Vector));
		for (int j = 0; j < 4; j++)
		{
			lines[j] = malloc(4 * sizeof(Vector));
			for (int t = 0; t < 4; t++) //tones 0 to 3
			{
				vector_init(&lines[j][t], 5);
			}
		}
		vector_set(&comms_npc_lines, i, lines);

		//load in the lines from file
		int next_state, next_state_index;
		
		switch (i)
		{
			case COMMS_NPC_GREETING:
				next_state = COMMS_STATE_PLAYER_CHOICE;
				next_state_index = COMMS_PLAYER_CHOICE_MAIN;
				break;
			case COMMS_NPC_DEFEND:
				next_state = COMMS_STATE_ENTER_COMBAT;
				next_state_index = -1;
				break;
			case COMMS_NPC_TRADE: //todo: We should define these values later based on the tone (angry NPCs don't want to trade, etc.)
				next_state = COMMS_STATE_PLAYER_CHOICE; //COMMS_STATE_ENTER_TRADE;
				if (faction_disposition[comms_faction] > FACTION_THRESHOLD_DISLIKE)
				{
					next_state_index = COMMS_PLAYER_CHOICE_TRADE; //-1; //TODO: This should be a buy/sell choice
				}
				else
				{
					next_state_index = COMMS_PLAYER_CHOICE_MAIN;
				}
				break;
			case COMMS_NPC_INFO: //todo: We should define these values later based on the tone (angry NPCs don't want to talk, etc.)
				next_state = COMMS_STATE_PLAYER_CHOICE; 
				next_state_index = COMMS_PLAYER_CHOICE_MAIN; //COMMS_PLAYER_CHOICE_INFO - if we detect that this is the next state, we need to work these out based on known topics/nearby planets
				break;
			case COMMS_NPC_FAREWELL:
				next_state = COMMS_STATE_ENTER_TRAVEL;
				next_state_index = -1;
				break;
			case COMMS_NPC_TRADE_ACCEPT_BUY:
				next_state = COMMS_STATE_ENTER_TRADE_BUY;
				next_state_index = -1;
				break;
			case COMMS_NPC_TRADE_ACCEPT_SELL:
				next_state = COMMS_STATE_ENTER_TRADE_SELL;
				next_state_index = -1;
				break;
			case COMMS_NPC_TRADE_DECLINE:
				next_state = COMMS_STATE_PLAYER_CHOICE;
				next_state_index = COMMS_PLAYER_CHOICE_MAIN;
				break;
			case COMMS_NPC_ATTACK_ACCEPT:
				next_state = COMMS_STATE_ENTER_COMBAT;
				next_state_index = -1;
				break;
			case COMMS_NPC_ATTACK_FLEE: //todo: Fleeing should cost fuel or have a random chance of failure?
				next_state = COMMS_STATE_ENTER_TRAVEL;
				next_state_index = -1;
				break;
			case COMMS_NPC_ATTACK_PLEAD: //todo: this value should be determined by how much the NPC wants to attack the player (eg: if there's no bounty, no cool loot and they don't care much, they may not bother)
				next_state = COMMS_STATE_PLAYER_CHOICE;
				next_state_index = COMMS_PLAYER_CHOICE_MAIN;
				break;
			default:
				next_state = -1;
				next_state_index = -1;
		}

		load_default_npc_lines(lines, comms_npc_line_files[i], next_state, next_state_index);
	}
}
Ejemplo n.º 27
0
void verr_thread_init() {
  vector_init(try_stack, sizeof(TryFrame), 3);
}
Ejemplo n.º 28
0
void comms_set_current_npc_lines()
{
	vector_free(&comms_current_npc_lines);
	vector_init(&comms_current_npc_lines, COMMS_NPC_COUNT);
	vector_fill(&comms_current_npc_lines, NULL);

	//todo: load possible npc text from file and select appropriate one based on disposition/bounty/resource need
	Comms_NPCDialogue *npcd;
	Vector ** line_type;
	int line_count = 0;

	line_type = (Vector **)vector_get(&comms_npc_lines, COMMS_NPC_GREETING);
	line_count = vector_get_size(&line_type[comms_faction][comms_tone]);
	npcd = vector_get(&line_type[comms_faction][comms_tone], rand() % line_count);
	vector_set(&comms_current_npc_lines, COMMS_NPC_GREETING, npcd);

	line_type = (Vector **)vector_get(&comms_npc_lines, COMMS_NPC_DEFEND);
	line_count = vector_get_size(&line_type[comms_faction][comms_tone]);
	npcd = vector_get(&line_type[comms_faction][comms_tone], rand() % line_count);
	vector_set(&comms_current_npc_lines, COMMS_NPC_DEFEND, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("We are glad you embrace fight willingly", 64);
	npcd->next_state = COMMS_STATE_ENTER_COMBAT;
	npcd->next_state_index = -1;
	vector_set(&comms_current_npc_lines, COMMS_NPC_ATTACK_ACCEPT, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("You get away.for today.", 64);
	npcd->next_state = COMMS_STATE_ENTER_TRAVEL;
	npcd->next_state_index = -1;
	vector_set(&comms_current_npc_lines, COMMS_NPC_ATTACK_FLEE, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("You are too pitiful to fight", 64);
	npcd->next_state = COMMS_STATE_PLAYER_CHOICE;
	npcd->next_state_index = COMMS_PLAYER_CHOICE_MAIN;
	vector_set(&comms_current_npc_lines, COMMS_NPC_ATTACK_PLEAD, npcd);

	line_type = (Vector **)vector_get(&comms_npc_lines, COMMS_NPC_TRADE);
	line_count = vector_get_size(&line_type[comms_faction][comms_tone]);
	npcd = vector_get(&line_type[comms_faction][comms_tone], rand() % line_count);
	vector_set(&comms_current_npc_lines, COMMS_NPC_TRADE, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("Good, let's trade", 64);
	npcd->next_state = COMMS_STATE_ENTER_TRADE_BUY;
	npcd->next_state_index = -1;
	vector_set(&comms_current_npc_lines, COMMS_NPC_TRADE_ACCEPT_BUY, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("Good, let's trade", 64);
	npcd->next_state = COMMS_STATE_ENTER_TRADE_SELL;
	npcd->next_state_index = -1;
	vector_set(&comms_current_npc_lines, COMMS_NPC_TRADE_ACCEPT_SELL, npcd);

	npcd = malloc(sizeof(Comms_NPCDialogue));
	npcd->text = wrap_text("No trade? oh well", 64);
	npcd->next_state = COMMS_STATE_PLAYER_CHOICE;
	npcd->next_state_index = COMMS_PLAYER_CHOICE_MAIN;
	vector_set(&comms_current_npc_lines, COMMS_NPC_TRADE_DECLINE, npcd);

	line_type = (Vector **)vector_get(&comms_npc_lines, COMMS_NPC_INFO);
	line_count = vector_get_size(&line_type[comms_faction][comms_tone]);
	npcd = vector_get(&line_type[comms_faction][comms_tone], rand() % line_count);
	vector_set(&comms_current_npc_lines, COMMS_NPC_INFO, npcd);

	line_type = (Vector **)vector_get(&comms_npc_lines, COMMS_NPC_FAREWELL);
	line_count = vector_get_size(&line_type[comms_faction][comms_tone]);
	npcd = vector_get(&line_type[comms_faction][comms_tone], rand() % line_count);
	vector_set(&comms_current_npc_lines, COMMS_NPC_FAREWELL, npcd);
}
Ejemplo n.º 29
0
Archivo: command.c Proyecto: ecks/harry
/* New string vector. */
static vector
cmd_make_descvec (const char *string, const char *descstr)
{ 
  int multiple = 0;
  const char *sp;
  char *token;
  int len;
  const char *cp;
  const char *dp;
  vector allvec;
  vector strvec = NULL;
  struct desc *desc;

  cp = string;
  dp = descstr;

  if (cp == NULL)
    return NULL;

  allvec = vector_init (VECTOR_MIN_SIZE);

  while (1)
    {
      while (isspace ((int) *cp) && *cp != '\0')
	cp++;

      if (*cp == '(')
	{
	  multiple = 1;
	  cp++;
	}
      if (*cp == ')')
	{
	  multiple = 0;
	  cp++;
	}
      if (*cp == '|')
	{
	  if (! multiple)
	    {
	      fprintf (stderr, "Command parse error!: %s\n", string);
	      exit (1);
	    }
	  cp++;
	}
      
      while (isspace ((int) *cp) && *cp != '\0')
	cp++;

      if (*cp == '(')
	{
	  multiple = 1;
	  cp++;
	}

      if (*cp == '\0') 
	return allvec;

      sp = cp;

      while (! (isspace ((int) *cp) || *cp == '\r' || *cp == '\n' || *cp == ')' || *cp == '|') && *cp != '\0')
	cp++;

      len = cp - sp;

      token = calloc(1, sizeof(char) * (len + 1));
      memcpy (token, sp, len);
      *(token + len) = '\0';

      desc = calloc (1, sizeof (struct desc));
      desc->cmd = token;
      desc->str = cmd_desc_str (&dp);

      if (multiple)
	{
	  if (multiple == 1)
	    {
	      strvec = vector_init (VECTOR_MIN_SIZE);
	      vector_set (allvec, strvec);
	    }
	  multiple++;
	}
      else
	{
	  strvec = vector_init (VECTOR_MIN_SIZE);
	  vector_set (allvec, strvec);
	}
      vector_set (strvec, desc);
    }
}
Ejemplo n.º 30
0
static inline void vector_add(vector v1, vector v2, vector v)
{
    vector_init(v, v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]);
}