Пример #1
0
void setup(TinBot* tinbot) {
    tinbot->sens.victim_attached = 0;
    t2t_data_init(&tinbot->rx_buffer);
    t2t_data_init(&tinbot->sens.t2t);
    modes[tinbot->mode].setup(tinbot);
    map_clear(map_get_accumulated());
    map_clear(map_get_proximity());
}
Пример #2
0
hint32 hdata_set_tree(hdata_set_t data_set, hdata_set_tree_key_t key,hdata_set_tree_key_t parent_key,hash_code_t key_hash,equal_t key_equal,list_compare_t comparator,hany param,InvokeTickDeclare){
	data_set_t * ds = (data_set_t *)data_set;
	hany k;
	hany pk;
	hint32 i,c;
	hdata_t items,item;
	data_set_tree_item_t * tree_item,*tree_pitem;
	data_set_tree_item_compare_param_t compare_param;
	if(ds && key && parent_key){
		data_set_tree_item_dealloc(ds->tree_root,InvokeTickArg);
		ds->tree_root = data_set_tree_item_alloc( NULL, ext_data(ds->data),NULL,NULL,NULL,InvokeTickArg);
		ds->tree_level = 0;
		if(ds->tree_cache == NULL){
			ds->tree_cache = map_alloc( key_hash, key_equal);
		}
		else{
			map_clear(ds->tree_cache);
		}
		items = ext_data(ds->data);
		c = hdata_array_size(ext_data_class(ds->data), items);
		for(i=0;i<c;i++){
			item = hdata_array(ext_data_class(ds->data),items,i);
			k = (*key)(data_set,item,param,InvokeTickArg);
			pk = (*parent_key)(data_set,item,param,InvokeTickArg);
			tree_pitem = map_get(ds->tree_cache, pk);
			tree_item = data_set_tree_item_alloc( k, item, tree_pitem == NULL?ds->tree_root:tree_pitem,comparator,param,InvokeTickArg);
			data_set_tree_item_dealloc( map_put(ds->tree_cache, k, tree_item),InvokeTickArg);
			if(ds->tree_level < tree_item->level){
				ds->tree_level = tree_item->level;
			}
		}
		c = list_count(ds->tree_root->childs);
		for(i=0;i<c;i++){
			tree_item = list_get(ds->tree_root->childs, i);
			pk = (*parent_key)(data_set,tree_item->data,param,InvokeTickArg);
			tree_pitem = map_get(ds->tree_cache, pk);
			if(tree_pitem){
				list_remove_at(ds->tree_root->childs, i--);
				c = list_count(ds->tree_root->childs);
				if(tree_pitem->childs==NULL){
					tree_pitem->childs = list_alloc(20, 20);
				}
				if(comparator){
					compare_param.compare = comparator;
					compare_param.param = param;
					list_add_and_order(tree_pitem->childs, tree_item, data_set_tree_item_compare, &compare_param);
				}
				else{
					list_add(tree_pitem->childs,tree_item);
				}
				tree_item->level = tree_pitem->level +1;
				if(ds->tree_level < tree_item->level){
					ds->tree_level = tree_item->level;
				}
			}	
		}
		return ds->tree_level;
	}
	return 0;
}
Пример #3
0
/* delete one name descriptor */ 
static void clist_forget(Content *target) { 
    Content *f; 
    if (!content_head) return; 
    if (target==content_head) { 
	content_head=content_head->next; 
        map_clear(&target->bhead); 
        free(target); return; 
    } 
    for (f=content_head; f && f->next!=target; f=f->next) ; 
    if (f) { 
	f->next=f->next->next; 
	map_clear(&target->bhead); 
	free(target); 
    } 
    return; 
} 
Пример #4
0
void style_change(appdata_t *appdata, const char *name) {
  char *new_style = NULL, *fname = NULL;

  file_chain_t *chain = file_scan(".style");

  while(chain) {
    file_chain_t *next = chain->next;
    style_t *style = style_parse(appdata, chain->name, NULL, TRUE);

    if(new_style == NULL && strcmp(style->name, name) == 0) {
      new_style = style_basename(chain->name);
      fname = chain->name;
      chain->name = NULL;
    }

    style_free(style);

    g_free(chain->name);
    g_free(chain);
    chain = next;
  }

  /* check if style has really been changed */
  if(appdata->settings->style &&
     !strcmp(appdata->settings->style, new_style)) {
    g_free(new_style);
    g_free(fname);
    return;
  }

  style_t *nstyle = style_load_fname(appdata, fname);
  if (nstyle == NULL) {
    errorf(GTK_WIDGET(appdata->window),
           _("Error loading style %s"), fname);
    g_free(new_style);
    g_free(fname);
    return;
  }
  g_free(fname);

  g_free(appdata->settings->style);
  appdata->settings->style = new_style;

  map_clear(appdata, MAP_LAYER_OBJECTS_ONLY);
  /* let gtk clean up first */
  while(gtk_events_pending()) {
    putchar('.');
    gtk_main_iteration();
  }

  style_free(appdata->map->style);
  appdata->map->style = nstyle;

  /* canvas background may have changed */
  canvas_set_background(appdata->map->canvas,
			appdata->map->style->background.color);

  map_paint(appdata);
}
Пример #5
0
static obj_ptr _map_clear(obj_ptr arg, obj_ptr env)
{
    if (NMAPP(arg))
        return MKERROR(MKSTRING("Expected a map in map-clear"), arg);

    map_clear(&MAP(arg));
    return NIL;
}
Пример #6
0
void network_deinit(struct network *net)
{
	if (net != NULL) {
		map_walk(&net->endpoints, visit_key, close_endpoint);
		map_walk(&net->endpoints, free_key, 0);
		map_clear(&net->endpoints);
	}
}
Пример #7
0
void map_free(struct _map *map)
{
    if (!map)
        return;

    map_clear(map);
    free(map->buckets);
    free(map);
}
Пример #8
0
static int reload_module(void) {
	msgs_unhook(&default_msgs, ema_exec);
	free_prices(contracts);
	map_clear(contracts);
	load_config();
	if (msgs_hook(&default_msgs, ema_exec, NULL) == -1)
		return MODULE_LOAD_FAILURE;
	return MODULE_LOAD_SUCCESS;
}
Пример #9
0
void _map_test()
{
    int a = 5, b = 12, c = 12345, d = 54321;
    int *aa, *bb, *cc, *dd, *ff;
    int repeat = 1;
    char *e = "Immanuel Kant",
          *ee;

    struct _map *map = map_new();
    assert(map != NULL);

    map_add(map, "rest not", &a);
    map_add(map, "life is sweeping by", &b);
    map_add(map, "go and do before you die", &c);
    map_add(map, "something mighty and sublime", &d);
    map_add(map, "leave behind to conquer time", e);

_repeat:
    aa = map_get(map, "rest not");
    if (repeat)
        assert(*aa == 5);
    else
        assert(aa == NULL);

    bb = map_get(map, "life is sweeping by");
    if (repeat)
        assert(*bb == 12);
    else
        assert(bb == NULL);
    cc = map_get(map, "go and do before you die");
    if (repeat)
        assert(*cc == 12345);
    else
        assert(cc == NULL);
    dd = map_get(map, "something mighty and sublime");
    if (repeat)
        assert(*dd == 54321);
    else
        assert(dd == NULL);
    ee = map_get(map, "leave behind to conquer time");
    if (repeat)
        assert(ee == e);
    else
        assert(ee == NULL);
    ff = map_get(map, "this is a nonexistent key");
    assert(ff == NULL);
    if (repeat) {
        repeat = 0;
        map_clear(map);
        goto _repeat;
    }
    fprintf(stdout, "%s: all tests passed\n", __func__);
    map_free(map);
}
Пример #10
0
unsigned long
addrxlat_map_decref(addrxlat_map_t *map)
{
	unsigned long refcnt = --map->refcnt;
	if (!refcnt) {
		map_clear(map);
		if (map->ranges)
			free(map->ranges);
		free(map);
	}
	return refcnt;
}
Пример #11
0
int main() {
    static const int iterations = 1000 * 1000;
    Map* accu;
    Map* prox;
    int i;
    clock_t time;

    accu = map_get_accumulated();
    prox = map_get_proximity();
    map_clear(accu);
    map_clear(prox);

    while (1) {
        time = clock();
        for (i = 0; i < iterations; ++i) {
            map_merge(accu, 4, 2, prox);
        }
        time = clock() - time;
        printf("%.3f us/iter\n", time * 1000000.0 / (iterations * CLOCKS_PER_SEC));
    }
}
Пример #12
0
int queue_clear(QUEUE* queue)
{
    int err;
    
    queue_dispose(queue);    
    err = queue_init(queue);
    
    if (err) {
        return err;
    }
    
    map_clear(queue->map);
    
    return err;
}
Пример #13
0
void SoundManager::destroy_AllSounds()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
	CocosDenshion::SimpleAudioEngine::sharedEngine()->stopAllEffects();

	auto begin = effect_sound_id_list.begin();
	auto end = effect_sound_id_list.end();
	auto i = effect_sound_id_list.begin();

	for(auto i = begin; i != end; ++i)
		SoundManager::Instance()->stop_EffectMusic(i->first);

	map_clear(effect_sound_id_list);

	CocosDenshion::SimpleAudioEngine::sharedEngine()->end();
}
Пример #14
0
int lrucache_clear(LRUCACHE* lrucache)
{
    int err;
    
    err = map_clear(lrucache->map);
    if (err) {
        return -1;
    }
    
    err = queue_clear(lrucache->queue);
    if (err) {
        return -2;
    }
    
    return 0;
}
Пример #15
0
/**
 * Assign map container.
 */
