Exemple #1
0
    def login(cls, para):
        if not checkPara(para, ['version', 'did', ('type', lambda x: x in [cls.DEVICE_TYPE, cls.FB_TYPE])]):
            return Error.INVALID_PARAM

        version = para['version']
        did = para['did']

        if para['type'] == cls.DEVICE_TYPE:
            (uid, is_new) = Login.device_login(did)
        else:
            if para['fb_id'] in para['frd_list']:
                return Error.INVALID_PARAM

            (uid, is_new) = Login.fb_login(did, para['fb_id'], para['fb_name'], para['frd_list'])

        sid = Session.gen_session(uid)
        ret = {'uid': uid, 'sid': sid}

        user_info = User(uid).get(['coin', 'level', 'exp', 'name'], True)
        user_info['exp'] /= 100

        ret.update(user_info)

        if version < Config.LATEST_VERSION:
            ret['update'] = Config.PKG_URL

        User(uid).login_time = int(time.time())

        if 'ip' in para:
            g = cls.GEO.city(para['ip'])
            Location.update(uid, g['country_code'], g['region'])

        return ret
Exemple #2
0
    def __init__(self, host, port, username, password):
        self.origin = Location()
        self.origin.set(130, 71, 83)
        self.range = Location()
        self.range.set(10, 10, 10)
        self.X = 0
        self.Y = 0
        self.Z = 0
        self.bot = Bot()
        self.dispatch = PacketDispatch(self)
        self.buff = Buffer()
        self.packetSend = []
        self.sendPacket = PacketSend(self)
        self.printable = True
        self.receiveSize = 1024
        self.compressionThreshold = -1
        self.username = username

        self.HOST = host
        self.PORT = port

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.settimeout(None)
        try:
            self.s.connect((self.HOST, self.PORT))
        except socket.error:
            print("Connection refused")
            thread.interrupt_main()
            exit()
 def getLocationForPlace(self, country, state, county, city, url, id):
     location = Location(country, state, county, city, 0, 0, -1, False)
     if self.locationToId.has_key(location): 
         return self.idToLocation[self.locationToId[location]]
     location.setUrl(url)
     location.setTwitterId(id)
     return location
Exemple #4
0
	def readPosition(self):
		val = self.readLong()
		x = (val >> 38) & 0x3FFFFFF
		y = (val >> 26) & 0xFFF
		z = val & 0x3FFFFFF;
		location = Location();
		location.set(x, y, z);
		return location;
Exemple #5
0
    def test_intervention_add(self):
        location = Location('Dublin',"Irish",30)
        location.intervention_add("Test Intervention",3)

        self.assertTrue(location.intervention_level == 3)
        self.assertTrue(location.intervention_list[0] == "Test Intervention")

        location.intervention_add("Test Intervention 2",3)
        self.assertTrue(location.intervention_level == 6)
Exemple #6
0
    def test_add_team(self):
        location = Location('Dublin', "culture1", 30)

        team1 = Team('test_team1', 10)
        self.assertTrue(location.add_team(team1))

        team2 = Team('test_team2', 20)
        self.assertTrue(location.add_team(team2))

        team3 = Team('test_team3', 1)
        self.assertFalse(location.add_team(team3))

        self.assertTrue(len(location.teams) == 2)
Exemple #7
0
    def test_calc_fail(self):
        # This test will only make sure that calc_fail will return a bool
        # We cannot verify anything else since there is a random element involved
        location1 = Location('Dublin', "Irish", 30)
        location2 = Location('Florida', "American", 30)

        failed = location1.calc_fail(location2,False)
        self.assertTrue(failed == True or failed == False)

        location3 = Location('Canberra', "Australian", 30)
        location4 = Location('Toronto', "Canadian", 30)

        failed = location3.calc_fail(location4,False)
        self.assertTrue(failed == True or failed == False)

        location5 = Location('Rio de Janeiro', "Brazilian", 30)
        location6 = Location('New Dehli', "Indian", 30)

        failed = location5.calc_fail(location6,False)
        self.assertTrue(failed == True or failed == False)

        location7 = Location('New Dehli', "Indian", 30)
        location8 = Location('Tokyo', "Japanese", 30)

        failed = location7.calc_fail(location8,False)
        self.assertTrue(failed == True or failed == False)
 def test_is_right_alt(self):
     loc = Location()
     self.assertFalse(loc.is_right_alt(CHARACTER))
     self.assertFalse(loc.is_right_alt(CHAR_NUMBER))
     loc.set_altitude(CHAR_NUMBER)
     self.assertTrue(loc.is_right_alt(CHAR_NUMBER))
     self.assertTrue(loc.is_right_alt(float(CHAR_NUMBER)-0.04))
     self.assertTrue(loc.is_right_alt(float(CHAR_NUMBER)+0.04))
     self.assertFalse(loc.is_right_alt(float(CHAR_NUMBER)-0.06))
     self.assertFalse(loc.is_right_alt(float(CHAR_NUMBER)+0.06))
     self.assertTrue(loc.is_right_alt(float(CHAR_NUMBER)-0.05))
     self.assertTrue(loc.is_right_alt(float(CHAR_NUMBER)+0.05))
     self.assertFalse(loc.is_right_alt(float(CHAR_NUMBER)-0.051))
     self.assertFalse(loc.is_right_alt(float(CHAR_NUMBER)+0.051))
 def loadLocationFile(self, filename):
     for line in open(filename).readlines():
         locationObj = json.loads(line)
         location = Location.parseLocationFromJsonObj(locationObj)
         aliases = locationObj['aliases']
         self.idToLocation[location.getId()] = location
         self.locationToId[location] = location.getId()
         justAddedAliases = []
         for alias in aliases:
             if alias in justAddedAliases:
                 continue
             if self.locationNameToLocation.has_key(alias):
                 logger.warn("Duplicate location name: {}".format(alias))
             else:
                 self.locationNameToLocation[alias] = location
             justAddedAliases.append(alias)
             var = re.sub("\\p{Punct}", " ", alias)
             newEntry = re.sub("\\s+", " ", var)
             if newEntry in justAddedAliases:
                 continue
             if newEntry != alias:
                 if self.locationNameToLocation.has_key(newEntry):
                     logger.warn("Duplicate location name: {}".format(newEntry))
                 else:
                     self.locationNameToLocation[newEntry] = location
             justAddedAliases.append(newEntry)
Exemple #10
0
 def __init__(self):
     super(XingZhengQuHua,self).__init__()
     self.top_url = 'http://www.xzqh.org/html/'
     self.encoding = 'gbk'
     self.LOG_FILE = 'XingZhengQuHua.log'
     self.location = Location()
     self.logger = LOG('XingZhengQuHua',self.LOG_FILE)
