示例#1
0
def register(id, firstName, lastName, email, pushToken):
    '''
    Creates a new user with the parameters inputted.

    :param id:
    :param firstName:
    :param lastName:
    :param pushToken:
    :param email:
    :return: True for success, False otherwise.
    '''

    try:
        if _get(id):
            logging.error("User with id %s already exists!", id)
            return False

        user = {}
        user['id'] = id
        user['lastName'] = lastName
        user['firstName'] = firstName
        user['email'] = email
        user['pushToken'] = pushToken

        db.users().child(id).put(user)

        db.emails_to_users().patch({_createEmailKey(email): id})
        return True
    except Exception as e:
        logging.exception("Couldn't create new user with id %s!" % id)
        return False
示例#2
0
def register(id, firstName, lastName, email, pushToken):
    '''
    Creates a new user with the parameters inputted.

    :param id:
    :param firstName:
    :param lastName:
    :param pushToken:
    :param email:
    :return: True for success, False otherwise.
    '''

    try:
        if _get(id):
            logging.error("User with id %s already exists!", id)
            return False

        user = {}
        user['id'] = id
        user['lastName'] = lastName
        user['firstName'] = firstName
        user['email'] = email
        user['pushToken'] = pushToken

        db.users().child(id).put(user)

        db.emails_to_users().patch({_createEmailKey(email):id})
        return True
    except Exception as e:
        logging.exception("Couldn't create new user with id %s!" % id)
        return False
示例#3
0
 def testGetExisting(self):
     oy = db.User.get('oy')
     cn = db.User.get('cn')
     oy = db.User.get('oy')
     self.assertEqual(oy.name, 'oy')
     self.assertEqual(oy.id, 1)
     self.assertEqual(len(db.users()), 2)
示例#4
0
def delete(id, accessToken=None):
    '''
    Delete a user.

    :param id:
    :return:
    '''

    try:
        user = _get(id)
        emailKey = _createEmailKey(user['email'])
        db.users().child(id).delete()
        db.emails_to_users().child(emailKey).delete()

        return True
    except Exception as e:
        logging.exception("Couldn't delete user with id %s!" % id)
        return False
示例#5
0
def add_user(username, pincode):
    exists = db_session.query(users).filter_by(
        username=username, pincode=pincode).scalar() is not None
    if exists == False:
        new_user = users(username=username, pincode=pincode, active=1)
        db_session.add(new_user)
        db_session.commit()
    else:
        pass
示例#6
0
def delete(id, accessToken=None):
    '''
    Delete a user.

    :param id:
    :return:
    '''

    try:
        user = _get(id)
        emailKey = _createEmailKey(user['email'])
        db.users().child(id).delete()
        db.emails_to_users().child(emailKey).delete()

        return True
    except Exception as e:
        logging.exception("Couldn't delete user with id %s!" % id)
        return False
示例#7
0
	def setUnits(self, coord, turn):
		units = {}
		if not coord:
			return
		
		self.tree.DeleteAllItems()
		image_list = wx.ImageList(40, 40)
		self.tree.AssignImageList(image_list)
		img_list_data = {}
		root = self.tree.AddRoot('Fleets')
		for user in db.users():
			user_id = user['id']
			tree_user = None
			for fleet in db.fleets(turn, util.filter_coord(coord) + ['owner_id=%s'%(user_id,)]):
				if not tree_user:
					tree_user = self.tree.AppendItem(root, user['name'])
				tree_fleet = self.tree.AppendItem(tree_user, fleet['name'])
				for unit in db.units(turn, ['fleet_id=%s'%(fleet['id'],)]):					
					proto = db.get_prototype(unit['class'], ('carapace', 'color', 'name'))
					obj_carp = int(unit['class']), int(proto['carapace']), int(proto['color'])
					img_item = None
					if obj_carp in img_list_data:
						img_item = img_list_data[obj_carp]
					else:
						img_item = image.add_image(image_list, obj_carp)
						img_list_data[obj_carp] = img_item
					name = proto['name']
					if not name:
						name = get_unit_name(int(proto['carapace']))
					self.tree.AppendItem(tree_fleet, name, image=img_item)
					
		for user in db.alien_players(turn):
			user_id = int(user['player_id'])
			tree_user = None
			for fleet in db.fleets(turn, util.filter_coord(coord) + ['owner_id=%s'%(user_id,)]):
				if not tree_user:
					tree_user = self.tree.AppendItem(root, user['name'])
				tree_fleet = self.tree.AppendItem(tree_user, fleet['name'])

				for unit in db.alienUnits(turn, ['fleet_id=%s'%(fleet['id'],)]):
					print 'get alient unit %s'%(unit,)
					obj_carp = unit['class'], int(unit['carapace']), int(unit['color'])
					img_item = None
					if obj_carp in img_list_data:
						img_item = img_list_data[obj_carp]
					else:
						img_item = image.add_image(image_list, obj_carp)
						img_list_data[obj_carp] = img_item

					self.tree.AppendItem(tree_fleet, get_unit_name(int(unit['carapace'])), image=img_item)
				
					
		self.tree.ExpandAll()