void map_assign(map_t* pmap_dest, const map_t* cpmap_src)
{
    assert(pmap_dest != NULL);
    assert(cpmap_src != NULL);
    assert(_pair_is_inited(&pmap_dest->_pair_temp));
    assert(_pair_is_inited(&cpmap_src->_pair_temp));
    assert(_map_same_pair_type_ex(&pmap_dest->_pair_temp, &cpmap_src->_pair_temp));

    /* clear */
    map_clear(pmap_dest);
    /* insert all element from src to dest */
    if(!map_empty(cpmap_src))
    {
        map_insert_range(pmap_dest, map_begin(cpmap_src), map_end(cpmap_src));
    }
}
Пример #16
0
/**
 * @brief Teleports the player to a new system.
 *
 * Does not change the position nor velocity of the player, which will probably be wrong in the new system.
 *
 * @usage player.teleport( system.get("Arcanis") ) -- Teleports the player to arcanis.
 *
 *    @luaparam sys System to teleport the player to.
 * @luafunc teleport( sys )
 */
static int playerL_teleport( lua_State *L )
{
   LuaSystem *sys;

   /* Get a system. */
   sys = luaL_checksystem(L,1);

   /* Go to the new system. */
   space_init( sys->s->name );

   /* Run hooks - order is important. */
   hooks_run( "jumpout" );
   hooks_run( "jumpin" );
   hooks_run( "enter" );

   /* Map gets deformed when jumping this way. */
   map_clear();

   return 0;
}
Пример #17
0
/////////////////////////////////////////////////////////////////
// checkUserInputAndPerformActions
//    scans the keyboard and checks whether the user has pressed
// any action key or not. When the user presses an action key, 
// the corresponding action is performed.
//
void checkUserInputAndPerformActions() {
   // Scan the keyboard for user keypresses
   cpct_scanKeyboard();

   // Perform checks only when the user has
   // pressed at least one key
   if(cpct_isAnyKeyPressed()) {
      // Get current (x,y) coordinates of the cursor 
      u8 x = cursor_getX();
      u8 y = cursor_getY();

      // Check if the key pressed is one of the valid keys and
      // if sanity conditions are met

      // CURSOR_UP or CURSOR_DOWN (Only one at a time)
      //   Perform required action, if the cursor is not at the
      // edge of the map already.
      if (cpct_isKeyPressed(Key_CursorUp) && y > 0)
         cursor_move(DIR_UP);
      else if (cpct_isKeyPressed(Key_CursorDown) && y < MAP_HEIGHT-1)
         cursor_move(DIR_DOWN);

      // CURSOR_LEFT or CURSOR_RIGHT (Only one at a time)
      //   Perform required action, if the cursor is not at the
      // edge of the map already.
      if (cpct_isKeyPressed(Key_CursorLeft) && x > 0)
         cursor_move(DIR_LEFT);
      else if (cpct_isKeyPressed(Key_CursorRight) && x < MAP_WIDTH-1)
         cursor_move(DIR_RIGHT);

      // SPACE (change tile) or ESCAPE (clear map)
      //    Perform one of these actions if corresponding key is pressed
      if (cpct_isKeyPressed(Key_Space)) 
         map_changeTile(x, y);
      else if (cpct_isKeyPressed(Key_Esc))
         map_clear();

      // Always redraw the cursor after any of the above actions
      cursor_draw();
   }
}
Пример #18
0
int main(int argc, char *argv[]) {
	const char *key = "404";
	const int values[3] = { 0, 1, 2 };

	plan_no_plan();

	Map *map = map_new();

	ok(map && map_empty(map), "Creation");
	ok(map_first(map, &key) == NULL && strcmp(key, "404") == 0, "First on empty map");
	ok(map_empty(map_prefix(map, "404")), "Empty prefix map");

	ok(!map_get(map, "404"), "Get non-existing key");
	ok(!map_contains(map, "404"), "Contains non-existing key");
	ok(!map_closest(map, "404") && errno == ENOENT, "Closest non-existing key");

	ok(!map_put(map, "a", NULL) && errno == EINVAL && map_empty(map) && !map_get(map, "a"), "Put NULL value");
	ok(map_put(map, "a", &values[0]) && !map_empty(map) && get(map, "a", &values[0]), "Put 1");
	ok(map_first(map, &key) == &values[0] && strcmp(key, "a") == 0, "First on map with 1 value");
	key = NULL;
	ok(map_first(map_prefix(map, "a"), &key) == &values[0] && strcmp(key, "a") == 0, "First on prefix map");
	ok(map_contains(map, "a"), "Contains existing key");
	ok(map_closest(map, "a") == &values[0], "Closest match existing key");
	ok(!map_put(map, "a", &values[1]) && errno == EEXIST && get(map, "a", &values[0]), "Put duplicate");
	ok(map_put(map, "cafebabe", &values[2]) && get(map, "cafebabe", &values[2]), "Put 2");
	ok(map_put(map, "cafe", &values[1]) && get(map, "cafe", &values[1]), "Put 3");
	key = NULL;
	ok(map_first(map_prefix(map, "cafe"), &key) == &values[1] && strcmp(key, "cafe") == 0, "First on prefix map with multiple suffixes");

	Map *copy = map_new();
	ok(map_copy(copy, map), "Copy");
	ok(!map_empty(copy), "Not empty after copying");
	map_iterate(copy, compare, map);
	map_iterate(map, compare, copy);

	int counter = 0;
	map_iterate(copy, once, &counter);
	ok(counter == 1, "Iterate stop condition");

	ok(!map_get(map, "ca") && !map_closest(map, "ca") && errno == 0, "Closest ambigious");

	int visited[] = { 0, 0, 0 };

	map_iterate(map, visit, &visited);
	ok(visited[0] == 1 && visited[1] == 1 && visited[2] == 1, "Iterate map");

	memset(visited, 0, sizeof visited);
	order_counter = 0;
	map_iterate(map, order, &visited);
	ok(visited[0] == 1 && visited[1] == 2 && visited[2] == 3, "Ordered iteration");

	memset(visited, 0, sizeof visited);
	map_iterate(map_prefix(map, "ca"), visit, &visited);
	ok(visited[0] == 0 && visited[1] == 1 && visited[2] == 1, "Iterate sub map");

	memset(visited, 0, sizeof visited);
	order_counter = 0;
	map_iterate(map_prefix(map, "ca"), order, &visited);
	ok(visited[0] == 0 && visited[1] == 1 && visited[2] == 2, "Ordered sub map iteration");

	ok(map_empty(map_prefix(map, "404")), "Empty map for non-existing prefix");

	ok(!map_delete(map, "404"), "Delete non-existing key");
	ok(map_delete(map, "cafe") == &values[1] && !map_get(map, "cafe"), "Delete existing key");
	ok(map_closest(map, "cafe") == &values[2], "Closest unambigious");
	ok(map_put(map, "cafe", &values[1]) && get(map, "cafe", &values[1]), "Put 3 again");

	map_clear(map);
	ok(map_empty(map), "Empty after clean");

	map_free(map);
	map_free(copy);

	return exit_status();
}
Пример #19
0
/**
 * @brief Teleports the player to a new system (only if not landed).
 *
 * Does not change the position nor velocity of the player.p, which will probably be wrong in the new system.
 *
 * @usage player.teleport( system.get("Arcanis") ) -- Teleports the player to arcanis.
 * @usage player.teleport( "Arcanis" ) -- Teleports the player to arcanis.
 *
 *    @luaparam sys System or name of a system to teleport the player to.
 * @luafunc teleport( sys )
 */