Exemple #11
0
    def test_total_module_progress(self):
        location = Location('Dublin', "culture1", 30)

        location.add_team(Team('test_team1', 1))
        location.add_team(Team('test_team2', 1))
        location.add_team(Team('test_team3', 1))
        location.add_team(Team('test_team4', 1))
        location.add_team(Team('test_team5', 1))

        self.assertTrue(location.total_module_progress() == 0)
 def __init__(self):
     self.stateFullNames = []
     self.countryFullNames = []
     self.stateAbbreviationToFullName = dict()
     self.countryAbbreviationToFullName = dict()
     self.geocodeLocationResolver = None
     self.useUnknownPlaces = True        
     self.newLocationIndex = Constants.NEW_LOCATION_STARTING_INDEX
     self.statePattern = ".+,\\s*(\\w+)"
     self.placeNameToNormalizedPlaceName = dict()
     self.idToLocation = dict()
     self.locationNameToLocation = dict()
     self.locationToParent = dict()
     self.locationToChildren = dict()
     self.locationToId = dict()
     self.usePlace = CarmenProperties["use_place"]
     self.useGeocodes = CarmenProperties["use_geocodes"]
     self.useUserString = CarmenProperties["use_user_string"]
     self.useUnknownPlaces = CarmenProperties["use_unknown_places"]
     logger.info("Geocoding using these resources:")
     if self.usePlace:
         logger.info('place')
     if self.useGeocodes:
         logger.info('geocodes')
     if self.useUserString:
         logger.info("user profile")
     logger.info("Loading location resources.")
     self.loadLocationFile(os.path.join(root,CarmenProperties["locations"]))
     knownLocations = []
     for location in self.idToLocation.values():
         knownLocations.append(location)
     self.idToLocation[-1] = Location.getNoneLocation()
     for location in knownLocations:
         parent = self.createParentOfLocation(location)
         if parent and not parent.isNone():
             self.locationToParent[location] = parent
         if not self.locationToChildren.has_key(parent):
             self.locationToChildren[parent] = []
         self.locationToChildren[parent].append(location)
         currentLocation = parent
         parent = self.createParentOfLocation(currentLocation)
         while parent and not parent.isNone():
             if not self.locationToParent.has_key(currentLocation):
                 self.locationToParent[currentLocation] = parent
             if not self.locationToChildren.has_key(parent):
                 self.locationToChildren[parent] = []
             self.locationToChildren[parent].append(currentLocation)
             currentLocation = parent
             parent = self.createParentOfLocation(currentLocation)
     if self.usePlace:
         self.loadNameAndAbbreviation(os.path.join(root,CarmenProperties["place_name_mapping"]), None, self.placeNameToNormalizedPlaceName, False)
     self.loadNameAndAbbreviation(os.path.join(root,CarmenProperties["state_names_file"]), self.stateFullNames, self.stateAbbreviationToFullName, True);
     self.loadNameAndAbbreviation(os.path.join(root,CarmenProperties["country_names_file"]), self.countryFullNames, self.countryAbbreviationToFullName, True);
     if self.useGeocodes:
         self.geocodeLocationResolver = GeocodeLocationResolver()
         for location in self.idToLocation.values():
             if location.latitude and location.longitude:
                 self.geocodeLocationResolver.addLocation(location)
Exemple #13
0
 def goTo(self, x, y, z):
     old = self.network.dispatch.bot.location
     distance = Location()
     distance.x = x - old.x
     distance.z = z - old.z
     speed = 3 / 20
     vx = speed * math.sin(math.tanh(distance.z / distance.x))
     vz = speed * math.cos(math.tanh(distance.z / distance.x))
     self.network.X = vx
     self.network.Z = vz
     if x > old.x:
         while self.network.dispatch.bot.location.x < x:
             sleep(0.05)
     elif x < old.x:
         while self.network.dispatch.bot.location.x > x:
             sleep(0.05)
     self.network.X = 0
     self.network.Z = 0
 def selectAllLocations(self, accountId):
     conn = sqlite3.connect(self.dbName)
     locationCursor = conn.cursor()
     data = locationCursor.execute(
                "select * from Location where AccountId = %d" % accountId
            ).fetchall()
     locationCursor.close()
     
     locations = []
     
     for ldata in data:
         location = Location(ldata[0], ldata[1], ldata[2], ldata[3], ldata[4])
         growCursor = conn.cursor()
         growData = growCursor.execute(
                        "select * from Grow, FruitCrop where (Grow.FC_Id) = FruitCrop.Id and Grow.L_Id = %d" % ldata[0]
                    ).fetchall()
         for g in growData:
             FC = FruitCrop(g[4], g[5], g[6], g[7])
             grow = Grow(g[0], g[1], FC, g[2], g[3])
             location.appendGrow(grow)
         growCursor.close()
         locations.append(location)
     conn.close()
     return locations
Exemple #15
0
 def update_location_retrieved(self):
     apple_location = self.apple_device.location()
     if apple_location is not None:
         self.logger.debug(apple_location)
         self.logger.debug("location: type=%s, finished=%s, horizontalAccuracy=%f" %
                           (apple_location['positionType'], apple_location['locationFinished'],
                            apple_location['horizontalAccuracy']))
         location_timestamp = apple_location['timeStamp'] / 1000
         accuracy = math.floor(apple_location['horizontalAccuracy'])
         self.location_retrieved = Location(apple_location['latitude'], apple_location['longitude'], accuracy,
                                            location_timestamp)
         return True
     else:
         self.logger.warn("Unable to get the location for device %s. Next retry in %d seconds" %
                          (self.name, ACTION_NEEDED_ERROR_SLEEP_TIME))
         return False
 def createParentOfLocation(self, location):
     parentLocation = None
     if location.getCity():
         parentLocation = Location(location.getCountry(), location.getState(), location.getCounty(), None, None, None, -1, False)
     elif location.getCountry():
         parentLocation = Location(location.getCountry(), location.getState(), None, None, None, None, -1, False)
     elif location.getState():
         parentLocation = Location(location.getCountry(), None, None, None, None, None, -1, False)
     elif location.getCountry() and location.getCountry().lower() != Constants.DS_LOCATION_NONE.lower():
         parentLocation = Location.getNoneLocation()
     if not parentLocation:
         return None
     if self.locationToId.has_key(parentLocation):
         return self.idToLocation[self.locationToId[parentLocation]]
     self.registerNewLocation(parentLocation)
     return parentLocation
Exemple #17
0
    def test_dist_g(self):
        location1 = Location('Dublin', "Irish", 30)
        location2 = Location('Florida', "American", 30)

        self.assertTrue(location1.dist_g(location2) == 8.0)

        location3 = Location('Canberra', "Australian", 30)
        location4 = Location('Toronto', "Canadian", 30)

        self.assertTrue(location3.dist_g(location4) == 9.0)

        location5 = Location('Rio de Janeiro', "Brazilian", 30)
        location6 = Location('New Dehli', "Indian", 30)

        self.assertTrue(location5.dist_g(location6) == 23.0)

        location7 = Location('New Dehli', "Indian", 30)
        location8 = Location('Tokyo', "Japanese", 30)

        self.assertTrue(location7.dist_g(location8) == 18.0)

        self.assertTrue(location7.dist_g(location7) == 2.0)
