Esempio n. 1
0
    def parseImageFile(self, guest):
        def checkTreeinfo(url):
            url = ("%s/%s" % (url, ".treeinfo")) if url[-1] != "/" else (
                "%s%s" % (url, ".treeinfo"))

            try:
                httpRequest = urllib2.urlopen(url)
                return True

            except:
                return False

        path = self.parseTextElement(guest, "image-file")

        if path and path.startswith("http://"):
            if checkTreeinfo(path):
                return Location.HttpDir(path)

            elif path.endswith(".iso"):
                return Location.HttpIso(path)

        elif path and path.endswith(".iso"):
            return Location.LocalIso(path)
        else:
            Logging.errorExit("Image file of all guests must be set.")
Esempio n. 2
0
 def saveConfig(self, config, fname=None):
     if not fname:
         fname = self.conf_file
     f = open(fname, "w")
     Location.getJsonModule().dump(config, f, indent=2)
     f.write("\n")  # json doesn't include a trailing newline?
     f.close()
Esempio n. 3
0
class Taxi:
    ##	The constructor
    #	@param taxiInfo dictinary with the Taxi datas
    #	@param mapManagerTaxi map manager for know vexteces and streets
    def __init__(self, taxiInfo, mapManagerTaxi):
        self.odometer = taxiInfo["odometer"]
        #determine if the taxi have alreay accept a request
        if taxiInfo["destination"] != None:
            self.destination = CabRequest(taxiInfo["destination"],
                                          mapManagerTaxi)
        else:
            self.destination = None
        #initialise locations
        self.loc_now = Location(taxiInfo["loc_now"], mapManagerTaxi)
        self.loc_prior = Location(taxiInfo["loc_prior"], mapManagerTaxi)

    ##	Return the Taxi list to dictionary format
    def toDictFormat(self):
        #initialise the taxi dictionary
        taxi = {}
        taxi["odometer"] = self.odometer
        #determine if the taxi have alreay accept a request
        if self.destination == None:
            taxi["destination"] = None
        else:
            taxi["destination"] = self.destination.toDictFormat()
        taxi["loc_now"] = self.loc_now.toDictFormat()
        taxi["loc_prior"] = self.loc_prior.toDictFormat()
        return taxi
Esempio n. 4
0
def initLogging(cgi=False):
    
    conf = ConfigParser.RawConfigParser()
    conf.read(Location.getInstance().toAbsolutePath("logging.conf"))
    
    logger = logging.getLogger()
    logger.setLevel(logging._levelNames[conf.get("logger_root", "level")]) # Weirdly, there's no supported method to get a level from a name...
    
    if cgi:
        # Make sure all created files are writable.
        os.umask(0)
    else:
        # Set up the console logger.
        formatter_name = conf.get("handler_consoleHandler", "formatter")
        format = conf.get("formatter_%s" % (formatter_name), "format")
        formatter = logging.Formatter(format)
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    # Set up the file logger.
    filename = Location.getInstance().toAbsolutePath(os.path.join("logs", conf.get("handler_logfileHandler", "filename")))
    max_bytes = conf.getint("handler_logfileHandler", "max_bytes")
    backup_count = conf.getint("handler_logfileHandler", "backup_count")
    formatter_name = conf.get("handler_logfileHandler", "formatter")
    format = conf.get("formatter_%s" % (formatter_name), "format")
    formatter = logging.Formatter(format)
    handler = logging.handlers.RotatingFileHandler(filename, "a", max_bytes, backup_count)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
Esempio n. 5
0
 def cal_user_venue_distance(self, user_id1, venue_id1):
     user1 = self.hliData.dictUserRes[user_id1]
     venue1 = self.hliData.dictVenueRes[venue_id1]
     loc1 = Location(user1.latitude, user1.longitude)
     loc2 = Location(venue1.latitude, venue1.longitude)
     dis = Location.cal_loc_distance_euclidean(loc1, loc2)
     return dis
Esempio n. 6
0
class Taxi:
	##	The constructor
	#	@param taxiInfo dictinary with the Taxi datas
	#	@param mapManagerTaxi map manager for know vexteces and streets
	def __init__(self, taxiInfo, mapManagerTaxi):
		self.odometer = taxiInfo["odometer"]
		#determine if the taxi have alreay accept a request
		if taxiInfo["destination"] != None:
			self.destination = CabRequest(taxiInfo["destination"], mapManagerTaxi)
		else:
			self.destination = None
		#initialise locations
		self.loc_now = Location(taxiInfo["loc_now"], mapManagerTaxi)
		self.loc_prior = Location(taxiInfo["loc_prior"], mapManagerTaxi)

	##	Return the Taxi list to dictionary format
	def toDictFormat(self):
		#initialise the taxi dictionary
		taxi = {}
		taxi["odometer"] = self.odometer
		#determine if the taxi have alreay accept a request
		if self.destination == None:
			taxi["destination"] = None
		else:
			taxi["destination"] = self.destination.toDictFormat()
		taxi["loc_now"] = self.loc_now.toDictFormat()
		taxi["loc_prior"] = self.loc_prior.toDictFormat()
		return taxi