static int playerL_teleport( lua_State *L )
{
   LuaSystem *sys;
   const char *name;

   /* Must not be landed. */
   if (landed)
      NLUA_ERROR(L,"Can not teleport the player while landed!");
   if (comm_isOpen())
      NLUA_ERROR(L,"Can not teleport the player while the comm is open!");
   if (player_isBoarded())
      NLUA_ERROR(L,"Can not teleport the player while he is boarded!");

   /* Get a system. */
   if (lua_issystem(L,1)) {
      sys   = lua_tosystem(L,1);
      name  = system_getIndex(sys->id)->name;
   }
   else if (lua_isstring(L,1))
      name = lua_tostring(L,1);
   else
      NLUA_INVALID_PARAMETER(L);

   /* Check if system exists. */
   if (!system_exists( name )) {
      NLUA_ERROR( L, "System '%s' does not exist.", name );
      return 0;
   }

   /* Jump out hook is run first. */
   hooks_run( "jumpout" );

   /* Just in case remove hyperspace flags. */
   pilot_rmFlag( player.p, PILOT_HYPERSPACE );
   pilot_rmFlag( player.p, PILOT_HYP_BEGIN );
   pilot_rmFlag( player.p, PILOT_HYP_BRAKE );
   pilot_rmFlag( player.p, PILOT_HYP_PREP );

   /* Free graphics. */
   space_gfxUnload( cur_system );

   /* Go to the new system. */
   space_init( name );

   /* Map gets deformed when jumping this way. */
   map_clear();

   /* Add the escorts. */
   player_addEscorts();

   /* Run hooks - order is important. */
   hooks_run( "jumpin" );
   hooks_run( "enter" );
   events_trigger( EVENT_TRIGGER_ENTER );

   /* Reset targets when teleporting */
   player_targetPlanetSet( -1 );
   player_targetHyperspaceSet( -1 );
   gui_setNav();
   return 0;
}
Пример #20
0
/**
 * @brief Teleports the player to a new planet or system (only if not landed).
 *
 * If the destination is a system, the coordinates of the player will not change.
 * If the destination is a planet, the player will be placed over that planet.
 *
 * @usage player.teleport( system.get("Arcanis") ) -- Teleports the player to Arcanis.
 * @usage player.teleport( "Arcanis" ) -- Teleports the player to Arcanis.
 * @usage player.teleport( "Dvaer Prime" ) -- Teleports the player to Dvaer, and relocates him to Dvaer Prime.
 *
 *    @luaparam dest System or name of a system or planet or name of a planet to teleport the player to.
 * @luafunc teleport( dest )
 */