示例#8
0
 def get(self):
     client = APIClient(app_key=c.APP_KEY, app_secret=c.APP_SECRET,
                        redirect_uri=c.CALLBACK_URL)
     code = self.request.get('code')
     r = client.request_access_token(code)
     access_token = r.access_token  # access token,e.g., abc123xyz456
     expires_in = r.expires_in      # token expires in
     user_id = r.uid
     client.set_access_token(access_token, expires_in)
     user = users.get_by_key_name(user_id)
     if user:
         user.delete()
     e = users(access_token=access_token, expires_in=str(expires_in), key_name=user_id)
     e.put()
     self.response.write("登录成功")
示例#9
0
	def __init__(self, parent, only_my_users = True):
		wx.Window.__init__(self, parent, wx.ID_ANY)
		sizer = wx.BoxSizer(wx.VERTICAL)
		
		self.users = {}
		for user in db.users():
			checkbox = wx.CheckBox(self, label=user['name'])
			checkbox.Bind(wx.EVT_CHECKBOX, self.userChanged)
			self.users[int(user['id'])] = checkbox
			checkbox.SetValue(False)
			sizer.Add(checkbox)
			
		self.SetSizer(sizer)
		
		self.Layout()
示例#10
0
def scheduledjob():
    """ Send new notifications that come on KTU site. \n
        Checks subscription status of each user from Firebase Realtime Database and sends notifs
        to subscribers
    """

    contents = get_contents()
    if contents and contents != []:
        for key, value in users().items():
            chat_id = key
            """ checking if unsubscribed and send the notification """
            if value != "F":
                send_notifs(chat_id, contents, value)

        setData(notifs)
示例#11
0
	def update(self):
		log.debug('update tasks %d'%(len(self.accounts),))
		for r in db.users([], ('id', 'name')):
			user_id = r['id']
			name = r['name']

			if user_id in self.accounts:
				continue

			log.debug("%s => %s"%(user_id, name))
			login = wx.StaticText(self,wx.ID_ANY, '%s'%(name,))
			self.accounts[user_id] = login
			self.sizer.Add(login)
			if not self.active_user:
				self.selectUser(user_id)
			login.Bind(wx.EVT_LEFT_DCLICK, self.onChangeUser)
		self.sizer.Layout()
示例#12
0
def get_user_nickname():
	nick = config.options['user']['nick']
	if nick:
		return nick

	# find out first user id ( consider it user nickname )
	min_id = None
	for user in db.users():
		if not user['login'] in config.users:
			continue
		user_id = int(user['id'])
		if not min_id:
			min_id = user_id
			nick = user['name']
		elif user_id < min_id:
			min_id = user_id
			nick = user['name']
	if min_id:
		return nick
	return None