Esempio n. 7
0
def Opt2(tour: List[Location.Location]):

    oldTour = tour.copy()
    newTour = tour.copy()
    shortestDist = Location.FindTourLength(tour)

    i = 0
    j = 0
    ij = len(tour)**2
    while (i < len(tour)):
        j = i + 1
        if miscGlobal.specialPrint == True:
            Funcs.PrintProgressBar(i * j, ij)
        while (j < len(tour)):
            if (time.process_time() - miscGlobal.start
                ) > miscGlobal.maxTime:  #A little bit spaghetti
                if miscGlobal.specialPrint == True:
                    print()
                return oldTour
            newTour = oldTour.copy()
            TwoOptSwap(i, j, oldTour, newTour)
            # print('Elements: ' + str(len(newTour)))
            newDist = Location.FindTourLength(newTour)
            # print('CurDist: ' + str(newDist))
            if (newDist < shortestDist):
                oldTour = newTour
                shortestDist = newDist
                yield oldTour
                # print("\tNew shorter dist: " + str(shortestDist))
            j += 1
        i += 1
    if miscGlobal.specialPrint == True:
        Funcs.PrintProgressBar(100, 100)
        print()
    return oldTour
Esempio n. 8
0
def reassTests():
    eax = Location(reg="eax")
    ebx = Location(reg="ebx")
    r1 = Location(reg="r1")
    a = XorAction(eax, ebx)
    b = a.reassigned({eax: r1})
    print(a)
    print(b)
Esempio n. 9
0
def choose(value):
    if value == 1:
        HelloWolrd.main()
    elif value == 2:
        Location.main()
    elif value == 3:
        print '3 - Not implemented'
    else:
        print 'Invalid option'
	return;
Esempio n. 10
0
	def __init__(self, taxiInfo, mapManagerTaxi):
		self.odometer = taxiInfo["odometer"]
		#determine if the taxi have alreay accept a request
		if taxiInfo["destination"] != None:
			self.destination = CabRequest(taxiInfo["destination"], mapManagerTaxi)
		else:
			self.destination = None
		#initialise locations
		self.loc_now = Location(taxiInfo["loc_now"], mapManagerTaxi)
		self.loc_prior = Location(taxiInfo["loc_prior"], mapManagerTaxi)
Esempio n. 11
0
 def __init__(self, taxiInfo, mapManagerTaxi):
     self.odometer = taxiInfo["odometer"]
     #determine if the taxi have alreay accept a request
     if taxiInfo["destination"] != None:
         self.destination = CabRequest(taxiInfo["destination"],
                                       mapManagerTaxi)
     else:
         self.destination = None
     #initialise locations
     self.loc_now = Location(taxiInfo["loc_now"], mapManagerTaxi)
     self.loc_prior = Location(taxiInfo["loc_prior"], mapManagerTaxi)
Esempio n. 12
0
def tweet(odict, creature):
    
    logger = logging.getLogger()
    logger.info("Posting %s as %s..." % (creature.getImagePath(), creature.getFullPageURL()))
    creds = Location.getJsonModule().load(open(Location.getInstance().toAbsolutePath(".twitter.json")))
    twitter = Twython(creds["app"], creds["app_secret"], creds["token"], creds["token_secret"])
    photo = open(creature.getImagePath(), 'rb')
    if (not odict.get("no-op", False)):
        response = twitter.upload_media(media=photo)
        response = twitter.update_status(status=creature.getFullPageURL(), media_ids=[response['media_id']])
        logger.info("Posted as %s." % (response["id_str"]))
Esempio n. 13
0
 def get_all_locations(self, cur_user):
     photo_list = []
     note_list = []
     loc1 = Location.Location("Westport", 41.512069, -71.069369, photo_list,
                              note_list)
     loc2 = Location.Location("California", 12.512069, -110.069369,
                              photo_list, note_list)
     loc3 = Location.Location("Tampa", 100.512069, -3.069369, photo_list,
                              note_list)
     loc_list = [loc1, loc2, loc3]
     return loc_list
Esempio n. 14
0
File: map.py Progetto: pab3507/RIT
 def addStop(self, name, distanceToNext):
     """
     This adds a stop for the train route.
     """
     if self.startLocation is None:
         self.startLocation = Location(name, None, 0)
     else:
         currStop = self.startLocation
         while currStop.next is not None:
             currStop = currStop.next
         currStop.distanceToNext = distanceToNext
         currStop.next = Location(name, None, 0)
Esempio n. 15
0
def SimulatedAnneal(tour : List[Location.Location], temp : float = 1000000.0, coolRate : float = 0.0003, targetTmp : float = 0.001, maxIts : int = 10000000):
	bestTour = tour
	bestDist = Location.FindTourLength(tour)

	currentTour = bestTour
	currentDist = bestDist

	#Initialise these once
	tourIndex1 = 0
	tourIndex2 = 0

	totalIts = 0

	while temp > targetTmp and totalIts < maxIts:
		if (100 / maxIts * totalIts) % 1 == 0 and miscGlobal.specialPrint == True: #Only write to console when needed
			Funcs.PrintProgressBar(totalIts, maxIts)
			
		if (time.process_time() - miscGlobal.start) > miscGlobal.maxTime: #A little bit spaghetti 
			if miscGlobal.specialPrint == True:
				print()
			return bestTour
		totalIts += 1
		newTour = currentTour.copy()

		while tourIndex1 == tourIndex2: #Make sure that these aren't the same
			tourIndex1 = random.randint(0, len(newTour) - 1)
			tourIndex2 = random.randint(0, len(newTour) - 1)

		#Swap the locations
		Location.Swap(newTour, tourIndex1, tourIndex2)
		
		newDist = Location.FindTourLength(newTour)

		if AcceptProbs(currentDist, newDist, temp) : #Should we accept this new tour
			currentTour = newTour
			currentDist = newDist
			# print('New tour dist: ' + str(currentDist))

		if newDist < bestDist:
			bestTour = newTour
			bestDist = newDist
			yield newTour

		tourIndex1 = tourIndex2 #Makes them both equal so they will be recalculated
		
		temp *= 1 - coolRate
		# print(temp)
	
	if miscGlobal.specialPrint == True:
		Funcs.PrintProgressBar(100, 100)
		print()
	return bestTour