static int playerL_teleport( lua_State *L )
{
    Planet *pnt;
    StarSystem *sys;
    const char *name, *pntname;

    /* Must not be landed. */
    if (landed)
        NLUA_ERROR(L,"Can not teleport the player while landed!");
    if (comm_isOpen())
        NLUA_ERROR(L,"Can not teleport the player while the comm is open!");
    if (player_isBoarded())
        NLUA_ERROR(L,"Can not teleport the player while he is boarded!");

    pnt = NULL;

    /* Get a system. */
    if (lua_issystem(L,1)) {
        sys   = luaL_validsystem(L,1);
        name  = system_getIndex(sys->id)->name;
    }
    /* Get a planet. */
    else if (lua_isplanet(L,1)) {
        pnt   = luaL_validplanet(L,1);
        name  = planet_getSystem( pnt->name );
        if (name == NULL) {
            NLUA_ERROR( L, "Planet '%s' does not belong to a system..", pnt->name );
            return 0;
        }
    }
    /* Get destination from string. */
    else if (lua_isstring(L,1)) {
        name = lua_tostring(L,1);
        if (!system_exists( name )) {
            if (!planet_exists( name )) {
                NLUA_ERROR( L, "'%s' is not a valid teleportation target.", name );
                return 0;
            }

            /* No system found, assume destination string is the name of a planet. */
            pntname = name;
            name = planet_getSystem( name );
            pnt  = planet_get( pntname );
            if (name == NULL) {
                NLUA_ERROR( L, "Planet '%s' does not belong to a system..", pntname );
                return 0;
            }
        }
    }
    else
        NLUA_INVALID_PARAMETER(L);

    /* Check if system exists. */
    if (!system_exists( name )) {
        NLUA_ERROR( L, "System '%s' does not exist.", name );
        return 0;
    }

    /* Jump out hook is run first. */
    hooks_run( "jumpout" );

    /* Just in case remove hyperspace flags. */
    pilot_rmFlag( player.p, PILOT_HYPERSPACE );
    pilot_rmFlag( player.p, PILOT_HYP_BEGIN );
    pilot_rmFlag( player.p, PILOT_HYP_BRAKE );
    pilot_rmFlag( player.p, PILOT_HYP_PREP );

    /* Free graphics. */
    space_gfxUnload( cur_system );

    /* Go to the new system. */
    space_init( name );

    /* Map gets deformed when jumping this way. */
    map_clear();

    /* Add the escorts. */
    player_addEscorts();

    /* Run hooks - order is important. */
    hooks_run( "jumpin" );
    hooks_run( "enter" );
    events_trigger( EVENT_TRIGGER_ENTER );
    missions_run( MIS_AVAIL_SPACE, -1, NULL, NULL );

    /* Reset targets when teleporting */
    player_targetPlanetSet( -1 );
    player_targetHyperspaceSet( -1 );
    gui_setNav();

    /* Move to planet. */
    if (pnt != NULL)
        vectcpy( &player.p->solid->pos, &pnt->pos );

    return 0;
}
Пример #21
0
static void proximity_send(ProxMapState* prox_map) {
    t2t_send_update_map(prox_map->lower_left.x, prox_map->lower_left.y,
        map_get_proximity());
    map_clear(map_get_proximity());
    prox_map->time_sent = hal_get_time();
}
Пример #22
0
Файл: map.c Проект: isfos/naev
/**
 * @brief Cleans up the map stuff.
 */