Exemple #18
0
 def load_regions_from_json(self, file_path):
     region_json = read_json(file_path)
         
     for region in region_json:
         new_region = Region(region['region_name'])
         new_region.world = self
         if 'scene' in region:
             new_region.scene = region['scene']
         if 'hint' in region:
             new_region.hint = region['hint']
         if 'dungeon' in region:
             new_region.dungeon = region['dungeon']
         if 'time_passes' in region:
             new_region.time_passes = region['time_passes']
             new_region.provides_time = TimeOfDay.ALL
         if new_region.name == 'Ganons Castle Grounds':
             new_region.provides_time = TimeOfDay.DAMPE
         if 'locations' in region:
             for location, rule in region['locations'].items():
                 new_location = LocationFactory(location)
                 new_location.parent_region = new_region
                 new_location.rule_string = rule
                 if self.logic_rules != 'none':
                     self.parser.parse_spot_rule(new_location)
                 new_location.world = self
                 new_region.locations.append(new_location)
         if 'events' in region:
             for event, rule in region['events'].items():
                 # Allow duplicate placement of events
                 lname = '%s from %s' % (event, new_region.name)
                 new_location = Location(lname, type='Event', parent=new_region)
                 new_location.rule_string = rule
                 if self.logic_rules != 'none':
                     self.parser.parse_spot_rule(new_location)
                 new_location.world = self
                 new_region.locations.append(new_location)
                 MakeEventItem(event, new_location)
         if 'exits' in region:
             for exit, rule in region['exits'].items():
                 new_exit = Entrance('%s -> %s' % (new_region.name, exit), new_region)
                 new_exit.connected_region = exit
                 new_exit.rule_string = rule
                 if self.logic_rules != 'none':
                     self.parser.parse_spot_rule(new_exit)
                 new_region.exits.append(new_exit)
         self.regions.append(new_region)
    def gen_from_index(index):

        boardIndexLookup = [
        (1,0) , (2,0) , (3,0) , (4,0) , (5,0) ,             # noqa: E122, E231, E203, E501
(0,1) , (1,1) , (2,1) , (3,1) , (4,1) , (5,1) , (6,1) ,     # noqa: E122, E231, E203, E501
(0,2) , (1,2) , (2,2) , (3,2) , (4,2) , (5,2) , (6,2) ,     # noqa: E122, E231, E203, E501
(0,3) , (1,3) , (2,3) ,         (4,3) , (5,3) , (6,3) ,     # noqa: E122, E231, E203, E501
(0,4) , (1,4) , (2,4) , (3,4) , (4,4) , (5,4) , (6,4) ,     # noqa: E122, E231, E203, E501
(0,5) , (1,5) , (2,5) , (3,5) , (4,5) , (5,5) , (6,5) ,     # noqa: E122, E231, E203, E501
        (1,6) , (2,6) , (3,6) , (4,6) , (5,6)]              # noqa: E122, E231, E203, E501

        if index < 0 or index >= len(boardIndexLookup):
            raise IndexError("Bounds err for index lookup: {0}".format(index))

        loc_tuple = boardIndexLookup[index]
        loc = Location(x=loc_tuple[0], y=loc_tuple[1])
        return loc
Exemple #20
0
    def from_xml_local(cls, xml_tree):
        arena = Arena()
        locs = []
        rooms = []
        doors = []
        for child in xml_tree.getchildren():
            if child.tag == 'LOCATION':
                locs.append(Location.from_xml_local(child))
            elif child.tag == 'ROOM':
                rooms.append(Room.from_xml_local(child))
            elif child.tag == 'DOOR':
                doors.append(Door.from_xml_local(child))

        arena.locations = locs
        arena.rooms = rooms
        arena.doors = doors

        return arena
Exemple #21
0
    def __init__(self, map_size):
        self.h = xxhash.xxh64
        self.agent_loc = (0, 0)
        self.pre_num_unknown_locations = map_size * map_size
        self.pre_prime = 13
        self.pre_result = 1

        self.PFS = np.ndarray(shape=(map_size, map_size), dtype=float)
        self.color = np.ndarray(shape=(map_size, map_size), dtype=float)
        self.seen = np.ndarray(shape=(map_size, map_size), dtype=bool)
        self.temp_seen = np.ndarray(shape=(map_size, map_size), dtype=bool)
        self.map_size = map_size
        self.middle = (self.map_size / 2, self.map_size / 2)
        self.mine_location = Location(randint(0, self.map_size - 1),
                                      randint(0, self.map_size - 1))
        self.complete = True
        self.max_reward = self.map_size * self.map_size
        self.reset()
Exemple #22
0
 def populate(self, numSapiens=50):
     """Populates the _field with randomly-locationed _sapiens.
     """
     self._field.clear()
     for s in range(numSapiens):
         location = Location(
             None, None, 0,
             self.size)  # generate 0 <= random location < size
         velocity = Velocity(randrange(-1, 1), randrange(
             -1, 1))  # generate random -1 <= random velocity < 1
         colour = self._colours[State.SUSCEPTIBLE]
         state = State.SUSCEPTIBLE
         self._sapiens.append(
             Sapiens(location, velocity, colour, self._field, state, 0,
                     0))  # append particle with location and velocity
     if len(self._sapiens) > 0:
         shuffle(self._sapiens)
         self._sapiens[0].state = State.INFECTED
Exemple #23
0
    def loadFile(self):
        print("Load Location CSV files...")
        locationsCSV = Utils.loadCsv(Config.LOCATION_PROFILE_FILEPATH)
        print("Load Location CSV finished\nCreating location data...")
        for subtowm, latitude, longitude, dsp in zip(
                locationsCSV.neighbourhood, locationsCSV.latitude,
                locationsCSV.longitude, locationsCSV.DSP):
            self.locations.append(Location(latitude, longitude, subtowm, dsp))
        print("Location load finish.")

        print("Load PV CSV files...")
        self.profileCSV = Utils.loadCsv(Config.PV_PROFILE_CSV_FILEPATH)
        # Create & Load PV data
        print("PV file load finished\nCreating PV data...")
        for date, production, time in zip(self.profileCSV.date,
                                          self.profileCSV.production,
                                          self.profileCSV.time):
            self.photoVoltaics.append(PhotoVoltaic(date, time, production))
        # print(self.profileCSV.iloc[0,0])
        # Create & Load Comsumption data
        print("Load Comsumptions file...")
        comsuptionsFileCount = 0
        comsuptionsDataCount = 0
        for filename in os.listdir(Config.CONSUMPTION_PROFILE_FILEPATH):
            file = Utils.loadCsv(Config.CONSUMPTION_PROFILE_FILEPATH +
                                 filename)
            print("Processing File:" + Config.C_VAUE +
                  "{0}...".format(filename) + Config.C_NORMAL)
            comsumption = Comsumption([])
            for i in range(0, Config.CONSUMPTION_COL):
                # Parse comsumption data
                for j in range(3, Config.CONSUMPTION_ROW):
                    data = file.iloc[i, j]
                    comsumption.appendComsumption(data)
                    comsuptionsDataCount += 1
            self.comsumptions.append(comsumption)
            comsuptionsFileCount += 1
        # debug msg
        print("Comsumptions File load finish,total:{0}.".format(
            comsuptionsFileCount))
        print("Comsumptions data created,total:{0}.".format(
            comsuptionsDataCount))
        print("File loading process finish.")
