Example #1
0
def collectdata():
    global currentcategories
    try:
        db = DB()
        initdriver()
        city = City()
        while city.nextcity(db, driver) is not None:
            prod_namelist = set()
            for suburl, categories in city.category_pages.items():
                driver.get(baseurl + suburl)
                currentcategories = categories
                scrolltoend()
                products = driver.find_elements(
                    By.XPATH, "//li[starts-with(@id,'product_')]")
                print(len(products))
                for product in products:
                    if(product.get_attribute("class") == "featured-product" or "display:none" in product.get_attribute("style") or len(product.text) < 5):
                        continue
                    try:
                        details = parseproduct(product)
                        if(details['prod_name'] not in prod_namelist):
                            prod_namelist.add(details['prod_name'])
                            db.insertproduct(details, currentcategories)
                    except Exception as e:
                        print("---------------------------------------")
                        print(e)
                        print("---------------------------------------")
                        continue
                time.sleep(10)
    finally:
        driver.close()
        db.conn.close()
def test_builder():
    toulouse = City('Toulouse', 'fr', 'C', 35)
    assert toulouse.name == 'Toulouse'
    assert toulouse.country == 'fr'
    empty_city = City('', '', '', '')
    assert empty_city.name == ''
    assert empty_city.country == ''
Example #3
0
    def __init__(self):
        spi = busio.SPI(clock=board.SCK_1,
                        MISO=board.MISO_1,
                        MOSI=board.MOSI_1)  #ADCs use second SPI port of RPi
        cs = digitalio.DigitalInOut(board.D16)
        mcp = MCP.MCP3008(spi, cs)
        self.pi = pigpio.pi()

        self.NUM_NEOPIXELS = 118
        self.pixels = neopixel.NeoPixel(board.D12,
                                        self.NUM_NEOPIXELS,
                                        auto_write=False)

        self.reservoir = Reservoir(self.pixels)
        self.windmills = Windmills(self.pi, mcp)
        self.solarPanels = SolarPanels(mcp)
        self.city = City(self.pixels)
        self.fuelCell = FuelCell(self.pixels, self.pi)
        self.distributionMiddle = DistributionLine(self.pixels, 101, 4)
        self.distributionRight = DistributionLine(self.pixels, 105, 5, True)
        self.transmissionLine = TransmissionLines(self.pixels)
        self.wattownSign = WattownSign(self.pixels)
        self.substation = Substation(self.pixels)

        self.stopEvent = threading.Event()
        self.stopEvent.clear()

        super().__init__()
Example #4
0
def collectdata():
    global currentcategories
    try:
        db = DB()
        initdriver()
        city = City()
        while city.nextcity(db, driver) is not None:
            prod_namelist = set()
            for suburl, categories in city.category_pages.items():
                driver.get(baseurl + suburl)
                currentcategories = categories
                scrolltoend()
                products = driver.find_elements(
                    By.XPATH, "//li[starts-with(@id,'product_')]")
                print(len(products))
                for product in products:
                    if (product.get_attribute("class") == "featured-product"
                            or "display:none" in product.get_attribute("style")
                            or len(product.text) < 5):
                        continue
                    try:
                        details = parseproduct(product)
                        if (details['prod_name'] not in prod_namelist):
                            prod_namelist.add(details['prod_name'])
                            db.insertproduct(details, currentcategories)
                    except Exception as e:
                        print("---------------------------------------")
                        print(e)
                        print("---------------------------------------")
                        continue
                time.sleep(10)
    finally:
        driver.close()
        db.conn.close()
Example #5
0
def astar(departure, destination, heuristic, nameHeuristic):
	cityStart = cityDic[departure]
	cityEnd = cityDic[destination]
	
	result = str(nameHeuristic) + "\n------------------------\n"
	frontiere = []
	history = []
	
	frontiere.append(cityStart)
	
	while len(frontiere) > 0:
		result += "front : " + str(frontiere) + "\n"
		city = frontiere.pop(0)
		history.append(city.name)
		result += "hist : " + str(history) + "\n"
		
		if city.name == cityEnd.name:
			result += "\nNombre de ville visiter: " + str(len(history))+ "\ndistance parcouru : " + str(city.d) + " km\n" +"\nChemin :\n" + city.parcours() + "\n"
			return result

		nextCities = city.getConnection()
		
		for c in nextCities:
			newCity = City(c.name, c.x, c.y, city)
			newCity.d = city.d + int(cityConnection[city.name][newCity.name])
			
			newCity.h += heuristic(city, newCity)
			newCity.listConnection = cityDic[c.name].listConnection
			if (newCity not in frontiere) and (c.name not in history):
				frontiere.append(newCity)
				
		frontiere.sort()
		
	result += str(nameHeuristic) + "\n------------------------\nNo solution"
	return result
Example #6
0
def test_varsovie():
    city_name, station_id, station_name, lang = getCityFromString("Varsovie")
    assert (city_name == "Varsovie" and lang == "fr" and station_id == "209")
    city = City(city_name, station_id, station_name, lang)
    img = city.defaultGraph()
    with open("tests/varsovie.png", "wb") as f:
        f.write(img.read())
        f.close()
Example #7
0
def test_koeln():
    city_name, station_id, station_name, lang = getCityFromString("Köln")
    assert (city_name == "Köln" and lang == "de" and station_id == "4298")
    city = City(city_name, station_id, station_name, lang)
    img = city.defaultGraph()
    with open("tests/cologne.png", "wb") as f:
        f.write(img.read())
        f.close()
Example #8
0
def test_berlin():
    city_name, station_id, station_name, lang = getCityFromString("Berlin")
    assert (city_name == "Berlin" and lang == "de" and station_id == "4563")
    city = City(city_name, station_id, station_name, lang)
    img = city.defaultGraph()
    with open("tests/berlin.png", "wb") as f:
        f.write(img.read())
        f.close()
Example #9
0
def test_zarago():
    city_name, station_id, station_name, lang = getCityFromString(
        "Zaragoza please")
    assert (city_name == "Zaragoza" and lang == "en" and station_id == "238")
    city = City(city_name, station_id, station_name, lang)
    img = city.defaultGraph()
    with open("tests/zaragoza.png", "wb") as f:
        f.write(img.read())
        f.close()