void map_cleanup (void)
{
    map_close();
    map_clear();
}
Пример #23
0
void proximity_reset(ProxMapState* prox_map, Sensors* sens) {
    desired_position(&prox_map->lower_left, sens);
    map_clear(map_get_proximity());
    prox_map->time_sent = hal_get_time();
}
Пример #24
0
void test_duplicates(unsigned int num)
{
    const struct map_config map_conf = {
        .size           = MAP_DEFAULT_SIZE,
        .lower_bound    = MAP_DEFAULT_LOWER_BOUND,
        .upper_bound    = MAP_DEFAULT_UPPER_BOUND,
        .static_size    = false,
        .key_compare    = &compare_int,
        .key_hash       = &hash_uint,
        .data_delete    = NULL,
    };
    struct map *m;
    struct random *random;
    unsigned int i, n, dups1, dups2;;
    int err;
    
    m = map_new(&map_conf);
    random = random_new();
    
    assert(m);
    assert(random);
    
    dups1 = 0;
    
    for(i = 0; i < num; ++i) {
        n = random_uint(random);
        
        if(map_contains(m, (void *)(long) n)) {
            dups1 += 1;
        } else {
            err = map_insert(m, (void *)(long) n, (void *)(long) n);
            if(err < 0) {
                fprintf(stderr, "Warning: "
                        "Map unable to insert %u in %uth iteration: %s\n",
                        n, i, strerror(-err));
            }
        }
    }
    
    random_delete(random);
    map_clear(m);
    
    srand(time(NULL));
    
    dups2 = 0;
    
    for(i = 0; i < num; ++i) {
        n = rand();
        
        if(map_contains(m, (void *)(long) n)) {
            dups2 += 1;
        } else {
            err = map_insert(m, (void *)(long) n, (void *)(long) n);
            if(err < 0) {
                fprintf(stderr, "Warning: "
                "Map unable to insert %u in %uth iteration: %s\n",
                n, i, strerror(-err));
            }
        }
    }
    
    map_delete(m);
    
    fprintf(stdout,
            "random: After %u iterations there are %u (%lf %%) duplicates\n"
            "rand(): After %u iterations there are %u (%lf %%) duplicates\n", 
            num, dups1, (double) dups1 / num, num, dups2, (double) dups2 / num);
}