Exemple #24
0
class Event(object):
    
    __ticketFee = 25

    def __init__(self, ename, tprice, date, city, loc_name):
        self.__event_name = ename
        self.__price = int(tprice)
        self.__date = date
        self.__location = Location(city, loc_name)
        self.__active = True

    def get_month(self):
        return int(self.__date.split("/")[1])

    def get_location(self):
        return self.__location

    def calculate_ticket_price(self):
        if(self.__location.get_city() == "Istanbul"):
            return self.__price + Event.__ticketFee
        else:
            return self.__price + (Event.__ticketFee * 0.75)

    def __lt__(self, other):
        if(self.__location < other.get_location()):
            return True
        elif(self.__location == other.get_location() and self.calculate_ticket_price() < other.calculate_ticket_price()):
            return True
        else:
            return False
        
    def set_active(self):
        self.__active = not self.__active
    
    def is_active(self):
        return self.__active
        
    def __repr__(self):
        s = ''
        if not self.is_active():
            s = '**CANCELLED** '
        return s + '{} {} ({}TL): {}\n'.format(self.__event_name, self.__date,self.calculate_ticket_price(),self.__location)
Exemple #25
0
    def xyzToLatLong(self, x, y, z):
        x = float(x)
        y = float(y)
        z = float(z)
        r = 6731
        long_0 = 0.0
        #________________________________________________

        lon = long_0 + (x / r)
        lat = (2 * math.atan(math.exp(y / r))) - (math.pi / 2.0)

        lat *= (180.0 / math.pi)
        lon *= (180.0 / math.pi)

        # print("X", x)
        # print("Y", y)
        # print("Z", z)
        # print("lat:", lat)
        # print("long", lon)
        # print("LC: Lat, Long:", lat, lon)
        #________________________________________________
        # r = math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(z,2))

        # lat = math.asin(z/r) * (180.0 / math.pi)
        # lon = math.atan2(y, x) * (180.0 / math.pi)
        # print("XYZ:", x, y, z)
        # print("Lat/Long", lat, lon)

        # return Location(lat, lon, 1.0)
        #________________________________________________
        # r = math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(x,2))

        # lat = math.asin(z/r) * (180/math.pi)
        # lon = 0.0
        # if (x > 0):
        # 	lon = math.atan(y/x) * (180/math.pi)
        # elif (y > 0):
        # 	lon = math.atan(y/x) * (180/math.pi) + 180
        # else:
        # 	lon = math.atan(y/x) * (180/math.pi) - 180

        return Location(lat, lon, 1.0)
    def create_delayed_rules(self):
        for region_name, node, subrule_name in self.delayed_rules:
            region = self.world.get_region(region_name)
            event = Location(subrule_name, type='Event', parent=region, internal=True)
            event.world = self.world

            self.current_spot = event
            # This could, in theory, create further subrules.
            access_rule = self.make_access_rule(self.visit(node))
            if access_rule is self.rule_cache.get('NameConstant(False)') or access_rule is self.rule_cache.get('Constant(False)'):
                event.access_rule = None
                event.never = True
                logging.getLogger('').debug('Dropping unreachable delayed event: %s', event.name)
            else:
                if access_rule is self.rule_cache.get('NameConstant(True)') or access_rule is self.rule_cache.get('Constant(True)'):
                    event.always = True
                event.set_rule(access_rule)
                region.locations.append(event)

                MakeEventItem(subrule_name, event)
        # Safeguard in case this is called multiple times per world
        self.delayed_rules.clear()
Exemple #27
0
def generate_locations(nodes, cell_size):
    locations_file = "Locations/" + "{}_locations_{}_cellsize_{}_sim.pkl".format(
        nodes, cell_size, num_simulations)
    locations_per_simulation = list()
    for num_sim in range(num_simulations):
        locations = list()
        for i in range(nodes):
            loc = Location(cell_size, indoor=False)
            locations.append(loc)
        locations_per_simulation.append(locations)

    if os.path.exists(locations_file):
        os.remove(locations_file)
    touch(locations_file)
    print(
        'Generating {} locations with cell size {} for {} simulations'.format(
            nodes, cell_size, num_simulations))

    with open(locations_file, 'wb') as f:
        pickle.dump(locations_per_simulation, f)
Exemple #28
0
def main():
    reader = DataReader('dataSrc')

    data = reader.readCoordinates()

    processor = DataProcessor(data)
    locations = processor.processDataPoints()
    try:
        for location in locations:
            location.state.country.addNew()
            location.state.country_id = location.state.country.id
            #location.state.country = None
            location.state.addNew()
            location.state_id = location.state.id
            #location.state = None
            location.addNew()
    except Exception as e:
        print(e)

    print(Location.listAll())
Exemple #29
0
    def create_delayed_rules(self):
        for region_name, node, subrule_name in self.delayed_rules:
            region = self.world.get_region(region_name)
            event = Location(subrule_name, type='Event', parent=region, internal=True)
            event.world = self.world

            self.current_spot = event
            # This could, in theory, create further subrules.
            event.access_rule = self.make_access_rule(self.visit(node))
            event.set_rule(event.access_rule)
            region.locations.append(event)

            MakeEventItem(subrule_name, event)
        # Safeguard in case this is called multiple times per world
        self.delayed_rules.clear()
Exemple #30
0
def location_handler(req, player, loc, components):
    """Handle a request for information on a single location"""
    if len(components) != 1:
        return apache.HTTP_NOT_FOUND

    if req.method != 'GET':
        return apache.HTTP_METHOD_NOT_ALLOWED

    req.content_type = "text/plain"
    here = Location.load(loc)

    if components[0] == 'desc':
        info = here.context_get(player.get_context())
        Util.render_info(info, req)
    elif components[0] == 'actions':
        # Return possible location-based actions
        pass
    else:
        return apache.HTTP_NOT_FOUND

    return apache.OK
class PathFinder(object):
    currentLocation = Location(0, 'A')

    def __init__(self, currentLocation):
        self.currentLocation = currentLocation

    def getDistanceToLoc(self, newLoc):
        #	self.log("Aktuelle Position : %s. Zu fahrende Position: %s" % (self.currentLocation.getDist(), newLoc.getDist()))
        return (int(newLoc.getDist()) - int(self.currentLocation.getDist()))

    def updateLocation(self, distance):
        self.currentLocation.dist = self.currentLocation.dist + distance

    def setLocation(self, location):
        self.currentLocation.dist = location.dist

    def getLocation(self):
        return self.currentLocation

    def log(self, message):
        print("[Pathfinder] : %s" % message)
def create_locations_table(file):
    locations = HashTable()

    with open(file, newline = '') as locations_file:
        reader = csv.reader(locations_file)

        idx = 0

        for row in reader:
            name = row[0].strip()
            street = row[1].strip()
            city = row[2].strip()
            state = row[3].strip()
            zip_code = row[4].strip()

            l = Location(name, street, city, state, zip_code, idx)
            locations.insert(street, l)
            
            idx += 1

    return locations
 def generateRandomEntry(db):
     shorthand = "A"
 
     randomDate = DateUtils.randomDate(datetime.date(2013, 6, 1), datetime.date.today())
     shorthand += "D" + randomDate.strftime("%d%m%y")
     shorthand += "G" + Glider.getRandomTrigraphOrCompNo(db)
     shorthand += "L" + Location.getRandomLocation(db)[:3]
     nFlights = randint(1,4);
     shorthand += "N" + str(nFlights)
     shorthand += "P" + str(randint(1,2))
     shorthand += "T"
     for i in range(nFlights):
         shorthand += "%02d" % randint(3, 20)
     
     shorthand += random.choice("WA")
     
     shorthand = shorthand.upper()
     
     shorthand += "NRandom Notes " if random.choice([True, False]) else ""
     
     return shorthand