Example #10
0
    def __init__(self):

        # ゲームの設定
        self.name = "03_example"
        self.state = State.START
        self.header = 32 #[pix]
        pyxel.init(96, 96, caption=self.name, scale=4, fps=15, 
                   palette=[0x000000, 0x1D2B53, 0x7E2553, 0x008751, 0xAB5236, 0x5F574F, 0xC2C3C7, 0xFFF1E8, 0xFF004D, 0xFFA300, 0xFFEC27, 0x00E436, 0x29ADFF, 0x83769C, 0xFF77A8, 0xFFCCAA])
    

        # 
        self.waiting_count = 7 # [frames]
        self.count = 0 # 画面遷移用カウンタ
        self.num_got_items = 0
        self.max_items = 1e10 # これだけ獲得したら次の画面へ
        self.total_score = 0 # 運んだ量
        
        # 地図の初期化
        self.map = City(pyxel.width, pyxel.height-self.header)
        self.num_col_rooms = 3
        self.num_row_rooms = 3
        self.corrider_width = 1
        self.map.create_map_dungeon(num_col_rooms=self.num_col_rooms, 
                                    num_row_rooms=self.num_row_rooms,
                                    corrider_width=self.corrider_width,
                                    max_room_size_ratio=0.7,
                                    min_room_size_ratio=0.2
                                    )
        self.map.set_start()
        
        # 自キャラの初期化
        self.num_vehicles = 4
        self.cars = []
        start_points = self.map.get_free_space(num=self.num_vehicles)
        for idx, xy in enumerate(start_points):
            x = xy[1]
            y = xy[0]
            v = Vehicle(x, y, 11)
            self.cars.append(v)
            self.map.occupancuy[y, x] = True
        

        for car in self.cars:        
            print(self.map.dumpings.items())
            if car.loaded:
                # print(self.map.dumpings.items())
                car.dest = random.choice(list(self.map.dumpings.items())) # (idx, (y, x)) # キャラの目的地
                # print("dest:===>")
                # print(car.dest)
            else:
                car.dest = random.choice(list(self.map.loadings.items())) # (idx, (y, x)) # キャラの目的地
                # print("dest:===>")
                # print(car.dest)

        # 実行        
        pyxel.run(self.update, self.draw)
Example #11
0
 def __init__(self):
     self.player = player.Player("Player 1", 20)
     self.city = City(
         self.player,
         World(self.player, [
             World_Tile(enemy.Simple_Enemy(), False),
             World_Tile(enemy.Medium_Enemy(), False),
             World_Tile(enemy.Hard_Enemy(), False),
             World_Tile(enemy.Endboss(), True)
         ]))
Example #12
0
    def test_set_cube_colours(self):
        saved = City.cube_colours

        City.cube_colours = []
        mocked_settings = {'Colours': {'colours': 'Red,Blue,Yellow,Black'}}
        City.set_cube_colours(mocked_settings)
        self.assertIn('Yellow', City.cube_colours)
        self.assertIn('Red', City.cube_colours)

        City.cube_colours = saved
Example #13
0
def test_plama():
    city_name, station_id, station_name, lang = getCityFromString(
        "Palma de mallorca bitte")
    assert (city_name == "Palma de Mallorca" and lang == "de"
            and station_id == "3918")
    city = City(city_name, station_id, station_name, lang)
    img = city.defaultGraph()
    with open("tests/parlma.png", "wb") as f:
        f.write(img.read())
        f.close()
Example #14
0
 def load_city(self, filename):
     parser = ConfigParser.ConfigParser()
     parser.read(filename)
     city = City()
     
     for section in parser.sections():
         if parser.get(section, 'type') == 'npc':
             city.add_npc(self._create_npc(section, parser))
         elif parser.get(section, 'type') == 'stock':
             city.add_stock_market(self._create_stock(section, parser))
     return city
Example #15
0
def generateCity(event):
    removeAllChildren(master)

    citySize = Size(WINDOW_WIDTH, WINDOW_HEIGHT)
    city = City(citySize)

    cityCanvas = Canvas(master, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, highlightthickness=0)
    cityCanvas.pack()

    cityCanvas.create_rectangle(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, fill="black")
    city.draw(cityCanvas)
def test_is_summer():
    toulouse = City('Toulouse', 'fr', 'C', 35)
    assert Weather(toulouse, "2028-06-12T00:08:29Z").is_summer()
    assert Weather(toulouse, "2028-08-12T00:08:29Z").is_summer()
    assert Weather(toulouse, "2028-09-12T00:08:29Z").is_summer()
    assert not Weather(toulouse, "2028-11-12T00:08:29Z").is_summer()
    sydney = City('Sydney', 'au', 'B', 12)
    assert Weather(sydney, "2028-11-12T00:08:29Z").is_summer()
    assert Weather(sydney, "2028-12-12T00:08:29Z").is_summer()
    assert Weather(sydney, "2028-02-12T00:08:29Z").is_summer()
    assert not Weather(sydney, "2028-08-12T00:08:29Z").is_summer()
Example #17
0
def dump_shops():
    try:
        for cityName in DUMP_CITY_NAMES:
            city = City(cityName)
            inject_cookie(city.headers)
            inject_cookie(city.map_headers)
            city.get()
            results = city.search(DUMP_KEYWORD)
            add_results_to_output(results, DUMP_FILE_SHOPS)
    finally:
        logger.info(f'Data dumped to {DUMP_FILE_SHOPS}')
Example #18
0
    def setup_game(self, settings_location=None):
        self.settings = config.get_settings(settings_location)
        City.set_cube_colours(self.settings)
        self.get_infection_rate()
        self.get_new_cities()
        self.get_new_decks()
        self.get_new_diseases()
        self.set_starting_epidemics()

        logging.info('Game ready to begin.')
        logging.info(f'Difficulty level: {self.starting_epidemics} Epidemics.')
Example #19
0
def getCityDetails(url):
    try:
        result = getRequest(url)
        if(result['response']['numFound'] > 0):
            city = result['response']['docs']
            if(city != None):
                src = City(city[0]['ID'], city[0]['Name'])
                return src
            print("Location not found")
            return City(0, "Location not found")
    except Exception as e:
        print(e)
 def __init__(self, **kwargs):
     self.firm_name = kwargs['name']
     self.cash = kwargs['cash']
     self.debt = kwargs['debt']
     self.cannons = kwargs['cannons']
     self.bank = 0
     self.maxshiphold = kwargs['shiphold']
     self.currentshiphold = 0
     Product.create_products()
     City.create_cities()
     self.current_city = City.cities[0]
     self.current_date = datetime.datetime(1820, 1, 1)