void test_range(unsigned int num)
{
    struct random *rand;
    unsigned int i, n;
    
    rand = random_new();
    assert(rand);
    
    for(i = 0; i < num; ++i) {
        n = random_uint_range(rand, 0, 100);
        assert(n <= 100);
        
        n = random_uint_range(rand, 1000, 10000);
        assert(n >= 1000 && n <= 10000);
        
        n = random_uint_range(rand, 99999, 123456);
        assert(n >= 99999 && n <= 123456);
        
        n = random_uint_range(rand, (unsigned int) 1e6 + 1, (unsigned int) 1e8);
        assert(n >= (unsigned int) 1e6 + 1 && n <= (unsigned int) 1e8);
        
        n = random_uint_range(rand, 0, 0);
        assert(n == 0);
        
        n = random_uint_range(rand, 100, 100);
        assert(n == 100);
    }
    
    random_delete(rand);
}

int main(int argc, char *argv[])
{
    unsigned int num;
    
    if(argc == 2)
        num = atoi(argv[1]);
    else
        num = 0;
    
    test_randomness();
    
    if(num) {
        test_seeding(num);
        test_duplicates(num);
        test_range(num);
    }
    
    fprintf(stdout, "Tests finished\n");
    
    return EXIT_SUCCESS;
}
Пример #25
0
void map_destroy(hashmap_t* map)
{
	map_clear(map);
	vec_destroy(&map->active_buckets);
}
Пример #26
0
void osm_upload(appdata_t *appdata, osm_t *osm, project_t *project) {

  printf("starting upload\n");

  /* upload config and confirmation dialog */

  /* count nodes */
  osm_dirty_t dirty;
  memset(&dirty, 0, sizeof(dirty));

  const node_t *node = osm->node;
  while(node) {
    object_counter(OSM_BASE(node), &dirty.nodes);
    node = node->next;
  }
  printf("nodes:     new %2d, dirty %2d, deleted %2d\n",
	 dirty.nodes.added, dirty.nodes.dirty, dirty.nodes.deleted);

  /* count ways */
  const way_t *way = osm->way;
  while(way) {
    object_counter(OSM_BASE(way), &dirty.ways);
    way = way->next;
  }
  printf("ways:      new %2d, dirty %2d, deleted %2d\n",
	 dirty.ways.added, dirty.ways.dirty, dirty.ways.deleted);

  /* count relations */
  const relation_t *relation = osm->relation;
  while(relation) {
    object_counter(OSM_BASE(relation), &dirty.relations);
    relation = relation->next;
  }
  printf("relations: new %2d, dirty %2d, deleted %2d\n",
	 dirty.relations.added, dirty.relations.dirty, dirty.relations.deleted);


  GtkWidget *dialog =
    misc_dialog_new(MISC_DIALOG_MEDIUM, _("Upload to OSM"),
		    GTK_WINDOW(appdata->window),
		    GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
		    GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
		    NULL);

  GtkWidget *table = gtk_table_new(4, 5, TRUE);

  table_attach_label_c(table, _("Total"),          1, 2, 0, 1);
  table_attach_label_c(table, _("New"),            2, 3, 0, 1);
  table_attach_label_c(table, _("Modified"),       3, 4, 0, 1);
  table_attach_label_c(table, _("Deleted"),        4, 5, 0, 1);

  int row = 1;
  table_attach_label_l(table, _("Nodes:"),         0, 1, row, row + 1);
  table_insert_count(table, &dirty.nodes, row++);

  table_attach_label_l(table, _("Ways:"),          0, 1, row, row + 1);
  table_insert_count(table, &dirty.ways, row++);

  table_attach_label_l(table, _("Relations:"),     0, 1, row, row + 1);
  table_insert_count(table, &dirty.relations, row++);

  gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), table, FALSE, FALSE, 0);

  /* ------------------------------------------------------ */

  gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox),
		     gtk_hseparator_new(), FALSE, FALSE, 0);

  /* ------- add username and password entries ------------ */

  table = gtk_table_new(2, 2, FALSE);
  table_attach_label_l(table, _("Username:"******"Password:"******"Please add a comment"), -1);

  /* disable ok button until user edited the comment */
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog),
				    GTK_RESPONSE_ACCEPT, FALSE);

  g_signal_connect(G_OBJECT(buffer), "changed",
		   G_CALLBACK(callback_buffer_modified), dialog);