Exemple #34
0
    def take_off(self,init_alt_in_meter):
        while not self.vehicle.is_armable:
            time.sleep(DELAY_HALF_SEC)
            print "Waiting for arming"

        self.vehicle.mode = VehicleMode("GUIDED")
        self.vehicle.armed = True
        while not self.vehicle.armed:
            time.sleep(DELAY_HALF_SEC)
        meter  = init_alt_in_meter
        self.vehicle.simple_takeoff(meter)
        loc = Location()
        loc.setFromVehicleLocation(self.vehicle.location.global_relative_frame)
        while not loc.is_right_alt(meter):
            loc.setFromVehicleLocation(self.vehicle.location.global_relative_frame)
            time.sleep(DELAY_HALF_SEC)
    def loadDistance(self, graph):
        locationQueue = []
        #open file and create file reader with a delimiter of ","
        with open('DistanceTable.csv') as file:
            fileReader = csv.reader(file, delimiter=",")
            #Time Complexity: O(n) Space Complexity:O(n)
            for row in fileReader:
                #Clean data in file by removing \n in csv file
                row[0] = row[0].replace("\n", "")
                row[1] = row[1].replace("\n", "")
                #create location object and add it to list
                location = Location(row[0], row[1], row[2:])
                locationQueue.append(location)
                # add a vertex to the graph using the location address
                vert = Vertex(location._address)
                graph.add_node(vert)

    #adds all distance data to graph from bidirectional matrix
    # A locationQueue was needed to keep an ordered set of addresses to loop through.
    # HashTable does not keep the address ordered and makes it inconsistent to loop through
        count = 0
        #Time Complexity: O(n^3) Space Complexity:O(n)
        while (count < len(locationQueue)):
            for location in locationQueue:  #For each location in list
                if location._distances[
                        count] is not '':  #Adds distance data that is not left blank
                    for key in graph._graph_dict.keys(
                    ):  #retireves keys from dictionary in graph
                        if (key.name == location._address
                            ):  #check to see if the location matches
                            vert_a = key
                        if (key.name == locationQueue[count]._address):
                            vert_b = key
                    #Adds vertexes to graph. Since graph is undirected only half of the matrix needs to be scanned in
                    graph.add_undirectedEdge(vert_b, vert_a,
                                             location._distances[count])
            count = count + 1
        #returns the altered graph and stores it for later reference
        self._graph = graph
        return graph
Exemple #36
0
def traceWalk(drunkKinds, numSteps):
    styleChoice = styleIterator(('k+', 'r^', 'mo'))
    f = Field()
    for dClass in drunkKinds:
        d = dClass()
        f.addDrunk(d, Location(0, 0))
        locs = []
        for s in range(numSteps):
            f.moveDrunk(d)
            locs.append(f.getLoc(d))
        xVals, yVals = [], []
        for loc in locs:
            xVals.append(loc.getX())
            yVals.append(loc.getY())
        curStyle = styleChoice.nextStyle()
        plt.plot(xVals, yVals, curStyle,
                   label = dClass.__name__)
    plt.title('Spots Visited on Walk ('
                + str(numSteps) + ' steps)')
    plt.xlabel('Steps East/West of Origin')
    plt.ylabel('Steps North/South of Origin')
    plt.legend(loc = 'best')
    def take_off(self,init_alt_in_meter):
        while not self.vehicle.is_armable:
            time.sleep(DELAY)
            print "Waiting for arming"

        #here the drone is armable and move to the next step
        self.vehicle.mode = VehicleMode("GUIDED")
        self.vehicle.armed = True
        while not self.vehicle.armed:
            time.sleep(DELAY)
        #after all the atriubute is set the simple take off can be done
        self.vehicle.simple_takeoff(init_alt_in_meter)
        loc = Location()
        loc.setFromVehicleLocation(self.vehicle.location.global_relative_frame)
        while not loc.is_right_alt(init_alt_in_meter):
            loc.setFromVehicleLocation(self.vehicle.location.global_relative_frame)
            time.sleep(DELAY)
Exemple #38
0
    def __init__(self, filename=None):
        """Class constructor.

		Args:
			filename (str): name of the .txt file to generate log from (default = None)
		"""
        if filename is None:
            pass
        else:
            try:
                file = open(filename, 'r')
            except:
                raise

            for entry in file.readlines():
                try:
                    data = json.loads(entry)
                    loc = Location(data['name'], float(data['latitude']),
                                   float(data['longitude']))
                    idx = data['user_id']
                    self.add_customer(loc, idx)
                except:
                    raise
    def packet_in_air(self, packet: UplinkMessage):
        self.num_of_packets_send += 1
        # id = packet.node.id
        # if id not in self.color_per_node:
        #     self.color_per_node[id] = '#' + random.choice(AirInterface.color_values) + random.choice(
        #         AirInterface.color_values) + random.choice(AirInterface.color_values) + random.choice(
        #         AirInterface.color_values) + random.choice(AirInterface.color_values) + random.choice(
        #         AirInterface.color_values)

        from_node = packet.node
        node_id = from_node.id
        # Calculate RSSI and SNR from node to each gateway
        for gw in self.gateways:
            d = Location.distance(gw.location, from_node.location)
            rss = self.prop_model.tp_to_rss(from_node.location.indoor,
                                            packet.lora_param.tp, d)
            if node_id not in self.prop_measurements:
                self.prop_measurements[node_id] = {}
            if gw.id not in self.prop_measurements[node_id]:
                self.prop_measurements[node_id][gw.id] = {
                    'rss': [],
                    'snr': [],
                    'time': []
                }
            packet.rss[gw.id] = rss
            snr = self.snr_model.rss_to_snr(rss)
            packet.snr[gw.id] = snr
            packet.collided[
                gw.
                id] = False  # collisions are checked later, once the packet is already in the air

            self.prop_measurements[node_id][gw.id]['time'].append(self.env.now)
            self.prop_measurements[node_id][gw.id]['rss'].append(rss)
            self.prop_measurements[node_id][gw.id]['snr'].append(snr)

        self.packages_in_air.append(packet)
        gc.collect()
Exemple #40
0
def get_location(filename, nc, coord_vars):
    """Create a location object for a camps data object from
    the location information in a netCDF4 file.
    """

    if file_cache[filename] and 'location' in file_cache[filename]:
        return file_cache[filename]['location']

    locations = []
    for c in coord_vars:
        try:
            nc_coord = nc.variables[c]
        except:
            logging.warning("can't find " + str(c))
            continue
        coord_len = len(nc_coord[:])
        if coord_len > 2:  # location data
            locations.append(nc_coord)

    location_obj = Location(*locations)
    if location_obj.location_data:
        file_cache[filename]['location'] = location_obj

    return location_obj