Esempio n. 16
0
class Game:
	def __init__(self):
		self.sender_data = ""
		self.const = Constants()
		self.location = Location(self)

	def handle_keys(self, d):
		if d == str(self.const.KEY_UP):
			self.location.player_move_or_attack(0, -1)
		elif d == str(self.const.KEY_DOWN):
			self.location.player_move_or_attack(0, 1)
		elif d == str(self.const.KEY_LEFT):
			self.location.player_move_or_attack(-1, 0)
		elif d == str(self.const.KEY_RIGHT):
			self.location.player_move_or_attack(1, 0)

		self.game_loop()
		return self.sender_data

	def game_loop(self):
		for obj in self.location.objects:
			if obj.ai:
				obj.ai.take_turn()
		self.render_all()

	def render_all(self):
		sender_data_arr = {}
		sender_data_arr["map_dung"] = self.location.map.get_client_data()
		sender_data_arr["objects"] = []
		for i in range(len(self.location.objects)):
			sender_data_arr["objects"] = self.location.objects[i].get_client_data()
		self.sender_data = str(json.dumps(sender_data_arr))
Esempio n. 17
0
 def get_loc_avg_from_user_friend(cls, hliData, user_id):
     flag = False
     loc = Location()
     locList = []
     checkInList = []
     if (user_id in hliData.dictFriend):
         friendList = hliData.dictFriend[user_id]
         for f in friendList:
             if (f in hliData.dictUserKnowHomeLoc):
                 user = hliData.dictUserKnowHomeLoc[f]
                 locList.append(Location(user.latitude, user.longitude))
         if (len(locList) > 0):
             flag = True
             loc = Location.get_avg_loc(locList)
     return (flag, loc)
Esempio n. 18
0
def analyseSeed(seed, day):
    summer = day
    print(seed)
    busstop = Location.createBusstop()
    mountain = Location.createMountain()
    forest = Location.createForest()
    town = Location.createTown()
    busstop.processDay(seed, summer)
    mountain.processDay(seed, summer)
    forest.processDay(seed, summer)
    town.processDay(seed, summer)
    print(busstop.items)
    print(mountain.items)
    print(forest.items)
    print(town.items)
Esempio n. 19
0
def findBoilerRoomSeed():
    backwoods = Location.createBackwoods()
    mountain = Location.createMountain()
    forest = Location.createForest()
    busstop = Location.createBusstop()
    absolute_path = os.path.dirname(os.path.abspath(__file__))
    print(absolute_path)
    filename = absolute_path + '/boilerRoomResults.txt'
    #f = open(filename,"at")
    for seed in range(44200000, 999999999):
        if seed % 100000 == 0:
            print("searching: " + str(seed))
            f = open(filename, "at")
            f.write("searching: " + str(seed) + '\n')
            f.close()
        #if SeedUtility.dailyLuck(seed,18,17) > 0.099 and not SeedUtility.doesSeedHaveMonsterFloorMines(seed,18,50):
        #backwoods.processDay(seed,15)
        #mountain.processDay(seed,15)

        #leekCount = 0
        #for item in backwoods.items.items():
        #    if item[1] != "Leek":
        #        leekCount = leekCount + 1

        #for item in mountain.items.items():
        #    if item[1] != "Leek":
        #        leekCount = leekCount + 1

        #if leekCount < 4:
        #    continue

        quartz = findFireQuartz(seed)
        if quartz == None:
            continue

        cart = findEarlyCart(seed)
        if cart == None:
            continue

        if cart[0][0] == cart[1][0] and (cart[3][0] == cart[1][0] or quartz[0]
                                         > 0) and (cart[2][0] == cart[1][0]
                                                   or quartz[1] > 0):

            print(str(seed) + " " + str(cart) + " " +
                  str(quartz))  # + " Leeks: " + str(leekCount))
            f = open(filename, "at")
            f.write(str(seed) + " " + str(cart) + " " + str(quartz) + '\n')
            f.close()
Esempio n. 20
0
def GetSolution(problemName : str):
	#Get shortest solution stored for this path
	print(problemName)
	if DoesSolutionExist(problemName):
		cursor.execute(
			"SELECT a.Tour " \
			"FROM Solution a " \
			"LEFT OUTER JOIN Solution b " \
			"ON a.ProblemName = b.ProblemName AND a.TourLength < b.TourLength " \
			f"WHERE a.ProblemName = '{problemName}'" \
		)
		shortestSolution = cursor.fetchone()['Tour'].replace(",", "").replace("-1", "").split()
		print('Shortest path')
		print(shortestSolution)

		#Get all the cities that match up to this tour
		cursor.execute(
			f"""SELECT * FROM Cities WHERE Name = '{problemName}'"""
		)

		cities = cursor.fetchall()
		
		#Construct the path
		path = []
		for ID in shortestSolution:
			for city in cities:
				if int(city['ID']) == int(ID):
					path.append(Location.Location(city['ID'], city['x'], city['y']))
		return path

	else:
		print(f"SOLUTION FOR {problemName} DOES NOT EXIST")
		return ""