示例#13
0
    def status(self):
        def headers(cols):
            return "<thead><tr>" + "".join("<th>{}</th>".format(col) for col in cols) + "</tr></thead>"
        def row(cols):
            return "<tr>" + "".join("<td>{}</td>".format(col) for col in cols) + "</tr>"

        import db
        res = "<html>"
        res += "<head>"
        res += "<script src=\"js/jquery-1.11.3.js\"></script>"
        res += "<script src=\"js/canvasjs.min.js\"></script>"
        res += "<script src=\"js/option_chart.js\"></script>"
        res += "</head>"

        a = analytics.get()
        res += "<h3>Analytics</h3>"
        res += "<table>" + headers(["function", "# calls", "# exceptions", "min time (s)", "avg. time (s)", "max time (s)"])
        res += "<tbody>"
        for key, entry in sorted(a.items()):
            res += row([
                key,
                entry["num_calls"],
                entry["num_exceptions"],
                "{:.3f}".format(entry["min_time"]),
                "{:.3f}".format(float(entry["total_time"]) / float(entry["num_calls"])),
                "{:.3f}".format(entry["max_time"])])
        res += "</tbody></table>"

        res += "<h3>Active URL leases</h3>"
        if db.url_leases:
            res += "<table><thead><tr><th>user</th><th>url</th><th>expires</th></tr></thead><tbody>"
            for url, user, expires in db.url_leases:
                res += "<tr><td>{}</td><td>{}</td><td>{}</td></tr>".format(user, url, expires)
            res += "</tbody></table>"
        else:
            res += "N/A"

        with DBConnection() as db:
            res += "<h3>Commands collected</h3>"
            pairs = []
            diverse_pairs = []
            num_pairs = 0
            num_cmds = 0
            num_diverse_pairs = 0
            cmds = []
            for _, _, nl, cmd, _ in db.pairs():
                num_pairs += 1
            #     pairs.append((nl, cmd))
            # for _, _, nl, cmd, _ in db.unique_pairs():
            #     num_diverse_pairs += 1
            #     diverse_pairs.append((nl, cmd))
            cmds_with_users = db.commands_with_users()
            for cmd in cmds_with_users:
                if "find" in cmd:
                    num_cmds += 1
            res += "<b>{}</b> annotations <br>".format(num_pairs)
            # res += "<b>{}</b> unique pairs <br>".format(num_diverse_pairs)
            res += "<b>{}</b> unique commands <br><br>".format(num_cmds)

            res += "<div id=\"chartContainer\" style=\"height: 500px; width: 500px;\"></div>"

            for cmd in sorted(cmds_with_users.keys())[:100]:
                if ".js" in cmd:
                    continue
                res += cmd + " ("
                for user in cmds_with_users[cmd]:
                    res += user + ', '
                res += ")<br>"
            res += "<i>(... end of top 100 commands collected)</i><br>"

            """res += "<h3>URLs in queue</h3>"
            for url, _ in db.find_urls_with_less_responses_than(None):
                res += url + "<br>"
            """

            """res += "<h3>URLs Finished</h3>"
            for url, _ in db.find_urls_that_is_done():
                res += url + "<br>"
            """

            """res += "<h3>Pairs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th><th>nl</th><th>cmd</th></tr></thead><tbody>"
            for user, url, nl, cmd in db.pairs():
                url = url.decode().encode('utf-8')
                nl = nl.decode().encode('utf-8')
                cmd = cmd.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(
                        user, url, nl, cmd)
            res += "</tbody></table>"
            """

            """res += "<h3>NoPairs URLs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th></tr></thead><tbody>"
            for user, url in db.nopairs():
                url = url.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td></tr>".format(
                        user, url)
            res += "</tbody></table>"
            """

            """res += "<h3>Skipped URLs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th></tr></thead><tbody>"
            for user, url in db.skipped():
                url = url.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td></tr>".format(
                        user, url)
            res += "</tbody></table>"
            """

            res += "<h3>Search Content (top 100)</h3>"
            res += "Number of finished URLs: {}<br>".format(db.num_urls_by_num_visit(2))
            res += "Number of URLs annotated by one user: {}<br>".format(db.num_urls_by_num_visit(1))
            res += "Number of unnotated URLs: {}<br>".format(db.num_urls_by_num_visit(0))
            res += "<table><thead><tr><th>url</th>" + \
                                "<th>fingerprint</th>" + \
                                "<th>minimum distance</th>" + \
                                "<th>max score</th>" + \
                                "<th>avg score</th>" + \
                                "<th>number of commands</th" + \
                                "><th>number of visits</th>" + \
                                "</tr></thead><tbody>"
            num_pages = 0
            for url, fingerprint, min_distance, max_score, avg_score, num_cmds, num_visits in db.search_content():
                if num_visits >= 2:
                    # do not show URLs that's done
                    continue
                if not max_score:
                    max_score = 0.0
                if not avg_score:
                    avg_score = 0.0
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.4f}</td><td>{:.4f}</td><td>{}</td><td>{}</td></tr>"\
                        .format(url, fingerprint, min_distance, max_score, avg_score, num_cmds, num_visits)
                num_pages += 1
                if num_pages > 100:
                    break
            res += "</tbody></table>"

            res += "<h3>Registered Users</h3>"
            res += "<table><thead><tr><th>user</th><th>first name</th><th>last name</th><th>completed milestone</th></tr></thead><tbody>"
            for user, fname, lname, time_stamp in db.users():
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(user, fname, lname, time_stamp)
            res += "</tbody></table>"

        res += "</html>"
        return res