Example #21
0
 def __init__(self):
     self.env = City(stepsize=0.01, dimensions=DIMENSIONS)
     self.state_size = 1 + len(self.env.intersections) * 4 * 3
     self.action_size = len(self.env.intersections) * 4
     self.memory = deque(maxlen=2000)
     self.gamma = 0.95  # discount rate
     self.epsilon = 1.0  # initial exploration rate
     self.epsilon_min = 0.01
     self.epsilon_decay = (self.epsilon_min / self.epsilon)**(1.25 /
                                                              NR_EPISODES)
     self.timestamp = time.strftime('%Y%m%d-%H%M', time.localtime())
     self.model = self._build_model()
Example #22
0
 def __init__(self, cityName, area=None):
     self.cityName = cityName
     self.area = area
     self.city = City(cityName,
                      searchDB=Database(MongoDB),
                      commentsDB=Database(MongoDB))
     self.city.get()
     self.category_list = []
     self.coa_category = []
     self.fin_category = []
     self.process_category(self.city.category, self.category_list)
     self.coarsness_category(self.category_list)
     self.fine_grained_category(self.category_list)
Example #23
0
def set_data_from_arr(data_arr):
    provinces_dict = {}
    cities_arr = []
    for city_dict in data_arr:
        city = City()
        city.set_city_from_dict(city_dict)
        city.get_total_scene_points()
        city.get_total_type_points()
        print(city.city_name)

        cities_arr.append(city)

        if city.city_province not in provinces_dict.keys():
            province = Province()
            province.province_name = city.city_province
        else:
            province = provinces_dict[city.city_province]

        province.add_city(city)

        if (city.city_name == '路凼填海区'):
            print('1', city.city_device_types_distribution)

        provinces_dict.update({province.province_name: province})
        if (city.city_name == '路凼填海区'):
            print('2', city.city_device_types_distribution)

    for city in cities_arr:
        if (city.city_name == '路凼填海区'):
            print('3', city.city_device_types_distribution)

    return cities_arr, provinces_dict
Example #24
0
    def get_steps_by_profile(self, json_profile):
        """
		accepts a json string of a profile and returns a dict containing related steps in order of time_frame
		:param json_profile: json string
		:return: dict {steps: [<step>...]}
		"""
        profile = Profile()
        profile.from_dict(json_profile)
        city = City(profile.new_residence)
        city.load()
        timeline = city.get_timeline_from_profile(profile)

        print json.dumps(timeline.to_dict())

        return timeline.to_dict()
Example #25
0
    def extract_city_data(self):
        dest = State.file_prefix + 'Aggregate'
        dir = Dir(dest)
        if dir.exists() is False:
            dir.create_if_needed()

        f = open(dest + '/aggr.csv', 'ab')
        writer = csv.writer(f, delimiter=',')
        for alpha in self._alpha:
            data_path = State.file_prefix + self._abbrv + '/City'
            for root, dirs, files in os.walk(data_path):
                for file in files:
                    this_city = City(self._abbrv, self._state, file)
                    this_city.extract_and_publish(writer)
        f.close()
Example #26
0
    def extract_city_data(self):
        dest = State.file_prefix + "Aggregate"
        dir = Dir(dest)
        if dir.exists() is False:
            dir.create_if_needed()

        f = open(dest + "/aggr.csv", "ab")
        writer = csv.writer(f, delimiter=",")
        for alpha in self._alpha:
            data_path = State.file_prefix + self._abbrv + "/City"
            for root, dirs, files in os.walk(data_path):
                for file in files:
                    this_city = City(self._abbrv, self._state, file)
                    this_city.extract_and_publish(writer)
        f.close()
Example #27
0
    def __init__(self):

        # ゲームの設定
        self.name = "05_example"
        pyxel.init(256, 256, caption=self.name, scale=2, fps=15)
        pyxel.load("my_resource.pyxres")

        scale = int(256/16)

        self.map = City(16, 16) # int(pyxel.width), int(pyxel.height/8))
        self.map.data = np.ones((self.map.h, self.map.w), dtype=np.int)
        self.map.data[2:-2, 2:-2] = 0
        self.map.data[6:-6, 6:-6] = 1
        self.map.data[:, 4] = 0
        self.map.data[5, :] = 0
        
        


        self.real_size_map = copy.deepcopy(self.map.data )
        
        # 自キャラの初期化
        x = int(np.random.rand() * self.map.w)
        y = int(np.random.rand() * self.map.h)
        while self.map.data[y, x] != 0:
            x = int(np.random.rand() * self.map.w)
            y = int(np.random.rand() * self.map.h)
        c = 11
        self.ego = Vehicle(x, y, c)
        


        # 実行        
        pyxel.run(self.update, self.draw)
Example #28
0
def main():
    cities = City.load_cities('./data/data50.txt')
    graph = Graph(cities)
    init_sol = graph.nearestNeighbourSolution()
    history = SimulatedAnnealing(graph, init_sol, 0.9998, 10, 0.0000001,
                                 1000000).anneal()
    DynamicPlot().show(cities, history, graph)
Example #29
0
class Game:
    """The Game Class"""
    def __init__(self):
        self.player = player.Player("Player 1", 20)
        self.city = City(
            self.player,
            World(self.player, [
                World_Tile(enemy.Simple_Enemy(), False),
                World_Tile(enemy.Medium_Enemy(), False),
                World_Tile(enemy.Hard_Enemy(), False),
                World_Tile(enemy.Endboss(), True)
            ]))

    def print_start(self):
        print("#####Welcome to the Game#####")

    def print_menu(self):
        print(
            "Your Turn! Choose what you want to do!\n[1]To fight in the Arena!\n[2]To enter the Shop\n[3]To show your Inventory\n[X]To quit the Game!"
        )

    def run(self):
        self.print_start()
        game_on = True
        while game_on:
            game_on = self.city.enter_city()
Example #30
0
    def test4_resolve(self):
        r = redis.Redis(self.redisHost, self.redisPort, self.redisDB)
        #resolve by coords

        loc = City.getByLatLon(34.05223, -118.24368, r)

        self.assertTrue(loc is not None)
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')

        #resolve by ip
        ip = '4.3.68.1'

        loc = IPRange.getCity(ip, r)

        self.assertTrue(loc is not None)
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')

        #resolve zip by lat,lon
        loc = ZIPCode.getByLatLon(34.0452, -118.284, r)

        self.assertTrue(loc is not None)
        self.assertTrue(loc.name == '90006')
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')

        #resolve zip bu ip
        loc = IPRange.getZIP(ip, r)
        self.assertTrue(loc is not None)
        self.assertTrue(loc.name == '90001')
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')
def main():
    cities = City.load_cities('./data/data30.txt')
    graph = Graph(cities)
    history, cost = ACO(20, 200, 10, [1.0, 3.0], [4.0, 2.0],
                        [0.4, 0.8]).solve(graph)
    print(cost)
    DynamicPlot().show(cities, history)