Esempio n. 21
0
    def getDistance(self, curr_loc='Dehradun', pick_up_point=(0, 0)):
        l = Location.location(0, 0)

        #'Dehradun' shall be replaced by the original
        #value sent by the Drone GPS

        self.current_location = l.getLatLong(curr_loc)

        #Radius of earth

        R = 6373.0

        lat1 = math.radians(self.current_location[0])
        long1 = math.radians(self.current_location[0])

        lat2 = math.radians(pick_up_point[0])
        long2 = math.radians(pick_up_point[0])

        dlong = abs(long2 - long1)
        dlat = abs(lat2 - lat1)

        a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(
            dlong / 2)**2
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

        self.point_dist = R * c

        return self.point_dist
Esempio n. 22
0
def loadTrafficNodes(fileName):
    reader = csv.reader(open(fileName))

    trafficNodes = []

    for row in reader:
        if (row[0] == "ongeval" or row[0]
                == 'blokkade') and row[14] == "TRUE" and row[40] != '':
            # Important indexes:
            #   situationRecordType         1
            #   situationId                 6
            #   validityOverallStartTime    11
            #   validityOverallEndTime      13
            #   lat lon                     40
            #   alertCLocationName          41

            #   Insert above values into TrafficNode Object

            #   Split the latitude and longitude into two separate variables
            if '|' in row[40]:
                loc = row[40].split('|')[0].split(' ')
            else:
                loc = row[40].split(' ')

            #   Split date and time into two separate variables
            start = row[11].split(' ')
            end = row[13].split(' ')

            #   Add a TrafficNode to the list of trafficNodes
            trafficNodes.append(
                TrafficNode(row[6], row[1],
                            Interval(start[0], start[1], end[0], end[1]),
                            Location(loc[1], loc[0]), row[41]))

    return trafficNodes
Esempio n. 23
0
    def __init__(self, env, name, hospital, displayStatus):
        self.location = Location.Location("", random.randint(1, 9),
                                          random.randint(1, 9))
        self.env = env
        self.name = name
        self.calltime = env.now
        self.priority = random.randint(0, 1)
        self.caretime = random.randint(3, 20)
        self.ambDisTime = None
        self.ambArrTime = None
        self.ambDepTime = None
        self.ambHosTime = None
        self.responder = None
        self.hospital = hospital
        self.displayStatus = displayStatus
        self.status = IncidentStatusPair(self.priority, self.priority,
                                         self.hospital)
        self.status.hid.priority = random.randint(0, 1)
        self.disTime = dict()
        self.arrTime = dict()
        self.depTime = dict()
        self.hosTime = dict()

        if (self.displayStatus):
            print('%s: calls 911 at %.2f.' % (self.name, self.calltime))
Esempio n. 24
0
def main(a, b, c, d):
    values = Location.locate(a, b, c, d)
    first = distance.haversine(values[a], values[c])
    second = distance.haversine(values[b], values[d])
    print "The distance from", a, "to", c, "is", first, "miles"
    print "The distance from", b, "to", d, "is", second, "miles"
    
Esempio n. 25
0
 def getDistance(self):
     l = Location.location(0, 0)
     
     #Radius of earth
     
     R = 6373.0
     
     #gets latitude and longitude of the destination
     
     dest_location = l.getLatLong(self.dest_name) 
     
     #gets latitude and longitude of the source
     
     source_location = l.getLatLong(self.source_name)
     
     lat1 = math.radians(dest_location[0])
     long1 = math.radians(dest_location[1])
     
     lat2 = math.radians(source_location[0])
     long2 = math.radians(source_location[1])
     
     dlong = abs(long2 - long1)
     dlat = abs(lat2 - lat1)
             
     a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlong/2)**2
     c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
     
     self.Order_dist = R*c
     
     return self.Order_dist
Esempio n. 26
0
File: plugin.py Progetto: KDE/silk
def request():
    """Called when plugin data are requested.

    When this function is called, Location data are valid. In this function
    should be set data for provider.
    Data are set with Provider.serProperty(pluginName, key, value) method. This
    method can by called multiple times, all keys are added to this plugin
    datasource.
    At the end, when all data are set, Provider.done(pluginName) method has to
    be called indicating that all data are ready and set.

    Location methods:
    QString getCountryCode();
    QString getCountry();
    QString getCity();
    QString getAddress(); // this method is usefull only when user has chosen
                          // manual configuration of location, otherwise its
                          // return is empty
    QString getLongitude();
    QString getLatitude();
    double getRange();    // range in KM around location for which user wants
                          // information

    Provider methods:
    void setProperty(QString source, QString key, QString value);
    void done(const QString source);
    """
    Provider.setProperty(PLUGIN_NAME, "Hello!", "You are in %s." %
        Location.getCity())
    Provider.done(PLUGIN_NAME)
Esempio n. 27
0
    def checkVenueInDictCityOld(self):
        self.dictCity = GeoMap.load_city_dict()
        self.listVenue = self.loadVenueFromFileFilt()

        cntNo=0
        cnt = 0

        index=0
        totalCnt = len(self.listVenue)
        for venue in self.listVenue:
            cnt = cnt + 1
            #print len(self.dictCity)
            loc = Location(venue.latitude, venue.longitude)
            city = Location.getLocCity(loc, self.dictCity)
            if(city == None):
                #print (venue.latitude, venue.longitude)
                cntNo = cntNo + 1

            index = index + 1
            if(index % 1000 == 0):
                print "%s/%s\tNo:%s/%s" % (index, totalCnt, cntNo, cnt)
            #    break




        print "No: %s/%s" % (cntNo, cnt)