示例#14
0
def _get(id):

    return db.users().child(id).get()
示例#15
0
 def testGetNew(self):
     oy = db.User.get('oy')
     self.assertEqual(oy.name, 'oy')
     self.assertEqual(oy.id, 1)
     self.assertEqual(len(db.users()), 1)
示例#16
0
	def onSendScouts(self, _):
		min_size = 70
		max_size = 99
		
		#helps avoid flying on the same planet with different accounts
		friend_geo_scout_ids = []
		for user in db.users():
			friend_geo_scout_ids.append(str(user['id']))
		
		for acc in config.accounts():
			user_id = int(acc['id'])

			if self.command_selected_user and user_id != self.map.selected_user_id:
				continue

			self.pending_actions.user_id = user_id
			#log.info('send scouts %s size %s'%(acc['login'], min_size))
					
			# find units that can geo-explore
			# find the ones that are already in fleets in one of our planets
			
			fly_range = 0.0
			ready_scout_fleets = {}
			# get all fleets over our planets
			for planet in store.iter_objects_list('open_planet', {'user_id':user_id}):
				#print 'open planet %s'%(planet,)
				coord = get_coord(planet)
				for fleet in store.iter_objects_list('fleet', {'user_id':user_id, 'x':coord[0], 'y':coord[1]}):
					if value_in(self.exclude_fleet_names, fleet['name']):
						continue
					units = store.get_fleet_units(fleet['fleet_id'])
					if len(units) != 1:
						#print 'fleet %s has wrong units count ( != 1 ) %s, skipping it'%(fleet, units)						
						continue
					unit = units[0]
					if int(unit['unit_id']) in self.manual_control_units:
						#print 'unit %s reserved for manual control, skipping it'%(unit,)
						continue

					if not self.is_geo_scout(unit):
						#print 'unit %s is not geo-scout, skipping it'%(unit,)
						continue
					#fly_range = max(fly_range, )
					#print 'unit %s on planet %s for fleet %s is geo-scout'%(unit, coord, fleet)
					# ok, this is geo-scout, single unit in fleet, on our planet
					#ready_scout_fleets.append((coord, fleet))
					_,r = store.get_fleet_speed_range(fleet['fleet_id'])
					fly_range = max(fly_range, r)
					ready_scout_fleets.setdefault(coord, []).append((fleet, r))
					
			
			# get possible planets to explore in nearest distance
			for coord in ready_scout_fleets.keys():
				#print 'load geo size centered at %s with range %s'%(coord, int(fly_range))
				save_load.load_geo_size_center(coord, int(fly_range))
			
			# jump to nearest/biggest unexplored planet
			exclude = set()
			for coord, fleets in ready_scout_fleets.iteritems():
				max_fly_range = 0
				for f,r in fleets:
					max_fly_range = max(max_fly_range, r)
				
				possible_planets = []
				#s<=99 - skip stars
				#dx = lt[0]-fly_range, lt[0]+fly_range
				#dy = lt[1]-fly_range, lt[1]+fly_range
				for p in store.iter_planets_size(pos=coord, fly_range=max_fly_range, size_min=min_size, bigger_first = True):
					if not (p['s']>=min_size and p['s']<=max_size):
						#print 'planet %s not fit the size'%(p,)
						continue
					dest = get_coord(p)
					if dest in exclude:
						continue
					dist = util.distance(dest, coord)
					if dist > fly_range:
						#print 'planet %s is too far away'%(p,)
						continue
						
					planet = db.get_planet(dest)
					if planet and 'o' in planet and planet['o']:
						#print 'planet %s already explored'%(p,)
						continue
					
					has_flying_geo_scouts = False
					
					# check if currently there is some explore fleet on planet, or explore fleet already fly there
					already_has_scout = False
					for fleet in store.iter_objects_list('fleet', {'x':dest[0], 'y':dest[1]}, controlled = True):
						if self.is_geo_scout_fleet(fleet['fleet_id']):
							already_has_scout = True
							break
					if already_has_scout:
						#print 'planet %s has scount fleet on it'%(p,)
						continue
						
					already_fly_geo_scouts = False
					for fleet in store.iter_objects_list('flying_fleet', {'x':dest[0], 'y':dest[1]}, controlled = True):
						if self.is_geo_scout_fleet(fleet['fleet_id']):
							already_fly_geo_scouts = True
							#self.actions.add_action( action.ActionGeoExplore(user_id, ':dest, 'fleet_id':fleet['fleet_id']}))
							break
					if already_fly_geo_scouts:
						#print 'planet %s has flying scount fleet'%(p,)
						continue

					possible_planets.append( (dist, dest) )
					#print 'add possible planet %s'%(dest,)

				for fleet, fleet_range in fleets:
					#print 'check planets for fleet %s'%(fleet,)
					for dist, planet in sorted(possible_planets):
						if dist > fleet_range:
							#print 'planet %s too scary'%(p,)
							continue
						# ok fly to it
						self.actions.add_action( action.ActionJump(user_id, fleet['fleet_id'], planet ))
						#self.pending_actions.fleetMove(fleet['id'], planet)
						exclude.add( planet )
						#print 'jump %s from %s to %s'%(fleet, coord, planet)
						possible_planets.remove( (dist, planet ) )
						break