Example #32
0
 def __init__(self):
     self.state = State()
     self.city = City()
     self.ninja = Ninja(self.city)
     self.badguys = self.get_badguys()
     self.hide_sword()
     self.hide_healths()
Example #33
0
    def buildCities(self, cityCount, maxNeighbourCount):
        # Build the cities
        for cityNumber in range(0, cityCount):
            point = Point(self.dimension)

            # Ensure that the point is distinct from existing cities
            while self.pointOccupied(point):
                point = Point(self.dimension)

            name = string.ascii_uppercase[cityNumber]
            city = City(point, name)
            self.cities.append(city)

        # Connect cities
        for city in self.cities:
            city.addNeighbours(self.cities, maxNeighbourCount)
Example #34
0
def main(argv):

    city = City.read_file(argv[0], constants.WIDTH, constants.HEIGHT)

    carryOn = True
    pygame.init()
    size = (constants.WIDTH, constants.HEIGHT)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Traffic Simulator")
    while carryOn:
        screen.fill(constants.BLACK)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                carryOn = False
            if event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_LEFT \
                    or event.key == pygame.K_DOWN) \
                    and constants.VELOCITY - 0.01 > 0:
                    constants.VELOCITY -= 0.01
                if (event.key == pygame.K_RIGHT \
                    or event.key == pygame.K_UP) \
                    and constants.VELOCITY + 0.01 < 4:
                    constants.VELOCITY += 0.01
        city.display(screen)
        pygame.display.update()
    pygame.quit()
Example #35
0
    def test4_resolve(self):
        r = redis.Redis(self.redisHost, self.redisPort, self.redisDB)
        #resolve by coords
        
        loc = City.getByLatLon(34.05223, -118.24368, r)
        
        self.assertTrue(loc is not None)
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')
        
        #resolve by ip
        ip = '4.3.68.1'

        loc = IPRange.getCity(ip, r)
        
        self.assertTrue(loc is not None)
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')

        #resolve zip by lat,lon
        loc = ZIPCode.getByLatLon(34.0452, -118.284, r)
        
        self.assertTrue(loc is not None)
        self.assertTrue(loc.name == '90006')
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')

        #resolve zip bu ip
        loc = IPRange.getZIP(ip, r)
        self.assertTrue(loc is not None)
        self.assertTrue(loc.name == '90001')
        self.assertTrue(loc.country == 'United States')
        self.assertTrue(loc.state == 'CA' or loc.state == 'California')
Example #36
0
def gmaps_json():
    city_query = request.args.get('city')
    city = City.lookup(city_query)

    if city is None:
        return jsonify({'gmaps-json': 'none'})
    else:
        return jsonify({'gmaps-json': city.to_json()})