Exemple #41
0
def run_parallel(nodes,
                 sf,
                 payload_size,
                 tx_intervall,
                 num_simulations,
                 cell_size,
                 mac,
                 path_loss_variances,
                 confirmed_messages,
                 adr,
                 std_jitter=0,
                 guard_time=0):
    resume_from_simulation, locations_per_simulation, _results, results_file = setup(
        nodes, payload_size, tx_intervall, cell_size, mac, sf, std_jitter,
        guard_time)
    for n_sim in range(resume_from_simulation, num_simulations):
        print(
            '\t\t\t\t\tSimulation: {} nodes, SF {}, TX-Interval {} min, Payload {} B,   #{} '
            .format(nodes, sf, tx_intervall, payload_size, n_sim + 1))
        locations = locations_per_simulation[n_sim]
        path_loss_variance = path_loss_variances[0]
        # transmission rate is going to be outdated
        gateway_location = Location(cell_size, indoor=False, gateway=True)
        #r_list = cProfile.run('SimulationProcess.run(locations, mac, payload_size, tx_intervall, path_loss_variance, gateway_location, nodes, sf,confirmed_messages, adr, std_jitter, guard_time)')
        r_list = SimulationProcess.run(locations, mac, payload_size,
                                       tx_intervall, path_loss_variance,
                                       gateway_location, nodes, sf,
                                       confirmed_messages, adr, std_jitter,
                                       guard_time)
        gc.collect()

        _sim_idx = n_sim
        process_results(_results, nodes, _sim_idx, r_list)
        # update Results
        _results['idx_of_simulations_done'] = n_sim
        pickle.dump(_results, open(results_file, "wb"))
Exemple #42
0
 def __init__(self):
     if RideManager._instance is not None:
         raise Exception("There is already an instance!")
     else:
         self.riders = {
             200:
             User(Location("3780 Arbutus", 49.2474624, -123.1532338),
                  Location("6133 University", 49.2664779, -123.2520534),
                  False, None, None, 9),
             300:
             User(Location("800 Robson", 49.2819229, -123.1211844),
                  Location("6133 University", 49.2664779, -123.2520534),
                  False, None, None, 9)
         }
         self.drivers = {
             400:
             User(Location("6800 Cambie", 49.227107, -123.1163085),
                  Location("6133 University", 49.2664779, -123.2520534),
                  True, 4, "911 DAFUZZ", 9),
         }
         self.rides = []
         RideManager._instance = self
         self.find_rides()
Exemple #43
0
    def countInDict(self, starting):
        # print "%" * 20
        for i in range(0, len(self.bin1)):
            if (starting.has_key(self.bin1[i])):
                starting[self.bin1[i]] = (starting[self.bin1[i]][0] + 1,
                                          list(starting[self.bin1[i]][1] +
                                               [Location(1, i)]))
            else:
                starting[self.bin1[i]] = (1, [Location(1, i)])
            if (starting.has_key(self.bin2[i])):
                starting[self.bin2[i]] = (starting[self.bin2[i]][0] + 1,
                                          list(starting[self.bin2[i]][1] +
                                               [Location(2, i)]))
            else:
                starting[self.bin2[i]] = (1, [Location(2, i)])

            if (starting.has_key(self.bin3[i])):
                starting[self.bin3[i]] = (starting[self.bin3[i]][0] + 1,
                                          list(starting[self.bin3[i]][1] +
                                               [Location(3, i)]))
            else:
                starting[self.bin3[i]] = (1, [Location(3, i)])

        return starting
Exemple #44
0
    def test_num_modules(self):
        location = Location('Dublin', "culture1", 30)

        location.add_team(Team('test_team1', 1))
        location.teams[0].module = Module('test_module1', 600)
        
        self.assertTrue(location.num_modules() == 1)

        location.add_team(Team('test_team2', 1))
        location.teams[1].module = Module('test_module2', 400)

        location.add_team(Team('test_team3', 1))
        location.teams[2].module = Module('test_module3', 200)

        self.assertTrue(location.num_modules() == 3)

        location.add_team(Team('test_team4', 1))
        location.teams[3].module = Module('test_module4', 600)

        location.add_team(Team('test_team5', 1))
        location.teams[4].module = Module('test_module5', 800)

        self.assertTrue(location.num_modules() == 5)
Exemple #45
0
class NetworkManager:
    def __init__(self, host, port, username, password):
        self.origin = Location()
        self.origin.set(130, 71, 83)
        self.range = Location()
        self.range.set(10, 10, 10)
        self.X = 0
        self.Y = 0
        self.Z = 0
        self.bot = Bot()
        self.dispatch = PacketDispatch(self)
        self.buff = Buffer()
        self.packetSend = []
        self.sendPacket = PacketSend(self)
        self.printable = True
        self.receiveSize = 1024
        self.compressionThreshold = -1
        self.username = username

        self.HOST = host
        self.PORT = port

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.settimeout(None)
        try:
            self.s.connect((self.HOST, self.PORT))
        except socket.error:
            print("Connection refused")
            thread.interrupt_main()
            exit()

    def recv(self, length):
        data = ""
        request = length
        while length > self.receiveSize:
            data += self.s.recv(self.receiveSize)
            length -= self.receiveSize
        data += self.s.recv(length)
        if len(data) < request:
            # Attempt to get the data again
            data += self.s.recv(length)
        if len(data) < request:
            # because the socket is blocking, this would indicate a dead connection
            raise Exception("Requested " + str(request) + " bytes but recieved " + str(len(data)))
            thread.interrupt_main()
            exit()
        return data

    def send(self, data):
        data.networkFormat(self.compressionThreshold)
        # print("->" + data.string.encode("hex"));
        try:
            self.s.send(data.string)
        except socket.error:
            print("Connection terminated.")
            thread.interrupt_main()
            exit()

    def readNewData(self):
        self.buff.addRaw(self.recv(self.receiveSize))

    def handleNewPackets(self, source=None):
        packet = self.buff.getNextPacket(self.compressionThreshold, source)
        # while packet:
        # handle packet here
        if isinstance(packet, Buffer) and len(packet.string) > 0:
            packetId = hex(packet.readVarInt())
            while len(packetId) < 4:
                packetId = "0x0" + packetId[2:]
            packetId = packetId.upper().replace("X", "x")
            # print("<-"+packetId+": "+packet.string.encode("hex"));
            getattr(self.dispatch, "Packet" + packetId)(packet)
            # 	packet = self.buff.getNextPacket(self.compressionThreshold != -1)

    def sendWaitingPackets(self):
        for packet in self.packetSend:
            self.send(packet)
            self.packetSend.remove(packet)
            # self.packetSend = []

    def networkLoop(self):
        while True:
            self.handleNewPackets(self)
            self.sendWaitingPackets()

    def beginUpdatePositions(self):
        while True:
            try:
                thread.start_new_thread(self.updatePosition, ())
            except KeyboardInterrupt:
                self.s.close()
                thread.interrupt_main()
                exit()
            time.sleep(0.05)

            # updates location every 50 ms

    def updatePosition(self):
        bot = self.dispatch.bot
        location = bot.location
        if bot.location.x != None:
            bot.location.x += self.X
        if bot.location.y != None:
            bot.location.y += self.Y
        if bot.location.z != None:
            bot.location.z += self.Z

        if location.x != None and location.y != None and location.z != None:
            self.sendPacket.Packet0x04(location.x, location.y, location.z, bot.onGround)
        return True

    def login(self):
        # Send handshake
        self.sendPacket.Packet0x00_0(self.HOST, self.PORT)

        # Send login
        self.sendPacket.Packet0x00_1(self.username)

        # Start main network loop
        try:
            thread.start_new_thread(self.networkLoop, ())
        except KeyboardInterrupt:
            self.s.close()
            print("interupt 1")
            exit()

            # Start position update loop
        try:
            thread.start_new_thread(self.beginUpdatePositions, ())
        except KeyboardInterrupt:
            self.s.close()
            print("interupt 2")
            exit()

        self.dispatch.bot.loggedIn = True