示例#17
0
def _get(id):

    return db.users().child(id).get()
示例#18
0
 def testRemoveByName(self):
     oy = db.User.get('oy')
     db.User.remove('oy')
     self.assertEqual(len(db.users()), 0)
示例#19
0
    def status(self):
        def headers(cols):
            return "<thead><tr>" + "".join("<th>{}</th>".format(col)
                                           for col in cols) + "</tr></thead>"

        def row(cols):
            return "<tr>" + "".join("<td>{}</td>".format(col)
                                    for col in cols) + "</tr>"

        import db
        res = "<html>"
        res += "<head>"
        res += "<script src=\"js/jquery-1.11.3.js\"></script>"
        res += "<script src=\"js/canvasjs.min.js\"></script>"
        res += "<script src=\"js/option_chart.js\"></script>"
        res += "</head>"

        a = analytics.get()
        res += "<h3>Analytics</h3>"
        res += "<table>" + headers([
            "function", "# calls", "# exceptions", "min time (s)",
            "avg. time (s)", "max time (s)"
        ])
        res += "<tbody>"
        for key, entry in sorted(a.items()):
            res += row([
                key, entry["num_calls"], entry["num_exceptions"],
                "{:.3f}".format(entry["min_time"]), "{:.3f}".format(
                    float(entry["total_time"]) / float(entry["num_calls"])),
                "{:.3f}".format(entry["max_time"])
            ])
        res += "</tbody></table>"

        res += "<h3>Active URL leases</h3>"
        if db.url_leases:
            res += "<table><thead><tr><th>user</th><th>url</th><th>expires</th></tr></thead><tbody>"
            for url, user, expires in db.url_leases:
                res += "<tr><td>{}</td><td>{}</td><td>{}</td></tr>".format(
                    user, url, expires)
            res += "</tbody></table>"
        else:
            res += "N/A"

        with DBConnection() as db:
            res += "<h3>Commands collected</h3>"
            pairs = []
            diverse_pairs = []
            num_pairs = 0
            num_cmds = 0
            num_diverse_pairs = 0
            cmds = []
            for _, _, nl, cmd, _ in db.pairs():
                num_pairs += 1
            #     pairs.append((nl, cmd))
            # for _, _, nl, cmd, _ in db.unique_pairs():
            #     num_diverse_pairs += 1
            #     diverse_pairs.append((nl, cmd))
            cmds_with_users = db.commands_with_users()
            for cmd in cmds_with_users:
                if "find" in cmd:
                    num_cmds += 1
            res += "<b>{}</b> annotations <br>".format(num_pairs)
            # res += "<b>{}</b> unique pairs <br>".format(num_diverse_pairs)
            res += "<b>{}</b> unique commands <br><br>".format(num_cmds)

            res += "<div id=\"chartContainer\" style=\"height: 500px; width: 500px;\"></div>"

            for cmd in sorted(cmds_with_users.keys())[:100]:
                if ".js" in cmd:
                    continue
                res += cmd + " ("
                for user in cmds_with_users[cmd]:
                    res += user + ', '
                res += ")<br>"
            res += "<i>(... end of top 100 commands collected)</i><br>"
            """res += "<h3>URLs in queue</h3>"
            for url, _ in db.find_urls_with_less_responses_than(None):
                res += url + "<br>"
            """
            """res += "<h3>URLs Finished</h3>"
            for url, _ in db.find_urls_that_is_done():
                res += url + "<br>"
            """
            """res += "<h3>Pairs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th><th>nl</th><th>cmd</th></tr></thead><tbody>"
            for user, url, nl, cmd in db.pairs():
                url = url.decode().encode('utf-8')
                nl = nl.decode().encode('utf-8')
                cmd = cmd.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(
                        user, url, nl, cmd)
            res += "</tbody></table>"
            """
            """res += "<h3>NoPairs URLs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th></tr></thead><tbody>"
            for user, url in db.nopairs():
                url = url.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td></tr>".format(
                        user, url)
            res += "</tbody></table>"
            """
            """res += "<h3>Skipped URLs</h3>"
            res += "<table><thead><tr><th>user</th><th>url</th></tr></thead><tbody>"
            for user, url in db.skipped():
                url = url.decode().encode('utf-8')
                res += "<tr><td>{}</td><td>{}</td></tr>".format(
                        user, url)
            res += "</tbody></table>"
            """

            res += "<h3>Search Content (top 100)</h3>"
            res += "Number of finished URLs: {}<br>".format(
                db.num_urls_by_num_visit(2))
            res += "Number of URLs annotated by one user: {}<br>".format(
                db.num_urls_by_num_visit(1))
            res += "Number of unnotated URLs: {}<br>".format(
                db.num_urls_by_num_visit(0))
            res += "<table><thead><tr><th>url</th>" + \
                                "<th>fingerprint</th>" + \
                                "<th>minimum distance</th>" + \
                                "<th>max score</th>" + \
                                "<th>avg score</th>" + \
                                "<th>number of commands</th" + \
                                "><th>number of visits</th>" + \
                                "</tr></thead><tbody>"
            num_pages = 0
            for url, fingerprint, min_distance, max_score, avg_score, num_cmds, num_visits in db.search_content(
            ):
                if num_visits >= 2:
                    # do not show URLs that's done
                    continue
                if not max_score:
                    max_score = 0.0
                if not avg_score:
                    avg_score = 0.0
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.4f}</td><td>{:.4f}</td><td>{}</td><td>{}</td></tr>"\
                        .format(url, fingerprint, min_distance, max_score, avg_score, num_cmds, num_visits)
                num_pages += 1
                if num_pages > 100:
                    break
            res += "</tbody></table>"

            res += "<h3>Registered Users</h3>"
            res += "<table><thead><tr><th>user</th><th>first name</th><th>last name</th><th>completed milestone</th></tr></thead><tbody>"
            for user, fname, lname, time_stamp in db.users():
                res += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(
                    user, fname, lname, time_stamp)
            res += "</tbody></table>"

        res += "</html>"
        return res