def getCity():

	city = City()
	city.boundingBox = (43.7731, 11.26605, 43.77551, 11.26937)
	city.effectiveBoundingBox = (43.7716004, 11.2615376, 43.7777961, 11.2699985)
	city.nodes_d = {1050026629: ((43.7765123, 11.2685373), {'changeset': '6710449', 'uid': '192299', 'timestamp': '2010-12-19T20:51:14Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 253248006: ((43.7747826, 11.2646078), {'changeset': '365110', 'uid': '1700', 'timestamp': '2008-03-21T20:31:24Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 249264780: ((43.7725774, 11.2651493), {'changeset': '260207', 'uid': '4987', 'timestamp': '2008-03-03T01:55:20Z', 'visible': 'true', 'version': '2', 'user': '******'}, {'created_by': 'JOSM'}), 249264782: ((43.7739103, 11.2663056), {'changeset': '527179', 'uid': '17383', 'timestamp': '2008-05-26T10:12:34Z', 'visible': 'true', 'version': '3', 'user': '******'}, {}), 269532440: ((43.7762605, 11.2658931), {'changeset': '121845', 'uid': '17383', 'timestamp': '2008-06-10T15:53:29Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 299853208: ((43.7747117, 11.2689793), {'changeset': '701860', 'uid': '49848', 'timestamp': '2008-09-26T00:18:50Z', 'visible': 'true', 'version': '1', 'user': '******'}, {'created_by': 'Merkaartor 0.11'}), 299853210: ((43.7733405, 11.2677777), {'changeset': '701860', 'uid': '49848', 'timestamp': '2008-09-26T00:18:50Z', 'visible': 'true', 'version': '1', 'user': '******'}, {'created_by': 'Merkaartor 0.11'}), 299853211: ((43.773937, 11.2664473), {'changeset': '701860', 'uid': '49848', 'timestamp': '2008-09-26T00:18:50Z', 'visible': 'true', 'version': '1', 'user': '******'}, {'created_by': 'Merkaartor 0.11'}), 1050026396: ((43.775351, 11.2696809), {'changeset': '6710449', 'uid': '192299', 'timestamp': '2010-12-19T20:51:10Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 266938010: ((43.7747284, 11.2691552), {'changeset': '527179', 'uid': '17383', 'timestamp': '2008-05-26T10:03:00Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 300435931: ((43.7752982, 11.2676838), {'changeset': '707474', 'uid': '49848', 'timestamp': '2008-09-27T21:50:10Z', 'visible': 'true', 'version': '1', 'user': '******'}, {'created_by': 'Merkaartor 0.11'}), 939929809: ((43.7752826, 11.2681805), {'changeset': '5974989', 'uid': '17382', 'timestamp': '2010-10-07T04:38:44Z', 'visible': 'true', 'version': '4', 'user': '******'}, {'website': 'www.regency-hotel.com', 'name': 'Regency', 'phone': '+39055245247', 'stars': '5', 'tourism': 'hotel', 'email': '*****@*****.**'}), 267396306: ((43.7727899, 11.2687494), {'changeset': '551100', 'uid': '17383', 'timestamp': '2008-05-30T08:59:40Z', 'visible': 'true', 'version': '2', 'user': '******'}, {}), 82591700: ((43.7743323, 11.2699985), {'changeset': '676144', 'uid': '49848', 'timestamp': '2008-12-30T19:05:53Z', 'visible': 'true', 'version': '4', 'user': '******'}, {'created_by': 'Merkaartor 0.12'}), 302963542: ((43.7754543, 11.2697681), {'changeset': '5526187', 'uid': '181166', 'timestamp': '2010-08-18T12:23:32Z', 'visible': 'true', 'version': '3', 'user': '******'}, {}), 82591707: ((43.7777961, 11.2626578), {'changeset': '527179', 'uid': '17383', 'timestamp': '2008-05-26T10:03:00Z', 'visible': 'true', 'version': '4', 'user': '******'}, {}), 267396578: ((43.7765961, 11.2686077), {'changeset': '6710449', 'uid': '192299', 'timestamp': '2010-12-19T20:51:19Z', 'visible': 'true', 'version': '8', 'user': '******'}, {'source': 'survey', 'highway': 'traffic_signals'}), 266938723: ((43.7763241, 11.2615376), {'changeset': '5531271', 'uid': '181166', 'timestamp': '2010-08-18T22:17:05Z', 'visible': 'true', 'version': '2', 'user': '******'}, {}), 266938724: ((43.7732348, 11.2678077), {'changeset': '527179', 'uid': '17383', 'timestamp': '2008-05-26T10:10:31Z', 'visible': 'true', 'version': '1', 'user': '******'}, {}), 266937071: ((43.7753977, 11.2633788), {'changeset': '6321945', 'uid': '368490', 'timestamp': '2010-11-08T16:29:13Z', 'visible': 'true', 'version': '2', 'user': '******'}, {}), 266938738: ((43.775425, 11.2676242), {'changeset': '121845', 'uid': '17383', 'timestamp': '2008-06-10T15:53:30Z', 'visible': 'true', 'version': '2', 'user': '******'}, {}), 867230075: ((43.7716004, 11.2663528), {'changeset': '5530428', 'uid': '181166', 'timestamp': '2010-08-18T20:37:19Z', 'visible': 'true', 'version': '2', 'user': '******'}, {})}
	city.ways_d = {73108616: ({'changeset': '5531271', 'uid': '181166', 'timestamp': '2010-08-18T22:17:01Z', 'visible': 'true', 'version': '1', 'user': '******'}, [266938723, 266937071, 253248006, 249264782, 266938724], {'name': 'Via della Colonna', 'highway': 'unclassified'}), 24597933: ({'changeset': '6710449', 'uid': '192299', 'timestamp': '2010-12-19T20:51:21Z', 'visible': 'true', 'version': '5', 'user': '******'}, [266938738, 1050026629, 267396578], {'name': 'Via Vittorio Alfieri', 'highway': 'unclassified', 'oneway': '-1'}), 24597934: ({'changeset': '23519', 'uid': '17383', 'timestamp': '2008-06-02T21:03:17Z', 'visible': 'true', 'version': '2', 'user': '******'}, [266938738, 249264782], {'oneway': 'yes', 'name': "Piazza D'Azeglio", 'created_by': 'Potlatch 0.9c', 'highway': 'unclassified'}), 24597935: ({'changeset': '23519', 'uid': '17383', 'timestamp': '2008-06-02T21:03:19Z', 'visible': 'true', 'version': '2', 'user': '******'}, [266938010, 266938738], {'oneway': 'yes', 'name': "Piazza D'Azeglio", 'created_by': 'Potlatch 0.9c', 'highway': 'unclassified'}), 24597928: ({'changeset': '6442099', 'uid': '24126', 'timestamp': '2010-11-23T20:06:40Z', 'visible': 'true', 'version': '6', 'user': '******'}, [867230075, 266938724], {'name': 'Via Giosu\xc3\xa8 Carducci', 'highway': 'residential', 'oneway': 'yes'}), 27590930: ({'changeset': '158574', 'uid': '49848', 'timestamp': '2008-10-08T00:14:14Z', 'visible': 'true', 'version': '1', 'user': '******'}, [267396306, 266938724], {'highway': 'unclassified', 'created_by': 'Potlatch 0.9c', 'name': 'Via G. B. Niccolini'}), 24550899: ({'changeset': '23519', 'uid': '17383', 'timestamp': '2008-06-02T21:04:28Z', 'visible': 'true', 'version': '7', 'user': '******'}, [266938724, 266938010], {'oneway': 'yes', 'name': "Piazza D'Azeglio", 'created_by': 'Potlatch 0.9c', 'highway': 'unclassified'}), 24550900: ({'changeset': '158574', 'uid': '49848', 'timestamp': '2008-10-08T00:14:12Z', 'visible': 'true', 'version': '3', 'user': '******'}, [82591700, 266938010], {'oneway': '-1', 'name': 'Via P. Giordani', 'created_by': 'Potlatch 0.9a', 'highway': 'residential'}), 23091573: ({'changeset': '676144', 'uid': '49848', 'timestamp': '2008-12-30T19:17:29Z', 'visible': 'true', 'version': '4', 'user': '******'}, [249264780, 249264782], {'oneway': '-1', 'name': 'Via Farini', 'created_by': 'Merkaartor 0.12', 'highway': 'unclassified'}), 27590908: ({'changeset': '6710449', 'uid': '192299', 'timestamp': '2010-12-19T20:51:21Z', 'visible': 'true', 'version': '3', 'user': '******'}, [266938010, 1050026396, 302963542], {'name': 'Via Silvio Pellico', 'highway': 'unclassified', 'oneway': 'yes'}), 24550898: ({'changeset': '6460367', 'uid': '375692', 'timestamp': '2010-11-26T09:19:05Z', 'visible': 'true', 'version': '8', 'user': '******'}, [266938738, 269532440, 82591707], {'name': 'Via Giuseppe Giusti', 'highway': 'residential', 'oneway': 'yes'}), 49131710: ({'changeset': '3749978', 'uid': '47888', 'timestamp': '2010-01-30T11:20:30Z', 'visible': 'true', 'version': '1', 'user': '******'}, [300435931, 299853208, 299853210, 299853211, 300435931], {'name': "Piazza D'Azeglio", 'leisure': 'park'})}

	city.streetNWAdm.streetsBoundingBox = (43.7716004, 11.2615376, 43.7777961, 11.2699985)
	city.streetNWAdm.directG.edges_l = [((266938723, 266937071), 73108616), ((266937071, 253248006), 73108616), ((253248006, 249264782), 73108616), ((249264782, 266938724), 73108616), ((266938738, 1050026629), 24597933), ((1050026629, 267396578), 24597933), ((266938738, 249264782), 24597934), ((266938010, 266938738), 24597935), ((867230075, 266938724), 24597928), ((267396306, 266938724), 27590930), ((266938724, 266938010), 24550899), ((82591700, 266938010), 24550900), ((249264780, 249264782), 23091573), ((266938010, 1050026396), 27590908), ((1050026396, 302963542), 27590908), ((266938738, 269532440), 24550898), ((269532440, 82591707), 24550898)]
	city.streetNWAdm.dualG.edges_l = [((73108616, 24597934), 249264782), ((73108616, 23091573), 249264782), ((24597934, 23091573), 249264782), ((73108616, 24597928), 266938724), ((73108616, 27590930), 266938724), ((73108616, 24550899), 266938724), ((24597928, 27590930), 266938724), ((24597928, 24550899), 266938724), ((27590930, 24550899), 266938724), ((24597933, 24597934), 266938738), ((24597933, 24597935), 266938738), ((24597933, 24550898), 266938738), ((24597934, 24597935), 266938738), ((24597934, 24550898), 266938738), ((24597935, 24550898), 266938738), ((24597935, 24550899), 266938010), ((24597935, 24550900), 266938010), ((24597935, 27590908), 266938010), ((24550899, 24550900), 266938010), ((24550899, 27590908), 266938010), ((24550900, 27590908), 266938010)]
	city.streetNWAdm.intAcc.intersections_d = {266938738: [24597933, 24597934, 24597935, 24550898], 266938724: [73108616, 24597928, 27590930, 24550899], 266938010: [24597935, 24550899, 24550900, 27590908], 249264782: [73108616, 24597934, 23091573]}
	city.streetNWAdm.proxAcc._ProximityAccelerator__cellSize = 0.001
	city.streetNWAdm.proxAcc._ProximityAccelerator__gridBB = (43.7716004, 11.2615376, 43.778600399999995, 11.2705376)
	city.streetNWAdm.proxAcc._ProximityAccelerator__gridSize = (7, 9)
	city.streetNWAdm.proxAcc.nodesGrid_m = [[{}, {}, {}, {249264780: [23091573]}, {867230075: [24597928]}, {-636946: [24597928]}, {}, {}, {}], [{}, {}, {}, {}, {-844546: [23091573]}, {-455469: [73108616], -209052: [24597928]}, {-318141: [27590930], 266938724: [73108616, 24597928, 27590930, 24550899]}, {267396306: [27590930]}, {}], [{}, {}, {}, {-84452: [73108616]}, {249264782: [73108616, 24597934, 23091573]}, {-10656: [24597934]}, {-624847: [24550899]}, {-382606: [24550899]}, {82591700: [24550900]}], [{}, {266937071: [73108616]}, {-318574: [73108616]}, {253248006: [73108616]}, {}, {-362311: [24597934]}, {266938738: [24597933, 24597934, 24597935, 24550898], -476881: [24597935]}, {266938010: [24597935, 24550899, 24550900, 27590908]}, {1050026396: [27590908], 302963542: [27590908]}], [{-839886: [73108616], 266938723: [73108616]}, {-9869: [73108616]}, {}, {}, {269532440: [24550898]}, {-257435: [24550898]}, {-241720: [24597933], 1050026629: [24597933]}, {267396578: [24597933]}, {}], [{}, {-796412: [24550898]}, {-4171: [24550898]}, {-70304: [24550898]}, {}, {}, {}, {}, {}], [{}, {82591707: [24550898]}, {}, {}, {}, {}, {}, {}, {}]]
	city.streetNWAdm.proxAcc.extraNodes_d = {-10656: ((43.7744152, 11.266745133333334), 24597934, 266938738), -70304: ((43.7766444, 11.265084275), 24550898, 269532440), -318141: ((43.77301235, 11.268278550000002), 27590930, 267396306), -209052: ((43.77269, 11.267322733333334), 24597928, 867230075), -257435: ((43.775842749999995, 11.26675865), 24550898, 266938738), -455469: ((43.77357255, 11.26705665), 73108616, 249264782), -241720: ((43.775968649999996, 11.26808075), 24597933, 266938738), -796412: ((43.7774122, 11.263466625), 24550898, 269532440), -382606: ((43.77423053333333, 11.268706033333334), 24550899, 266938724), -318574: ((43.77509015, 11.2639933), 73108616, 266937071), -636946: ((43.7721452, 11.266837766666667), 24597928, 867230075), -476881: ((43.7750767, 11.2683897), 24597935, 266938010), -624847: ((43.77373266666667, 11.268256866666666), 24550899, 266938724), -839886: ((43.7760153, 11.262151333333334), 73108616, 266938723), -9869: ((43.7757065, 11.262765066666667), 73108616, 266938723), -4171: ((43.7770283, 11.26427545), 24550898, 269532440), -362311: ((43.774920099999996, 11.267184666666667), 24597934, 266938738), -84452: ((43.774346449999996, 11.265456700000001), 73108616, 253248006), -844546: ((43.77324385, 11.26572745), 23091573, 249264780)}
	return city
Example #38
0
def benchResolveCoords(num):

    coords = [(-3.03333,53.47778), (40.7226,-74.66544), (31.78199,35.2196), (0,0),(45,45)]
    r = redis.Redis()
    ncoords = len(coords)
    for i in xrange(num):
        lat,lon = coords[i % ncoords]
        loc = City.getByLatLon(lat,lon, r)
        

    return num
Example #39
0
    def fetch_cities_data(self):
        dest = State.file_prefix + self._abbrv + "/City"
        dir = Dir(dest)
        if dir.exists() is False:
            dir.create_if_needed()

        for alpha in self._alpha:
            data = File(State.file_prefix + self._abbrv + "/" + alpha + "/file")
            if data.exists() is True:
                # parse and get a list of cities
                print "parsing city data for (%s, %s)" % (self._state, alpha)
                cities = CityParser(self._abbrv, data)
                for c in cities.parse():
                    this_city = City(self._abbrv, State.state_map[self._abbrv], c)
                    try:
                        this_city.fetch_data()
                    except Exception:
                        print "error data for (%s, %s)" % (self._state, alpha)
            else:
                print "...... no data for %s, %s" % (self._abbrv, alpha)
Example #40
0
def gen_city():
    city = City()
    city.name = gen_city_name()
    city.size = choice(SIZES)
    city.danger = randint(-3, 4)
    city.draw = randint(-3, 4)

    if city.size == "village":
        city.danger -= 1
        city.draw -= 1
    elif city.size == "city":
        city.danger += 1
        city.draw += 1
    elif city.size == "metropolis":
        city.danger += 2
        city.draw += 2

    if city.size == "village":
        population_count = randint(4, 5)
    elif city.size == "town":
        population_count = randint(6, 8)
    elif city.size == "city":
        population_count = randint(9, 10)
    elif city.size == "metropolis":
        population_count = randint(11, 12)

    city.population = []
    for person in range(population_count):
        person = gen_person()
        city.population.append(person)

    return city
Example #41
0
File: GA.py Project: hajix/GA_TSP
    def __init__(self, file_path='./data/dj.txt', pop_size=10000, generations=100):
        super(GA, self).__init__()
        # read file and make base city list
        with open(file_path, 'r') as f:
            city_lines = [i.strip() for i in f.readlines() if i[0].isdigit()]
        self.base_city_list = [City(i.split()[0], float(i.split()[1]), float(i.split()[2])) for i in city_lines]
        City.make_table()

        # generate initial population
        self.pop_size = pop_size
        self.pop = []
        #print('-------------------generate pop-------------------')
        for i in range(self.pop_size):
            #print(i * 100.0 / self.pop_size)
            self.pop.append(chromosome.Chromosome(self.generate_city_permutation(self.base_city_list)))

        # keep the best solution
        self.best_tour = deepcopy(chromosome.Chromosome(self.base_city_list))
        self.tsp_size = len(self.best_tour.city_list)
        #print('tsp size {}'.format(self.tsp_size))

        # how many generations?
        self.generations = generations
Example #42
0
    def getCity(ip, redisConn):
        """
        Get location object by resolving an IP address
        @param ip IPv4 address string (e.g. 127.0.0.1)
        @oaram redisConn redis connection to the database
        @return a Location object if we can resolve this ip, else None
        """

        range = IPRange.get(ip, redisConn)
        if not range:
            return None

        #load a location by the
        return City.getByGeohash(hasher.encode(range.lat, range.lon), redisConn)
Example #43
0
    def search_location(self, location):
        """
        Try to find locations by given city name. Return list of :class:`City` objects
        """
        path = 'search'

        response = self.__request(path, {
            'query':location,
            'format':self.format,
        })

        tree = ET.fromstring(response)

        if tree.tag == 'data':
            raise Exception(tree.find('error').find('msg').text)

        cities = list()
        for result in tree:
            city = City(result.get)
            for child in result.getchildren():
                city.__setattr__(child.tag, child.text)
            cities.append(city)

        return cities
 def to_newappl_msg(cls):
     data_list = []
     querry = cls.select().where(cls.sent_application_email == False and cls.application_code != None and cls.school_cid != None)
     if querry.count() == 0:
         raise StopIteration
     for record in querry:
         city_record = City.select().join(School).join(Applicant).where(Applicant.aid==record.aid).get()
         data_list.append({'email': record.email,
                           'name': record.name,
                           'ap_code': record.application_code,
                           'city': city_record.name,
                           'aid': record.aid})
         record.sent_application_email = True
         record.save()
     return data_list
Example #45
0
 def to_dict(self):
     ''' Returns a hash of the Place in the database '''
     data = {}
     city = City.get(City.id == self.city)
     owner = User.get(User.id == self.owner)
     data['owner_id'] = owner.id
     data['city_id'] = city.id
     data['name'] = self.name
     data['description'] = self.description
     data['number_rooms'] = self.number_rooms
     data['number_bathrooms'] = self.number_bathrooms
     data['max_guest'] = self.max_guest
     data['price_by_night'] = self.price_by_night
     data['latitude'] = self.latitude
     data['longitude'] = self.longitude
     return super(Place, self).to_dict(self, data)
 def to_appl_interview_msg(cls):
     from interview_slot import InterviewSlot
     data_list = []
     querry = cls.select().join(InterviewSlot)
     if querry.count() == 0:
         raise StopIteration
     for record in querry:
         city_record = City.select().join(School).join(Applicant).where(Applicant.aid==record.aid).get()
         data_list.append({'email': record.email,
                           'name': record.name,
                           'ap_code': record.application_code,
                           'city': city_record.name,
                           'aid': record.aid})
         record.sent_application_email = True
         record.save()
     return data_list
Example #47
0
	def to_dict(self):
		owner = User.get(User.id == self.owner)
		city = City.get(City.id == self.city)

		return {	'id': self.id,
					'created_at': self.created_at.strftime('%Y/%m/%d %H:%M:%S'),
					'updated_at': self.updated_at.strftime('%Y/%m/%d %H:%M:%S'),
					'owner_id': owner.id,
					'city_id': city.id,
					'name': self.name,
					'description': self.description,
					'number_rooms': self.number_rooms,
					'number_bathrooms': self.number_bathrooms,
					'max_guest': self.max_guest,
					'price_by_night': self.price_by_night,
					'latitude': self.latitude,
					'longitude': self.longitude	}
Example #48
0
    def __init__(self):
        Gtk.Window.__init__(self)
        self.vbox = Gtk.VBox(False, 5)
        self.vbox.show()

        self.set_title(WINDOW_CAPTION)
        self.add(self.vbox)

        # TODO: Ugly, try to improve this mechanism
        self.last_route_id = -1

        # Initialize the City backend part 
        # (Must be created before the Drawing Area)
        self.city = City()
        self.storage = Drawable_Object_Storage()

        # Create the PyGtk Interface
        self.create_window_interface()
Example #49
0
    def new_game(self):
        # Create new city
        self.city = City()
        self.city.generate_name()
        self.city.generate_districts()

        # Generate AI companies
        for i in xrange(0, randrange(10, 20)):
            b = Business(self)
            b.starting_funds()
            b.randomize_production(self.industries, self.resources)
            b.generate_name()
            b.district = choice(self.city.districts.keys())
            # self.city.districts[b.district].companies.append(b)
            self.ai_companies.append(b)

            # for i in self.ai_companies:
            # 	print i.name, i.money, i.producing, i.district

        self.player.money = 1000000

        self.commands.show_city(None)
        self.update_options(self.menus["city_overview_menu"])
Example #50
0
    def build(cls, data, start, end, center=None):
        
        log.info("Loading OpenPaths data...")

        if center is not None:
            points = [Point(i, float(d['lon']), float(d['lat']), d['t']) for i, d in enumerate(data) if d['t'] >= start and d['t'] <= end and science.geo_distance((float(d['lon']), float(d['lat'])), center) <= RADIUS]            
        else:
            points = [Point(i, float(d['lon']), float(d['lat']), d['t']) for i, d in enumerate(data) if d['t'] >= start and d['t'] <= end]                        
        points.sort(key=lambda p: p.t)                

        log.info("Generating graph...")
        start_clock = time.clock()  


        paths = Path.find_paths(points)
        places = Place.find_places(paths, CLUSTER_RADIUS)  
        cities = City.find_cities(places, CITY_RADIUS)
        almanac = Almanac(points, paths, places, cities)

        # almanac.label()        

        print("(%ss)" % (time.clock() - start_clock))

        return almanac
 def create_cities(cls):
     for c in cls.city_list:
         city = City.create(name=c)
Example #52
0
 def __init__(self):
     City.__init__(self)
     # self.url_header="http://search.rsscc.cn/flight/domestic?src=ctrip"
     self.url_header="http://search.rsscc.cn/flight/domestic?src=qunar"
Example #53
0
def resolveCoords(lat, lon):
    global redis_host, redis_port, redis_db
    r = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
    loc = City.getByLatLon(lat, lon, r)
    print loc
Example #54
0
     try:
         opt = int(input())
         break
     except ValueError:
         print("I asked a number, not else...")
 if opt == 0:
     print("Thanks for playing!\nI hope you enjoyd :)")
     break
 elif opt == 1:
     print(player)
 elif opt == 2:
     Pokemon.print_pokekodex()
 elif opt == 3:
     player.print_pokemons_objects_name()
 elif opt == 4:
     City.print_available_cities_with_pokemon()
 elif opt == 5:
     player.go_to_sleep()
 elif opt == 6:
     available_cities = [bp, kv, hb, db]
     counter = 0
     print("Available cities:\n"+"-"*18)
     for element in City.available_pokemon_object:
         print("-", element.name, "[{}]".format(counter))
         counter += 1
     while True:
         try:
             answer = int(input("Give me the target city number!\n"))
             break
         except ValueError:
             print("I asked a number, not else...")
 def length(self):
     sumPairs = zip(self._cities, [self._cities[-1]] + self._cities[0:-1])
     return sum(map(lambda tup: City.distance(tup[0], tup[1]), sumPairs))
Example #56
0
                name = row[2]

                country = row[8]
                adminCode = '.'.join((country, row[10]))
                region = re.sub('\\(.+\\)', '', self._adminCodes.get(adminCode, '')).strip()

                #for us states - take only state code not full name
                if country == 'US':
                    region = row[10]

                lat = float(row[4])
                lon = float(row[5])

                loc = City(name = name,
                                country = country,
                                state = region,
                                lat = lat,
                                lon = lon)

                loc.save(pipe)


                
            except Exception, e:
                logging.error("Could not import line %s: %s" % (row, e))
            i += 1
            if i % 1000 == 0:
                pipe.execute()
        pipe.execute()

        logging.info("Imported %d locations" % i)
Example #57
0
class Engine:
    def __init__(self, player, screen):
        self.player = player
        self.commands = Commands(self)
        self.screen = screen
        self.city = None
        self.menus = None
        self.current_menu = None
        self.resources = None
        self.industries = None
        self.ai_companies = []

    def preload_cfg(self):
        self.menus = json.load(open("data/menus.cfg"))
        self.resources = json.load(open("data/resources.cfg"))
        self.industries = json.load(open("data/industries.cfg"))

    def start(self):
        print "Starting"
        self.update_options(self.menus["title_menu"])
        self.screen.update_main_win("Title Screen")
        self.screen.init_screen()

    def update_options(self, menu_data):
        # Unbind all previous keys
        if self.current_menu is not None:
            for option in self.current_menu["options"].items():
                self.screen.root.unbind(option[0])

        txt = ""
        for option in menu_data["options"].items():
            o_key = option[0]
            o_str = option[1][0]
            o_cb = option[1][1]
            txt += "(%s) %s\n" % (o_key, o_str)

            # Bind callbacks
            cmd = getattr(self.commands, o_cb)
            if cmd:
                self.screen.root.bind(o_key, func=cmd)

        self.current_menu = menu_data
        self.screen.update_opts_win(txt)

    def new_game(self):
        # Create new city
        self.city = City()
        self.city.generate_name()
        self.city.generate_districts()

        # Generate AI companies
        for i in xrange(0, randrange(10, 20)):
            b = Business(self)
            b.starting_funds()
            b.randomize_production(self.industries, self.resources)
            b.generate_name()
            b.district = choice(self.city.districts.keys())
            # self.city.districts[b.district].companies.append(b)
            self.ai_companies.append(b)

            # for i in self.ai_companies:
            # 	print i.name, i.money, i.producing, i.district

        self.player.money = 1000000

        self.commands.show_city(None)
        self.update_options(self.menus["city_overview_menu"])

    def display_city_menu(self, districts=None):
        if districts is None:
            # By default, we sort by district name
            districts = self.city.districts_info()

        self.screen.display_column_data(
            "City: \n%s\n\n" % self.city.name, ["District", "Pop", "Income", "Unemployed", "%"], districts
        )

        self.update_options(self.menus["city_overview_menu"])

    def display_biz_menu(self, district=None):
        self.ai_companies
        self.screen.display_column_data("%s City\n\n" % self.city.name, ["Business", "Cash", ""])

    def end_turn(self):
        self.player.end_turn()
        txt = "%s\nTurn: %s" % (self.player.date.ctime(), self.player.turn)
        self.screen.update_head_win(txt)
Example #58
0
                    "you can also specify how many cities you want by passing an "
                    "optional number with the flag",
                    type=int, const=1, nargs='?')
parser.add_argument("--forcename", help="Force the specified name", action="store_true")
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
parser.add_argument("-V", "--version", action='version', version="%(prog)s " + VERSION)


args = parser.parse_args()
is_verbose = args.verbose
is_random = args.random
is_overwrite = args.overwrite
is_random_name = not args.forcename

if args.command == "build":
    if args.object == "city" and is_random:
        print("Building " + str(args.random) + " city")
        city = City(args.name)
        city.build_random(overwrite=is_overwrite, verbose=is_verbose, random_name=is_random_name)
    if args.object == "npc" and is_random:
        print("Building " + str(args.random) + " npc")
        npc = Npc(args.name)
        npc.build_random(overwrite=is_overwrite, verbose=is_verbose)

elif args.command == "show":
    if args.object == "city":
        pprint.pprint(City.get_city_by_name(args.name))
    if args.object == "npc":
        pprint.pprint(Npc.get_npc_by_name(args.name))
Example #59
0
 def eval_fitness(self):
     result = City.distance(self.city_list[0].name, self.city_list[-1].name)
     for ind, city1 in enumerate(self.city_list[:-1]):
         city2 = self.city_list[ind + 1]
         result += City.distance(city1.name, city2.name)
     return result