Exemple #46
0
 def test_location(self):
     self.piece.location = Location(x=5, y=10)
     self.assertEqual(self.piece.location, Location(x=5, y=10))
    def test_setFromVehicleLocation(self):
        #test Vehicle and after that check the location
        vec= Vec(0,0,0)
        loc = Location()
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        vec.alt == loc.altitude and
                        vec.lat == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,0,0)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        vec.alt == loc.altitude and
                        vec.lat == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,0)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        vec.alt == loc.altitude and
                        vec.lat == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,POSITIVE_NUMBER)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        vec.alt == loc.altitude and
                        vec.lat == loc.latitude)

        vec= Vec(LIMIT_NUMBER_LATITUDE+1,LIMIT_NUMBER_LONGITUDE,POSITIVE_NUMBER)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        vec.alt == loc.altitude and
                        LIMIT_NUMBER_LATITUDE == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE+1,POSITIVE_NUMBER)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(LIMIT_NUMBER_LONGITUDE == loc.longitude and
                        vec.alt == loc.altitude and
                        vec.lat == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,CHAR_NUMBER)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        float(vec.alt) == loc.altitude and
                        vec.lat == loc.latitude)
        vec= Vec(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,CHARACTER)
        loc.setFromVehicleLocation(vec)
        self.assertTrue(vec.lon == loc.longitude and
                        0 == loc.altitude and
                        vec.lat == loc.latitude)
Exemple #48
0
 def up(self,init_alt_in_meter):
     if(self.is_first_function):
         head = self.vehicle.heading/ANGLE_FIX
         self.is_first_function = False
     else:
         head= self.vehicle.heading
     loc = Location()
     loc1 = Location()
     loc.setFromVehicleLocation(self.vehicle.location.global_frame)
     loc1.setFromVehicleLocation(self.vehicle.location.global_frame)
     loc.set_altitude(loc.get_altitude()+init_alt_in_meter)
     location_global = LocationGlobal(loc.latitude,loc.longitude,loc.altitude)
     self.vehicle.simple_goto(location_global)
     while not loc1.is_right_alt(loc.altitude):
         loc1.setFromVehicleLocation(self.vehicle.location.global_frame)
         self.condition_yaw(head)
         time.sleep(DELAY)
     if init_alt_in_meter > 0:
         print "complete function up"
     else:
         print "complete function down"
 def test_displayLocation(self):
     loc = Location()
     loc.displayLocation()
     loc= Location(LIMIT_NUMBER_LATITUDE,0,0)
     loc.displayLocation()
     loc=Location(-LIMIT_NUMBER_LATITUDE,0,0)
     loc.displayLocation()
     loc=Location(LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,0)
     loc.displayLocation()
     loc=Location(LIMIT_NUMBER_LATITUDE,-LIMIT_NUMBER_LONGITUDE,0)
     loc.displayLocation()
     loc=Location(-LIMIT_NUMBER_LATITUDE,LIMIT_NUMBER_LONGITUDE,0)
     loc.displayLocation()
     loc=Location(-LIMIT_NUMBER_LATITUDE,-LIMIT_NUMBER_LONGITUDE,0)
     loc.displayLocation()
     self.assertTrue(1)
Exemple #50
0
 def test_east_edge_bottom(self):
     loc_target = Location(6, 5)
     self.assertTrue(loc_target in EAST_EDGE)