#ifndef FREMANTLE
  GtkWidget *view = gtk_text_view_new_with_buffer(buffer);
#else
  GtkWidget *view = hildon_text_view_new();
  hildon_text_view_set_buffer(HILDON_TEXT_VIEW(view), buffer);
#endif

  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(view), GTK_WRAP_WORD);
  gtk_text_view_set_editable(GTK_TEXT_VIEW(view), TRUE);
  gtk_text_view_set_left_margin(GTK_TEXT_VIEW(view), 2 );
  gtk_text_view_set_right_margin(GTK_TEXT_VIEW(view), 2 );

  g_object_set_data(G_OBJECT(view), "first_click", GINT_TO_POINTER(TRUE));
  g_signal_connect(G_OBJECT(view), "focus-in-event",
		   G_CALLBACK(cb_focus_in), buffer);


  gtk_container_add(GTK_CONTAINER(scrolled_win), view);

  gtk_box_pack_start_defaults(GTK_BOX(GTK_DIALOG(dialog)->vbox),
  			      scrolled_win);
  gtk_widget_show_all(dialog);

  if(GTK_RESPONSE_ACCEPT != gtk_dialog_run(GTK_DIALOG(dialog))) {
    printf("upload cancelled\n");
    gtk_widget_destroy(dialog);
    return;
  }

  printf("clicked ok\n");

  /* retrieve username and password */
  g_free(appdata->settings->username);
  appdata->settings->username =
    g_strdup(gtk_entry_get_text(GTK_ENTRY(uentry)));

  g_free(appdata->settings->password);
  appdata->settings->password =
    g_strdup(gtk_entry_get_text(GTK_ENTRY(pentry)));

  /* osm upload itself also has a gui */
  osm_upload_context_t *context = g_new0(osm_upload_context_t, 1);
  context->appdata = appdata;
  context->osm = osm;
  context->project = project;

  /* add proxy settings if required */
  if(appdata->settings)
    context->proxy = appdata->settings->proxy;

  /* fetch comment from dialog */
  GtkTextIter start, end;
  gtk_text_buffer_get_start_iter(buffer, &start);
  gtk_text_buffer_get_end_iter(buffer, &end);
  char *text = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
  context->comment = g_strdup(text);

  gtk_widget_destroy(dialog);
  project_save(GTK_WIDGET(appdata->window), project);

  context->dialog =
    misc_dialog_new(MISC_DIALOG_LARGE,_("Uploading"),
	  GTK_WINDOW(appdata->window),
	  GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL);

  gtk_dialog_set_response_sensitive(GTK_DIALOG(context->dialog),
				    GTK_RESPONSE_CLOSE, FALSE);

  /* ------- main ui element is this text view --------------- */

  GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
  				 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

  context->log.buffer = gtk_text_buffer_new(NULL);

  context->log.view = gtk_text_view_new_with_buffer(context->log.buffer);
  gtk_text_view_set_editable(GTK_TEXT_VIEW(context->log.view), FALSE);
  gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(context->log.view), FALSE);
  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(context->log.view), GTK_WRAP_WORD);

  gtk_container_add(GTK_CONTAINER(scrolled_window), context->log.view);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled_window),
				      GTK_SHADOW_IN);

  gtk_box_pack_start_defaults(GTK_BOX(GTK_DIALOG(context->dialog)->vbox),
			       scrolled_window);
  gtk_widget_show_all(context->dialog);

  /* server url should not end with a slash */
  if(project->rserver && project->rserver[strlen(project->rserver)-1] == '/') {
    printf("removing trailing slash\n");
    project->rserver[strlen(project->rserver)-1] = 0;
  }

  appendf(&context->log, NULL, _("Log generated by %s v%s using API 0.6\n"),
	  PACKAGE, VERSION);
  appendf(&context->log, NULL, _("User comment: %s\n"), context->comment);

   /* check if server name contains string "0.5" and adjust it */
  if(project->rserver && strstr(project->rserver, "0.5") != NULL) {
    strstr(project->rserver, "0.5")[2] = '6';

    appendf(&context->log, NULL, _("Adjusting server name to v0.6\n"));
  }

  appendf(&context->log, NULL, _("Uploading to %s\n"), project->server);

  /* create a new changeset */
  gchar *cred;
  if(osm_create_changeset(context, &cred)) {
    /* check for dirty entries */
    appendf(&context->log, NULL, _("Uploading nodes:\n"));
    osm_upload_nodes(context, cred);
    appendf(&context->log, NULL, _("Uploading ways:\n"));
    osm_upload_ways(context, cred);
    appendf(&context->log, NULL, _("Uploading relations:\n"));
    osm_upload_relations(context, cred);
    appendf(&context->log, NULL, _("Deleting relations:\n"));
    osm_delete_relations(context, cred);
    appendf(&context->log, NULL, _("Deleting ways:\n"));
    osm_delete_ways(context, cred);
    appendf(&context->log, NULL, _("Deleting nodes:\n"));
    osm_delete_nodes(context, cred);

    /* close changeset */
    osm_close_changeset(context, cred);
  }

  appendf(&context->log, NULL, _("Upload done.\n"));

  gboolean reload_map = FALSE;
  if(project->data_dirty) {
    appendf(&context->log, NULL, _("Server data has been modified.\n"));
    appendf(&context->log, NULL, _("Downloading updated osm data ...\n"));

    if(osm_download(context->dialog, appdata->settings, project)) {
      appendf(&context->log, NULL, _("Download successful!\n"));
      appendf(&context->log, NULL, _("The map will be reloaded.\n"));
      project->data_dirty = FALSE;
      reload_map = TRUE;
    } else
      appendf(&context->log, NULL, _("Download failed!\n"));

    project_save(context->dialog, project);

    if(reload_map) {
      /* this kind of rather brute force reload is useful as the moment */
      /* after the upload is a nice moment to bring everything in sync again. */
      /* we basically restart the entire map with fresh data from the server */
      /* and the diff will hopefully be empty (if the upload was successful) */

      appendf(&context->log, NULL, _("Reloading map ...\n"));

      if(!diff_is_clean(appdata->osm, FALSE)) {
	appendf(&context->log, COLOR_ERR, _("*** DIFF IS NOT CLEAN ***\n"));
	appendf(&context->log, COLOR_ERR, _("Something went wrong during upload,\n"));
	appendf(&context->log, COLOR_ERR, _("proceed with care!\n"));
      }

      /* redraw the entire map by destroying all map items and redrawing them */
      appendf(&context->log, NULL, _("Cleaning up ...\n"));
      diff_save(appdata->project, appdata->osm);
      map_clear(appdata, MAP_LAYER_OBJECTS_ONLY);
      osm_free(appdata->osm);

      appendf(&context->log, NULL, _("Loading OSM ...\n"));
      appdata->osm = osm_parse(appdata->project->path, appdata->project->osm, &appdata->icon);
      appendf(&context->log, NULL, _("Applying diff ...\n"));
      diff_restore(appdata, appdata->project, appdata->osm);
      appendf(&context->log, NULL, _("Painting ...\n"));
      map_paint(appdata);
      appendf(&context->log, NULL, _("Done!\n"));
    }
  }

  /* tell the user that he can stop waiting ... */
  appendf(&context->log, NULL, _("Process finished.\n"));

  gtk_dialog_set_response_sensitive(GTK_DIALOG(context->dialog),
				    GTK_RESPONSE_CLOSE, TRUE);

  gtk_dialog_run(GTK_DIALOG(context->dialog));
  gtk_widget_destroy(context->dialog);

  g_free(context->comment);
  g_free(context);
}
Пример #27
0
/******************************************************************************
    main
 *****************************************************************************/