Esempio n. 28
0
 def transformImage(self, img):
     dims = self.getDims()
     ret = Image.new("RGB", dims, "white")
     draw = ImageDraw.Draw(ret)
     font = "courR" + self.args["font"] + ".pil"
     path= Location.getInstance().toAbsolutePath(os.path.join("fonts", font))
     font = ImageFont.load(path)
     (w,h) = draw.textsize(self.args["charset"][-1], font)
     if self.args["mode"] == "L":
         # Convert to grayscale
         values = img.convert("L")
     else:
         # Saturate the color
         values = ImageEnhance.Color(img).enhance(4.0)
     values = values.filter(ImageFilter.MedianFilter(5))
     for y in range(0, dims[1], h):
         for x in range(0, dims[0], w):
             v = values.getpixel((x,y))
             if self.args["mode"] == "L":
                 pct =  v/255.0
                 fill = (0, 0, 0)
             else:
                 pct = sum(v)/765.0
                 fill = v
             vi = int(round(pct * (len(self.args["charset"])-1)))
             draw.text((x,y), self.args["charset"][vi], font=font, fill=fill)
     return ret
Esempio n. 29
0
def checkReward(m):
    '''
	x = [i for i in range(0,m.N)]; 
	plt.plot(x,m.R[0],c='r');
	plt.plot(x,m.R[1],c='b'); 
	plt.plot(x,m.R[2],c='g');  
	plt.legend(['Left','Right','Stay']); 
	plt.show()
	'''

    plots = []
    nRows = int(np.sqrt(len(Location)))
    nCols = nRows
    fig, axarr = plt.subplots(nRows, nCols)
    fig.suptitle("Rewards", fontsize=14)
    for i in range(0, nRows):
        for j in range(0, nCols):
            #print np.reshape(m.R[i*nCols+j], (m.height, m.width)).dtype
            plot = axarr[i][j].imshow(np.reshape(
                m.R[i * nCols + j], (m.height, m.width)).astype(np.float32),
                                      cmap='binary',
                                      norm=colors.Normalize(vmin=np.min(m.R),
                                                            vmax=np.max(m.R)),
                                      alpha=0.5)
            #plot = axarr[i][j].contourf(np.reshape(m.R[i*nCols+j], (m.height, m.width)).astype(np.float32),cmap = 'binary', alpha=0.5)
            #axarr[i][j].imshow(m.hazMap, cmap='binary', alpha=0.5)
            axarr[i][j].set_ylim(m.height - 0.5, -0.5)
            axarr[i][j].set_title(
                'Action %d:%s' % (i * nCols + j, str(Location(i * nCols + j))))
            plots.append(plot)

    plt.show()
    '''
Esempio n. 30
0
def main():
    
    try:

        Experiment.initLogging(os.environ.has_key("GATEWAY_INTERFACE"))
        
        if os.environ.has_key("GATEWAY_INTERFACE"):
            # CGI
            (odict, args) = getCGIOptions()
        else:
            # Command line.  All the output is still CGI-ish, though.  Sorry.
            (odict, args) = getOptions()
        (odict, args) = processOptions(odict, args)
            
        data = newCreature(odict, odict["e"], odict.get("p"))
        data = Location.getJsonModule().dumps(data, indent=2)
        
        print "Content-type: application/json"
        print "Content-length: %s" % (len(data))
        print
        print data

    except:
        msg = string.join(apply( traceback.format_exception, sys.exc_info() ), "")
        if (msg[-1] == "\n"):
            msg = msg[:-1]
        logging.getLogger().warning(msg)
        data = "Huh?\n%s" % (msg)
        print "Status: 500 Internal Server Error"
        print "Content-type: text/plain"
        print "Content-length: %s" % (len(data))
        print
        print data
Esempio n. 31
0
def NearestNeighbour(locations: List[Location.Location]):
    path = []

    #Greedy implementation
    if miscGlobal.specialPrint == True:
        print('Greedy results:')
    locationsLeft = locations.copy()
    path.append(locationsLeft[0])
    locationsLeft.remove(locationsLeft[0])

    #Find greedy path
    closest = None  #Initialize this once
    while len(locationsLeft) > 0:
        closest = Location.FindClosestCity(path[len(path) - 1], locationsLeft)
        path.append(closest)
        locationsLeft.remove(closest)
        if miscGlobal.specialPrint == True:
            Funcs.PrintProgressBar(len(path), len(locations))
        if (time.process_time() - miscGlobal.start) > miscGlobal.maxTime:
            path.extend(locationsLeft)
            locationsLeft.clear()
            if miscGlobal.specialPrint == True:
                print('\nCould not complete Nearest Neigbhour search')
        yield path
    if miscGlobal.specialPrint == True:
        print()
        Funcs.PrintTour(path)
    return path
Esempio n. 32
0
 def get_loc_avg_from_user_checkinList(cls, hliData, user_id):
     flag = False
     loc = Location()
     if (user_id in hliData.dictUserCheckin):
         flag = True
         checkInList = hliData.dictUserCheckin[user_id]
         (flag, loc) = HLIAvg.get_loc_method_avg(checkInList)
     return (flag, loc)
Esempio n. 33
0
 def __getitem__(self, name):
     loc = self.db.primary_table[name]
     filetag, startpos, length = loc.split("\t")
     filename = self.db.fileid_info[filetag][0]
     return [
         Location.Location(self.namespace, name, filename, long(startpos),
                           long(length))
     ]
Esempio n. 34
0
 def __init__(self, List):
     self.ID = List[0]
     self.Fee = List[1]
     self.State = List[2]
     self.ListPrefer = List[3]
     self.Matched = List[4]
     self.Cost = List[5]
     self.Rank = [Location(0, 0), 0.0]
Esempio n. 35
0
    def _start_comp(self, ref):
        component = Component.Component()

        ref = [x.strip() for x in ref.split(",")]
        for x in ref:
            component.addLocation(Location.Location(x))

        self.stack.append(component)
Esempio n. 36
0
 def getOccupiedLocations(self):
     locations = []
     for i in range(self.getNumRows()):
         for k in range(self.getNumCols()):
             loc = Location(i, k)
             if (self.get(loc) != None):
                 locations.append(loc)
     return locations
 def MakeLocations(self, file_path):
     with open(file_path) as data_file:
         data = json.load(data_file)
         for location in data:
             name_of_location = data[location]["name"]
             tmx_map_path_of_location = data[location]["tmx map path"]
             a_location = Location.Location(name_of_location,
                                            tmx_map_path_of_location)
             self.locations.append(a_location)
Esempio n. 38
0
    def trans_checkin_to_cityId(self, checkin, flagNearCity=False):
        loc = Location(checkin.latitude, checkin.longitude)
        city = Location.getLocCity(loc, self.dictCity, flagNearCity)

        cityId = -1
        if(city != None):
            cityId = city.id

        return cityId
Esempio n. 39
0
 def home_loc_identify_method_get_result(self):
     resList = []
     for user_id in self.hliData.setUserNotKnowHome:
         user = self.hliData.dictUserRes[user_id]
         loc = Location(user.latitude, user.longitude)
         line = user_id + "\t" + str(loc.latitude) + "\t" + str(
             loc.longitude)
         resList.append(line)
     return resList
Esempio n. 40
0
def makeLocationArray():
    locations = []
    i = 1
    while worksheet_addresses_read.cell(i, 0).value:
        address = worksheet_addresses_read.cell(i, 0).value
        locations.append(Location.Location(address, 0, i))
        i += 1

    return locations
Esempio n. 41
0
 def loadConfig(self, fname=None):
     if not fname:
         fname = self.conf_file
     f = open(fname)
     config = Location.getJsonModule().load(f)
     f.close()
     if config.get("debug"):
         logging.getLogger().setLevel(logging.DEBUG) # Set the root level.
     return config
Esempio n. 42
0
class CabRequest:
	##	The constructor
	#	@param requestInfo dictinary with datas about the request
	#	@param mapManagerTaxi map manager for know vexteces and streets
	def __init__(self, requestInfo, mapManagerTaxi):
		self.areaRequest = mapManagerTaxi.areasDict[requestInfo["area"]]
		self.locationRequest = Location(requestInfo["location"], mapManagerTaxi)

	##	Return the CabRequest to dictionary format
	def toDictFormat(self):
		#initialise the cab request dictionary
		cabRequest = {}
		cabRequest["area"] = self.areaRequest.areaName
		cabRequest["location"] = self.locationRequest.toDictFormat()
		return cabRequest
Esempio n. 43
0
def main():

    """ Application start """

    logging.basicConfig(level=logging.INFO)

    get_module_logger().setLevel(logging.INFO)

    arg_parser = get_arg_parser()
    args = arg_parser.parse_args()

    tle, tle_provider = try_to_get_tle(args.tle)

    location = Location.get_location(args.location)

    tle_parser = TLEParser(location, tle)
    motor_control = ArduinoHardware(args.port, args.baudrate, True)

    tracker = Tracker(tle_provider, tle_parser, motor_control)

    tracker.run(int(args.azimuth), int(args.altitude))
Esempio n. 44
0
	def __init__(self, requestInfo, mapManagerTaxi):
		self.areaRequest = mapManagerTaxi.areasDict[requestInfo["area"]]
		self.locationRequest = Location(requestInfo["location"], mapManagerTaxi)
 def format_rating_to_location(cls, rating):
     loc = Location()
     loc.latitude = rating.latitude
     loc.longitude = rating.longitude
     return loc
Esempio n. 46
0
#t.addChannel("VSAMessages", sys.stdout);
#t.addChannel("MAC", sys.stdout);
#t.addChannel("VSA", sys.stdout);
t.addChannel("VSA OUTPUT", sys.stdout);
#t.addChannel("AUTOMATON", sys.stdout);
#t.addChannel("SYNC", sys.stdout);
t.addChannel("LEDS", sys.stdout);


m1 = t.getNode(1)
#m3 = t.getNode(3)
m1.bootAtTime(0);
sf.process();


msg = Location()
msg.set_x(8);
msg.set_y(8);
msg.set_theta(0);
#./msg.set_s(50);
#msg.set_lane(1);
#msg.set_region(4);
#msg.set_numngbs(0);
#msg.set_ngbs([0]);
#msg.set_ts(1);
#serialpkt = t.newSerialPacket()
#serialpkt.setData(msg.data)
#serialpkt.setType(0x89)
#serialpkt.setDestination(1)
#serialpkt.deliver(1, 1)
Esempio n. 47
0
  def updateMicaz(self) :
    heading = int(self.theta*180/math.pi)
    heading = heading % 360
    speed = int(self.omega*100.0)
    pressSpeed = int(self.pressSpeed*100.0)
    
    msg = Location()
    msg.set_x(self.x);
    msg.set_y(self.y);    
    msg.set_heading(heading/30);
    if self.laneChangeInProgress:
      msg.set_lane(2);
    else:
      msg.set_lane(self.lane);
    #print self.id,  "in Lane ", self.lane
    msg.set_speed(self.omega);
    msg.set_pressSpeed(self.pressSpeed*600)
        
    #print  self.id, " Updating Micaz: Heading ", heading % 360, "Current Speed K/H", speed, "Press Speed K/H ", pressSpeed
    
    if self.front.id != 0 and self.front.distance < (2**4)-1:
      #print self.id,  " at ", self.omega, " distance ", self.front.distance, " to car ", self.front.id
      #if self.front.distance
      msg.set_distanceFront(int(self.front.distance));      
    else:
      msg.set_distanceFront((2**4)-1);
    if self.monitored == 1:
      if self.omega ==0:
	dis=int(self.routeLength)
      else:
	dis= int(self.routeLength*(1-self.completed))
      msg.set_disJunction(dis);
    else:
      msg.set_disJunction(0);
    serialpkt = tossim.newSerialPacket()
    serialpkt.setData(msg.data)
    serialpkt.setType(0x89)
    serialpkt.setDestination(self.id)
    serialpkt.deliver(self.id,  TIME)
 def format_checkin_to_location(cls, checkIn):
     loc = Location()
     loc.latitude = checkIn.latitude
     loc.longitude = checkIn.longitude
     return loc
Esempio n. 49
0
class testLocation(unittest.TestCase):
	def setUp( self ):
		self.l = Location()
		self.mo = MassObject.MassObject()
	def test_Location_setLocation_absoluteWithNoReference( self ):
		self.l.setLocation( Coord.Coord(0,0,0) )
		self.assertEqual( self.l.coords, Coord.Coord(0,0,0) )
		self.failIf( self.l.reference )
	def test_Location_setLocation_relativeWithReference( self ):
		self.mo.location.setLocation( Coord.Coord(10,10,10) )
		self.l.setLocation( Coord.Coord(20,20,20), self.mo )
		self.assertEqual( self.l.coords, Coord.Coord(20,20,20) )
		self.assertEqual( self.l.reference, self.mo )
	def test_Location_setLocation_invalidReferenceObjectRaisesException( self ):
		self.assertRaises( TypeError, self.l.setLocation, Coord.Coord(0,0,0), int() )
	def test_Location_setLocation_NoneCoordsRaisesTypeError( self ):
		self.assertRaises( TypeError, self.l.setLocation, None )
	def test_Location_setLocation_3ValueTupleIsConvertedToCoord( self ):
		self.l.setLocation( (10,100,1000) )
		self.assert_( isinstance( self.l.coords, Coord.Coord ) )
	def test_Location_getLocation_invalidReferenceObjectRaisesException( self ):
		self.assertRaises( TypeError, self.l.getLocation, int() )
	def test_Location_getLocation_TakesTupleParameter( self ):
		self.l.setLocation( (10,100,1000) )
		print self.l.getLocation( (10,100,1000) )
	def test_Location_getLocation_TakesListParameter( self ):
		self.l.setLocation( (10,100,1000) )
		print self.l.getLocation( [10,100,1000] )
	def test_Location_getLocation_TakesCoordParameter( self ):
		self.l.setLocation( (10,100,1000) )
		print self.l.getLocation( Coord.Coord(10,100,1000) )
	def test_Location_getLocation_absoluteWithNoReference( self ):
		self.l.setLocation( Coord.Coord(0, 0, 0) )
		self.assertEqual( self.l.getLocation( ), Coord.Coord(0,0,0) )
	def test_Location_getLocation_absoluteWithSelfReference( self ):
		self.l.setLocation( Coord.Coord(10,20,30) )
		self.assertEqual( self.l.getLocation( self.mo), Coord.Coord(0,0,0) )
	def test_Location_getLocation_relativeWithNoReference( self ):
		self.mo.location.setLocation( Coord.Coord(0, 0, 0) )
		self.l.setLocation( Coord.Coord(10, 10, 10), self.mo )
		self.assertEqual( self.l.getLocation(), Coord.Coord(10,10,10) )
	def test_Location_getLocation_relativeWithOriginalReference( self ):
		self.mo.location.setLocation( Coord.Coord(0, 0, 0) )
		self.l.setLocation( Coord.Coord(10, 10, 10), self.mo )
		self.assertEqual( self.l.getLocation( self.mo ), Coord.Coord(10,10,10) )
	def test_Location_getLocation_relativeWithZeroReference( self ):
		self.mo.location.setLocation( Coord.Coord(0, 0, 0) )
		self.l.setLocation( Coord.Coord(10, 10, 10), self.mo )
		self.assertEqual( self.l.getLocation( Coord.Coord(0,0,0) ), Coord.Coord(10,10,10) )
	def test_Location_getLocation_relativeWithObjectLocationReference( self ):
		self.mo.location.setLocation( Coord.Coord(0, 0, 0) )
		self.l.setLocation( Coord.Coord(10, 10, 10), self.mo )
		self.assertEqual( self.l.getLocation( Coord.Coord(10,10,10) ), Coord.Coord(0,0,0) )
	def test_Location_getLocation_relativeReferenceObjectOffCenter( self ):
		self.mo.location.setLocation( Coord.Coord(-100, -100, -100) )
		self.l.setLocation( Coord.Coord(10, 10, 10), self.mo )
		self.assertEqual( self.l.getLocation( self.mo ), Coord.Coord(-90, -90, -90) )
	def test_Location_getLocation_relativeReferenceObjectXTranslate( self ):
		self.mo.location.setLocation( Coord.Coord( 10, 10, 10 ) )
		self.mo2 = MassObject.MassObject()
		self.mo2.location.setLocation( Coord.Coord( 110, 10, 10 ) )
		self.l.setLocation( (10, 0, 0 ), self.mo2 )
		self.assertEqual( self.l.getLocation( self.mo ), Coord.Coord(130, 0, 0) )
	def test_Location_getLocation_relativeReferenceObjectHasRelativeReferenceObject( self ):
		self.mo.location.setLocation( Coord.Coord(10, 10, 10) )
		self.mo2 = MassObject.MassObject()
		self.mo2.location.setLocation( Coord.Coord(20, 20, 20), self.mo )
		self.l.setLocation( Coord.Coord(40, 40, 40), self.mo2 )
		self.assertEqual( self.l.getLocation( Coord.Coord(0,0,0) ), Coord.Coord(70, 70, 70 ) )
Esempio n. 50
0
        print('STOP')
        return True
    else:
        return False

def addData():
    pass

def findDis(lat1, lat2, long1, long2, count = 0 ):
    lat1 = math.radians(lat1)
    lat2 = math.radians(lat2)
    long1 = math.radians(long1)
    long2 = math.radians(long2)
    dlat = lat1 - lat2
    dlong = long1 - long2 
    a = pow(math.sin(dlat/2),2) + math.cos(lat1) * math.cos(lat2) * pow(math.sin(dlong/2),2)
    c =  2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    miles = c * 3960
    return miles
    

if __name__ == '__main__':
    coord = Location.getLocation()
    #rad = int(input('rad: '))
    offlimit = offlimit(coord[0], coord[1])
    settings = True
    if not offlimit == 'good':
        dontfly(settings)
        print(offlimit)
    
Esempio n. 51
0
 def __init__(self):
     self.logger = logging.getLogger(self.getLoggerName())
     self.loc = Location.getInstance()
Esempio n. 52
0
	def __init__(self):
		self.sender_data = ""
		self.const = Constants()
		self.location = Location(self)
Esempio n. 53
0
	def setUp( self ):
		self.l = Location()
		self.mo = MassObject.MassObject()
Esempio n. 54
0
import shutil
import time
import sys
import logging.handlers
import ConfigParser

import Location
import Creature
import ImageLoader
import Picklable
import SrcImage
import Thumbnailer
import TransformLoader

exps_dir = "exps"
abs_dir = Location.getInstance().toAbsolutePath(exps_dir)

class NoSuchExperiment(Exception):
    def __init__(self, exp):
        Exception.__init__(self)
        self.exp = exp
    def __str__(self):
        return str(self.exp)


################################################################
def initLogging(cgi=False):
    
    conf = ConfigParser.RawConfigParser()
    conf.read(Location.getInstance().toAbsolutePath("logging.conf"))
    
Esempio n. 55
0
code = chkdate.validate(sys.argv)

if isinstance(code, types.IntType):
    print "Error code: %d" % code
    exit(code)
else:
    year = code[0]
    month = code[1]
    day   = code[2]
    d1  = Dates(year, month, day)
    dnr = d1.yday()
    sd =  d1.getdate()
    print("\nDate %s (Day number %d) \n" % (sd, dnr))

p1 = Location("Helsinki", 60.18, 24.93, 2)
p1.printrecord()

sol1a = Solar(dnr, p1, "SUNRISE", znt_official)
sol1b = Solar(dnr, p1, "SET", znt_official)
delivery(sol1a, sol1b, p1)

print("Declination %.2f degrees at sunrise" % sol1a.Declination)
meandecl = getdeclination(sol1a, sol1b)
print("Declination %.2f degrees at noon" % meandecl)
print("Declination %.2f degrees at sunset" % sol1b.Declination)
print("-----------\n")

p2 = Location("Oulu", 65.02, 25.47, 2)
p2.printrecord()
Esempio n. 56
0
code = chkdate.validate(sys.argv)

if isinstance(code, types.IntType):
    print "Error code: %d" % code
    exit(code)
else:
    year = code[0]
    month = code[1]
    day   = code[2]
    d1  = Dates(year, month, day)
    dnr = d1.yday()
    sd =  d1.getdate()
    print("\nDate %s (Day number %d) \n" % (sd, dnr))

cityTable = getTable("locationData.txt")
nr = len(cityTable) - 1 # Number of cities

for i in range(0, nr):
   city, latitude, longitude, timeZone = getRowdata(cityTable[i])
   pl = Location(city, latitude, longitude, timeZone)
   pl.printrecord()

   solpa = Solar(dnr, pl, "SUNRISE", znt_official)
   solpb = Solar(dnr, pl, "SET", znt_official)
   delivery(solpa, solpb, pl)

#   meandecl = getdeclination(solpa, solpb)
#   print("Declination %.2f degrees at noon" % meandecl)
   print("-----------\n")