Exemple #51
0
 def test_west_edge_bottom(self):
     loc_target = Location(0, 5)
     self.assertTrue(loc_target in WEST_EDGE)
 def test_equalsTo(self):
     loc = Location()
     loc1 = Location()
     #---------------latitude--------------------#
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_latitude(LIMIT_NUMBER_LATITUDE)
     self.assertFalse(loc.equalsTo(loc1))
     loc.set_latitude(LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_latitude(LIMIT_NUMBER_LATITUDE+1)
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_latitude(LIMIT_NUMBER_LATITUDE+1)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_latitude(-LIMIT_NUMBER_LATITUDE)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_latitude(-LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_latitude(-LIMIT_NUMBER_LATITUDE-1)
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_latitude(-LIMIT_NUMBER_LATITUDE-1)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_latitude(CHARACTER)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_latitude(CHARACTER)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_latitude(CHAR_NUMBER)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_latitude(CHAR_NUMBER)
     self.assertTrue(loc.equalsTo(loc1))
     #print "%f   %f " % ( loc.longitude, loc.latitude)
     #print "%f   %f " % ( loc1.longitude, loc1.latitude)
     #---------------longitude-------------------------#
     loc1.set_longitude(LIMIT_NUMBER_LONGITUDE)
     self.assertFalse(loc.equalsTo(loc1))
     loc.set_longitude(LIMIT_NUMBER_LONGITUDE)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_longitude(LIMIT_NUMBER_LONGITUDE+1)
     #print "%f   %f " % ( loc.longitude, loc.latitude)
     #print "%f   %f " % ( loc1.longitude, loc1.latitude)
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_longitude(LIMIT_NUMBER_LONGITUDE+1)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_longitude(-LIMIT_NUMBER_LONGITUDE)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_longitude(-LIMIT_NUMBER_LONGITUDE)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_longitude(-LIMIT_NUMBER_LONGITUDE-1)
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_longitude(-LIMIT_NUMBER_LONGITUDE-1)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_longitude(CHARACTER)
     self.assertTrue(loc.equalsTo(loc1))
     loc1.set_longitude(CHARACTER)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_longitude(CHAR_NUMBER)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_longitude(CHAR_NUMBER)
     self.assertTrue(loc.equalsTo(loc1))
     #-------------altitude--------------------#
     loc.set_altitude(CHARACTER)
     self.assertTrue(loc.equalsTo(loc1))
     loc.set_altitude(CHAR_NUMBER)
     self.assertFalse(loc.equalsTo(loc1))
     loc1.set_altitude(CHAR_NUMBER)
     self.assertTrue(loc.equalsTo(loc1))
Exemple #53
0
 def test_east_edge_top(self):
     loc_target = Location(6, 1)
     self.assertTrue(loc_target in EAST_EDGE)
 def test_set_latitude(self):
     #create object location
     loc = Location()
     #set the default location
     loc.set_latitude(0)
     self.assertTrue(loc.get_latitude() == 0)
     #set latitude limit positive number
     loc.set_latitude(LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.get_latitude() == LIMIT_NUMBER_LATITUDE)
     #check is success the set on the latitude the underscore limit
     loc.set_latitude(-LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.get_latitude() == -LIMIT_NUMBER_LATITUDE)
     #check if the number that not in the limits set the closest number limit.
     loc.set_latitude(LIMIT_NUMBER_LATITUDE+1)
     self.assertEqual(loc.get_latitude(),LIMIT_NUMBER_LATITUDE)
     loc.set_latitude(-LIMIT_NUMBER_LATITUDE-1)
     self.assertEqual(loc.get_latitude(),-LIMIT_NUMBER_LATITUDE)
     #check if the latitude set a character when it's character - set zero
     loc.set_latitude(CHARACTER)
     self.assertEqual(loc.get_latitude(),0)
     #when it's number - set the number as float
     loc.set_latitude(CHAR_NUMBER)
     self.assertEqual(loc.get_latitude(),float(CHAR_NUMBER))
Exemple #55
0
 def test_index_of_2_is_3_0(self):
     loc = BoardLocations.gen_from_index(2)
     loc_target = Location(x=3, y=0)
     self.assertEqual(loc, loc_target)
 def test_is_equals_lat(self):
     loc = Location()
     self.assertTrue(loc.is_equals_lat(0))
     self.assertFalse(loc.is_equals_lat(1))
     self.assertFalse(loc.is_equals_lat(0.05))
     self.assertFalse(loc.is_equals_lat(-0.05))
     self.assertFalse(loc.is_equals_lat(-0.06))
     self.assertTrue(loc.is_equals_lat(-0.04))
     self.assertTrue(loc.is_equals_lat(-0.03))
     self.assertTrue(loc.is_equals_lat(-0.02))
     self.assertTrue(loc.is_equals_lat(-0.01))
     self.assertTrue(loc.is_equals_lat(+0.04))
     self.assertTrue(loc.is_equals_lat(+0.03))
     self.assertTrue(loc.is_equals_lat(+0.02))
     self.assertTrue(loc.is_equals_lat(+0.01))
     self.assertFalse(loc.is_right_alt(CHARACTER))
     self.assertFalse(loc.is_right_alt(CHAR_NUMBER))
     loc.set_latitude(LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+1))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+0.05))
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.05))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.06))
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.04))
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.03))
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.02))
     self.assertTrue(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE-0.01))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+0.04))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+0.03))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+0.02))
     self.assertFalse(loc.is_equals_lat(LIMIT_NUMBER_LATITUDE+0.01))
     loc.set_latitude(-LIMIT_NUMBER_LATITUDE)
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+1))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE-0.05))
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.05))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.06))
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.04))
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.03))
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.02))
     self.assertTrue(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE+0.01))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE-0.04))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE-0.03))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE-0.02))
     self.assertFalse(loc.is_equals_lat(-LIMIT_NUMBER_LATITUDE-0.01))
 def test_set_longitude(self):
     loc=Location()
     loc.set_longitude(0)
     #check if the longitude equal to zero
     self.assertEqual(loc.get_longitude(),0)
     #set function change to limit  number
     loc.set_longitude(LIMIT_NUMBER_LONGITUDE)
     self.assertEqual(loc.get_longitude(),LIMIT_NUMBER_LONGITUDE)
     #out of limit number LIMIT_NUMBER_LONGITUDE
     loc.set_longitude(LIMIT_NUMBER_LONGITUDE+1)
     self.assertEqual(loc.get_longitude(),LIMIT_NUMBER_LONGITUDE)
     #set lower limit
     loc.set_longitude(-LIMIT_NUMBER_LONGITUDE)
     self.assertEqual(loc.get_longitude(),0)
     #set less then lower limit-> set the lower limit
     loc.set_longitude(-LIMIT_NUMBER_LONGITUDE-1)
     self.assertEqual(loc.get_longitude(),0)
     #check if the latitude set a character
     loc.set_longitude(CHARACTER)
     self.assertEqual(loc.get_longitude(),0)
     #check if the latitude set a character number
     loc.set_longitude(CHAR_NUMBER)
     self.assertEqual(loc.get_longitude(),float(CHAR_NUMBER))
 def test_is_equals_lon(self):
     loc = Location()
     self.assertTrue(loc.is_equals_lon(0))
     self.assertFalse(loc.is_equals_lon(1))
     self.assertFalse(loc.is_equals_lon(0.05))
     self.assertFalse(loc.is_equals_lon(-0.05))
     self.assertFalse(loc.is_equals_lon(-0.06))
     self.assertFalse(loc.is_equals_lon(-0.04))
     self.assertFalse(loc.is_equals_lon(-0.03))
     self.assertFalse(loc.is_equals_lon(-0.02))
     self.assertFalse(loc.is_equals_lon(-0.01))
     self.assertTrue(loc.is_equals_lon(+0.04))
     self.assertTrue(loc.is_equals_lon(+0.03))
     self.assertTrue(loc.is_equals_lon(+0.02))
     self.assertTrue(loc.is_equals_lon(+0.01))
     self.assertFalse(loc.is_equals_lon(CHARACTER))
     self.assertFalse(loc.is_equals_lon(CHAR_NUMBER))
     loc.set_longitude(LIMIT_NUMBER_LONGITUDE)
     self.assertTrue(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+1))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+0.05))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.05))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.06))
     self.assertTrue(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.04))
     self.assertTrue(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.03))
     self.assertTrue(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.02))
     self.assertTrue(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE-0.01))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+0.04))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+0.03))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+0.02))
     self.assertFalse(loc.is_equals_lon(LIMIT_NUMBER_LONGITUDE+0.01))
Exemple #59
0
from Location import Location
from Weather import Weather
from datetime import datetime
import time
weatherKey = 'XXXXXXXXXXXXX'
IPKey = 'XXXXXXXXXXX'
units = 'imperial'
syncTime = False;

while True:
    location = Location(IPKey).getLocation()
    weatherTime = Weather(weatherKey, location).getTime()
    actualWeather = Weather(weatherKey, location).getWeather()
    actualTime = datetime.now()
    forcastTime = datetime.fromtimestamp(Weather(weatherKey, location).getForecast(units, 1)[0])
    forcastWeather = Weather(weatherKey, location).getForecast(units, 1)[1][0]['main']
    print('Real time: '+str(actualTime))
    print('App time: '+str(weatherTime))
    print('Current weather:'+actualWeather)
    print('Forecast time: '+str(forcastTime))
    print('Forecast Weather: '+forcastWeather)


    if forcastWeather == 'Rain':
        print('Bring Umbrella\n')
    elif forcastWeather == 'Clouds':
        print('Enjoy the cloudy weather!\n')
    elif forcastWeather == 'Clear':
        print('Nice weather!\n')
    else:
        print(forcastWeather)
 def test_set_altitude(self):
     loc = Location()
     #set the default location
     self.assertEqual(loc.get_altitude(),0)
     loc.set_altitude(0)
     self.assertEqual(loc.get_altitude(),0)
     #check character -> set zero
     loc.set_altitude(CHARACTER)
     self.assertEqual(loc.get_altitude(),0)
     #check character number -> convert to the number
     loc.set_altitude(CHAR_NUMBER)
     self.assertEqual(loc.get_altitude(),float(CHAR_NUMBER))