int 
main( int pargc, char* pargv[] ) 
{
    val_t val;
    map_init();

    if ( pargc == 1) {
        char *cmd;
        char* cmds = cmd;
        int cmdlen = 0;
        cmd[0] = 0;

        printf("Use Control-C to quit.\n");

        for( ;; ) {
top:
            // print command line.
            printf( "\r> %s", cmd );

            cmdlen = strlen(cmd);
            
            for( ;; ) {
                char c = getchar();
                if ( c == '\b' ) {
                    if ( cmdlen > 0 ) {
                        cmd[--cmdlen] = 0;
                        printf( "\r> %s \b", cmd );
                    }
                } else if ( c == '\r' ) {
                    putc('\n', stdout);
                    break;
                } else if ( c == 3 ) {
                    printf("QUIT\n");
                    exit(0);
                } else if ( cmdlen < sizeof(cmd)-1 ) {
                    putc(c, stdout);
                    //printf("%d\n", c);
                    cmd[cmdlen++] = c;
                    cmd[cmdlen] = 0;
                }
            }
            
            reset( 1, &cmds );
            
            /* parse the expression. */
            if ( parse( &val ) ) {
                /* print the value. */
                print_val( &val );
            } else {
                printf("Error.\n");
            }
        }
    }

    reset( pargc - 1, pargv + 1 );
    /* parse the expression. */
    parse_expr( &val );

    /* print the value. */
    print_val( &val );

    map_clear();

    return 0;
}
Пример #28
0
static void parse_reset(void)
{
    map_clear(s->sym_table);
    named_buffer_clear(s->named_buffer);
}