示例#20
0
 def testRemoveByObject(self):
     oy = db.User.get('oy')
     db.User.remove(oy)
     self.assertEqual(len(db.users()), 0)
示例#21
0
	def onSendScouts(self, _):
		turn = db.getTurn()
		min_size = 70
		max_size = 99
		
		#helps avoid flying on the same planet with different accounts
		friend_geo_scout_ids = []
		for user in db.users():
			friend_geo_scout_ids.append(str(user['id']))
		
		for acc in config.accounts():
			user_id = int(acc['id'])

			if self.command_selected_user and user_id != self.map.selected_user_id:
				continue

			self.pending_actions.user_id = user_id
			print 'send scouts %s size %s'%(user_id, min_size)
					
			# find units that can geo-explore
			# find the ones that are already in fleets in one of our planets
			
			fly_range = 0.0
			ready_scout_fleets = {}
			# get all fleets over our planets
			for planet in db.open_planets(user_id):
				print 'open planet %s'%(planet,)
				coord = get_coord(planet)
				for fleet in db.fleets(turn, filter_coord(coord)+['owner_id=%s'%(user_id,)]):
					if value_in(self.exclude_fleet_names, fleet['name']):
						continue
					units = db.get_units(turn, ['fleet_id=%s'%(fleet['id'],)])
					if len(units) != 1:
						print 'fleet %s has wrong units count ( != 1 ) %s, skipping it'%(fleet, units)
						
						continue
					unit = units[0]
					if int(unit['id']) in self.manual_control_units:
						print 'unit %s reserved for manual control, skipping it'%(unit,)
						continue

					if not self.is_geo_scout(unit):
						print 'unit %s is not geo-scout, skipping it'%(unit,)
						continue
					fly_range = max(fly_range, self.get_unit_range(unit))
					print 'unit %s on planet %s for fleet %s is geo-scout'%(unit, coord, fleet)
					# ok, this is geo-scout, single unit in fleet, on our planet
					#ready_scout_fleets.append((coord, fleet))
					ready_scout_fleets.setdefault(coord, []).append((fleet, fly_range))
					
			
			# get possible planets to explore in nearest distance
			for coord in ready_scout_fleets.keys():
				serialization.load_geo_size_center(coord, 10)
			
			# jump to nearest/biggest unexplored planet
			exclude = set()
			for coord, fleets in ready_scout_fleets.iteritems():
				lt = int(coord[0]-fly_range), int(coord[1]-fly_range)
				
				possible_planets = []
				#s<=99 - skip stars
				for p in db.planets_size(['s>=%s'%(min_size,), 's<=%s'%(max_size,)] + planet_area_filter( lt, (int(fly_range*2), int(fly_range*2)))):
					dest = get_coord(p)
					if dest in exclude:
						continue
					dist = util.distance(dest, coord)
					if dist > fly_range:
						continue
						
					planet = db.get_planet(dest)
					if planet and 'o' in planet:
						continue
					
					has_flying_geo_scouts = False
					# get list of all flying fleets ( or our allies and mults ) to this planet 
					for fleet in db.flyingFleets(turn, filter_coord(dest) + ['owner_id in(%s)'%','.join(friend_geo_scout_ids)]):
						# check if the fleet is geo-scout
						if self.is_geo_scout_fleet(turn, fleet['id']):
							has_flying_geo_scouts = True
							print 'found another scout %s, skip planet %s'%(fleet, dest)
					if has_flying_geo_scouts:
						exclude.add(dest)
						continue
					
					#TODO: can check if it will take too long for the other fleet, send ours
					
					possible_planets.append( (dist, dest) )

				for fleet, fleet_range in fleets:
					for dist, planet in sorted(possible_planets):
						if dist > fleet_range:
							continue
						# ok fly to it
						self.pending_actions.fleetMove(fleet['id'], planet)
						exclude.add( planet )
						print 'jump %s from %s to %s'%(fleet, coord, planet)
						possible_planets.remove( (dist, planet ) )
						break
							
			self.perform_actions()