def processCommand(userInput, playerList, groupList): if (userInput == "add player" or userInput == "ap"): player.addPlayer(playerList) elif (userInput == "change player info" or userInput == "cpi"): processChangePlayerInfo(playerList, groupList) elif (userInput == "show results" or userInput == "sr"): Castle.printRecord(playerList) elif (userInput == "print match info" or userInput == "pmi"): processPrintMatchInfo(playerList) elif (userInput == "show players" or userInput == "sp"): player.printPlayerList(playerList) elif (userInput == "delete player" or userInput == "dp"): player.deletePlayer(playerList) elif (userInput == "help" or userInput == "h" or userInput == "show help" or userInput == "sh"): printHelp() elif (userInput == "rules" or userInput == "r" or userInput == "show rules"): printRules() elif (userInput == "create group" or userInput == "cg"): Groups.createGroup(groupList) elif (userInput == "group results" or userInput == "gr"): showGroupResults(playerList, groupList) else: print("Invalid command.") return input("Enter a command: ").lower()
def makeNamedGroup(id, groupID, idTuple): if not Groups.getGroup(id): toRet = Groups.MainGroup(id, groupID) user = toRet.users.addUser(Users.User(toRet, idTuple[0])).setToken(idTuple[1]) user.save() else: toRet = Groups.getGroup(id) return toRet
def makeNamedGroup(id, groupID, idTuple, initialPassword = None, classType = Groups.MainGroup): if not Groups.getGroup(id): toRet = classType(id, groupID) user = toRet.users.addUser(Users.User(toRet, idTuple[0])).setToken(idTuple[1]) user.save() else: toRet = Groups.getGroup(id) #Regardless, set the password if initialPassword: toRet.setPassword(initialPassword) return toRet
def __init__(self, host, port): """ Constructs an instance of DeadlineCon. Params: host name of the web service (string) port number the web service is listening on (integer) """ #Builds the ConnectionProperty object used for sending requests address = host + ":" + str(port) self.connectionProperties = ConnectionProperty(address) #The different request groups use the ConnectionProperty object to send their requests self.Jobs = Jobs.Jobs(self.connectionProperties) self.SlavesRenderingJob = SlavesRenderingJob.SlavesRenderingJob( self.connectionProperties) self.Tasks = Tasks.Tasks(self.connectionProperties) self.TaskReports = TaskReports.TaskReports(self.connectionProperties) self.JobReports = JobReports.JobReports(self.connectionProperties) self.LimitGroups = Limits.LimitGroups(self.connectionProperties) self.Pulse = Pulse.Pulse(self.connectionProperties) self.Repository = Repository.Repository(self.connectionProperties) self.MappedPaths = MappedPaths.MappedPaths(self.connectionProperties) self.MaximumPriority = MaximumPriority.MaximumPriority( self.connectionProperties) self.Pools = Pools.Pools(self.connectionProperties) self.Groups = Groups.Groups(self.connectionProperties) self.Plugins = Plugins.Plugins(self.connectionProperties) self.Slaves = Slaves.Slaves(self.connectionProperties) self.Users = Users.Users(self.connectionProperties) self.Balancer = Balancer.Balancer(self.connectionProperties)
def do_POST(self, messageOverride = None): #For GroupMe messages and server passwords if messageOverride: #Allow us to test without stealing the other server messageBody = messageOverride else: #Read all info from web response messageBody = self.getContent() try: #Block differentiating between groupMe responses and website messages message = json.loads(messageBody) except json.decoder.JSONDecodeError: #Failure is a website request and not a GroupMe request log.info.debug("Received a normal http POST message") self.body = messageBody #We actually need this... Website.handleRequest("POST", self) #Give web request with the message and headers else: #Success is for a groupMe message log.info.debug("Received GroupMe Message") ### Note: The way to implement headers is "send_response, send_header, send_header..., end_headers" ### Also: For writing body, just use self.wfile.write after end headers self.send_response(200) #Reply that we have received the message. No further response is needed self.end_headers() log.network.debug("Message received:", message) message = Commands.Message(message) #Give us all our nice functions #Group not existing can raise KeyError, terminating futher processing try: workingGroup = Groups.getGroup(message.group_id) except AttributeError: log.info.error("NO GROUP IN MESSAGE. MESSAGE: ", message) else: #There is a group in the message if workingGroup: #If the group exists log.info.debug("Handling message for Group",workingGroup.ID) workingGroup.handleMessage(message) #Yes, let us pass all the hard work to the helper files else: log.info.error("No group found associated with",message.group_id)
def do_POST(self, messageOverride = None): #For GroupMe messages and server passwords if messageOverride: #Allow us to test without stealing the other server messageBody = messageOverride else: #Read all info from web response messageBody = self.getContent() try: #Block differentiating between groupMe responses and website messages message = json.loads(messageBody) except json.decoder.JSONDecodeError: #Failure is a website request and not a GroupMe request log.info.debug("Received a normal http POST message") parsedURL = self.getParsedPath() Website.handleRequest("POST", parsedURL, self.headers) #Give web request with the message and headers else: #Success is for a groupMe message log.info.debug("Received GroupMe Message") ### Note: The way to implement headers is "send_response, send_header, send_header..., end_headers" ### Also: For writing body, just use self.wfile.write after end headers self.send_response(200) #Reply that we have received the message. No further response is needed self.end_headers() log.network.debug("Message received:", message) message = Commands.Message(message) #Give us all our nice functions #Group not existing can raise KeyError, terminating futher processing try: workingGroup = Groups.getGroup(message.group_id) except AttributeError: log.info.error("NO GROUP IN MESSAGE. MESSAGE: ", message) else: #There is a group in the message if workingGroup: #If the group exists log.info.debug("Handling message for Group",workingGroup.ID) workingGroup.handleMessage(message) #Yes, let us pass all the hard work to the helper files else: log.info.error("No group found associated with",message.group_id)
def makeCollective(id, groupID, put, classType = Groups.CollectiveGroup): toRet = Groups.getGroup(id) if not toRet: toRet = classType(id, groupID) user = toRet.users.addUser(Users.User(toRet, put[0])).setToken(put[1]) user.save() return toRet
def makeCollector(id, groupID, put, groupCollective): toRet = Groups.getGroup(id) if not toRet: toRet = Groups.CollectorGroup(id, groupID, groupCollective) user = toRet.users.addUser(Users.User(toRet, put[0])).setToken(put[1]) user.save() return toRet
def addGroup(playerList, idNum, groupList, groupID=-1): index = findpNum(playerList, idNum) if (groupID == -1): groupID = input( "Please enter the group ID of the group you would like to add this player to: " ) try: groupID = int(groupID) except: print("Not a valid integer. Group add failed.") return if groupID in playerList[index][11]: print("Player already in group {}".format(groupID)) else: playerList[index][11].append(groupID) print("Player added successfully.") Groups.printGroup(playerList, groupID, groupList)
def __init__(self, parsedUrl, headers, handler): self.handler = handler self.url = parsedUrl self.headers = headers groupNum = re.search("\AGroup (\d+)", self.url.path.lstrip("/")) self.group = Groups.getGroup(int(groupNum.group(1))) if groupNum else None #log.debug("Group: ", self.group) log.net.low("New Handler for Url: ", self.url)
def __init__(self, username): self.username = username; self.reddit = None; self.key = None; try: self.fp = open('groups_' + self.username + '.json', 'a+') self.groups = g.Groups(self.fp); except IOError: print("Fatal error opening the groups file") raise IOError
def buildGroupAlignments(D, namD, rev_namD, F, pD): groups = Groups.groupAlignmentDict(D, namD) aliD = dict() for i, group in enumerate(groups): subF = dict((nam, F[rev_namD[nam]]) for nam in group) ali = runAlignment.runAlignment(subF, pD, alignment_type='pairwise', quick=False, keep_failed=True) aliD[i] = ali return (aliD)
def do_selectionScreen(self): log.web.debug("Sending Selection Screen") basicFile = self.loadFile(self.fileName) content = "" for group in Groups.getSortedList(groupType = Groups.MainGroup): #Get a list of all the main groups if group.getID() != 99: #If is not error group content += dedent("""\ <tr onclick="document.location = '{group}/index.html'"> <td valign="middle" style="text-align:center"><p style="font-size:110%;margin:5pt">{groupName}</p><p style="font-size:100%;font-style:italic;color:#008800;margin:5pt">Group {group}</p></td> <td width = 1pt><img src="{groupImage}" style="vertical-align:middle;width:90px"></td> </tr>""".format(group = group.getID(), groupName = group.getName(), groupImage = group.image or self.PAGE_ICON)) basicFile = basicFile.replace(self.STR_CONTENT, content) self.writeText(basicFile) self.sendResponse() #Send good response
def showGroupResults(playerList, groupList): try: groupNum = int(input("Enter group number: ")) except: print("Invalid group ID") return group = Groups.makeGroup(playerList, groupNum) try: print("Results within {} group:".format(groupList[groupNum - 1])) except: print("Results within unnamed group {}:".format(groupNum)) Castle.printRecord(group) details = input( "Would you like to view detailed match by match info? [y/n]: ").lower( ) if (details == "yes" or details == "y"): head2head.printAll1v1(group)
def __init__(self, handler): self.handler = handler self.url = urlparse(handler.path) self.params = parse_qs(self.url.query) or {} #log.debug("Path: ", handler.path) #log.debug("URL: ", self.url) #log.debug("Params:",self.params) #List of request headers self.headers = handler.headers #The local file path to get files from self.fileName = os.path.normpath(self.url.path).strip(os.sep) #Strip these slashes from both sides or else things mess up when loading files #Organize the cookies (if we have any) self.cookies = http.cookies.BaseCookie(self.handler.headers['cookie']) if ('cookie' in self.handler.headers) else None self.group = None #The group number self.groupObj = None #The group object self.responseSent = False #After we call "sendResponse" then we can't send headers again #We won't actually send data until we are sure that we have it all self.buffer = "".encode(self.ENCODING) #Checking for a group folder try: splitPath = os.path.split(self.fileName) #splits into (everything besides tail, tail) #NOTE: A really nice thing about this is that all hyperlinks are paths relative to a folder unless otherwise specified :D #NOTE ON IMPLEMENTATION: this naiive assumption is that we will never be in a folder besides base or a group number self.group = int(splitPath[0]) #I expect the most folder complexity to be "group/file" self.groupObj = Groups.getGroup(self.group) self.fileName = splitPath[1] #If we have a group, modify the fileName to not contain the group except ValueError: #Not part of a group pass if self.genFiles == None: #If the list of files isn't loaded self.loadGenFiles() #log.debug("Group: ", self.group) log.web.low("New Handler for Url: ", self.url)
import ProjectMgr import transformations r2d = 180.0 / math.pi d2r = math.pi / 180.0 parser = argparse.ArgumentParser(description='Set the aircraft poses from flight data.') parser.add_argument('--project', required=True, help='project directory') args = parser.parse_args() proj = ProjectMgr.ProjectMgr(args.project) print("Loading image info...") proj.load_images_info() groups = Groups.load(proj.analysis_dir) # compute an average transform between original camera attitude estimate # and optimized camera attitude estimate quats = [] for i, image in enumerate(proj.image_list): if image.name in groups[0]: print(image.name) ned, ypr, q0 = image.get_camera_pose(opt=False) ned, ypr, q1 = image.get_camera_pose(opt=True) # rx = q1 * conj(q0) conj_q0 = transformations.quaternion_conjugate(q0) rx = transformations.quaternion_multiply(q1, conj_q0) rx /= transformations.vector_norm(rx) print(' ', rx) (yaw_rad, pitch_rad, roll_rad) = transformations.euler_from_quaternion(rx, 'rzyx')
def __init__(self, data_dir='../data/'): self._data_dir = data_dir self._matches = None self._groups = Groups.Groups(self._data_dir) self._points = {} self._dataframe = None
#source_file = os.path.join(args.project, 'matches_direct' ) opt_file = os.path.join(args.project, 'matches_opt') if args.refine and os.path.isfile(opt_file): print('Match file:', opt_file) matches = pickle.load(open(opt_file, "rb")) elif os.path.isfile(source_file): print('Match file:', source_file) matches = pickle.load(open(source_file, "rb")) else: print("Cannot find a matches file to load... aborting") quit() print('Match features:', len(matches)) # load the group connections within the image set groups = Groups.load(args.project) print('Main group size:', len(groups[0])) opt = Optimizer.Optimizer(args.project) opt.setup(proj, groups[0], matches, optimized=args.refine) cameras, features, cam_index_map, feat_index_map, fx_opt, fy_opt, cu_opt, cv_opt, distCoeffs_opt = opt.run( ) # mark all the optimized poses as invalid for image in proj.image_list: opt_cam_node = image.node.getChild('camera_pose_opt', True) opt_cam_node.setBool('valid', False) for i, cam in enumerate(cameras): image_index = cam_index_map[i] image = proj.image_list[image_index]
def print_group_msg(msg): ''' 群聊信息处理 :param msg: :return: ''' print("Group") print(msg) try: dict_msg = msg.raw # message对象字典 menber = dict_msg['ActualNickName'] # 发言人 group_name = msg.chat.name # 群名称 times = time.localtime(dict_msg['CreateTime']) # 发言时间戳 dt = "%s-%s-%s %s:%s:%s" % (times[0], times[1], times[2], times[3], times[4], times[5]) # 格式化时间 print dt filename = dict_msg['FileName'] # 发送文件名称 group = groupDao.findGroup(group_name) # 获取当前群信息 主要是group_id group_id = 0 if group == None: # 群在数据库中不存在,则添加新的群信息 newgroup = Groups.Group() newgroup.group_name = group_name newgroup.number = len(msg.chat) print groupDao.addGroup(newgroup) group_id = groupDao.findGroup(group_name)[0] else: group_id = group[0] except Exception as e: print e.message message = Messages.Message() message.group_id = group_id message.member = menber message.create_time = dt try: if msg.type == TEXT: # 发言保存到数据库 text = dict_msg['Content'] # 发言内容 message.text = text messageDao.addMessage(message) if u"@%s" % bot.self.name in msg.text: # @机器人信息 text_key = msg.text[len(u"@%s" % bot.self.name):] print text_key deal_reply(msg, keywords=text_key) # url_1 = ' http://test2.bicoin.info/robot/autoReply?keyword=%s'% text # r = requests.get(url_1) # dict_result = r.json() # print dict_result # if dict_result['code'] and dict_result['type'] == "2": # return dict_result['data'] else: # 普通信息 deal_reply(msg) if msg.type == NOTE: group = msg.chat group.update_group(True) print len(group) # bot.groups()[0].update_group(True) if msg.type == RECORDING: # 记录录音 if not os.path.exists("recording"): os.mkdir("recording") filename = u"recording/%s" % filename msg.get_file(filename) # filename 存储路径 duration = int(math.ceil(dict['VoiceLength'] / 1000)) message.recording = filename message.duration = duration messageDao.addMessage(message) if msg.type == PICTURE: # 存储图片 if not os.path.exists("image"): os.mkdir("image") filename = u"image/%s" % filename msg.get_file(filename) # filename 存储路径 message.picture = filename messageDao.addMessage(message) if msg.type == ATTACHMENT: # 存储文件 if not os.path.exists("file"): os.mkdir("file") filename = u"file/%s" % filename msg.get_file(filename) # filename 存储路径 if msg.type == VIDEO: # 存储视频 if not os.path.exists("video"): os.mkdir("video") filename = u"video/%s" % filename msg.get_file(filename) # filename 存储路径 if msg.type == SHARING: print dict_msg['Url'] except Exception as e: print e, e.message pass
def main(): """Initialize All Modules""" tokenList = Files.getTokenList() #[0] should be mine, and [1] should be my alt for group creation log.debug("Tokens:",tokenList) #Just my user id and token put = ("27094908", tokenList[0]) #Totally Not The NSA Token Groups.Group.overlord = tokenList[1] #Just things log.network.debug.disable() #Suppress the return value of every message #log.command.low.enable() #For going through all the commands every time we get a command #log.user.low.enable() #For going through all the users every time we search for a user if Events.IS_TESTING: log.save.low.enable() #First load all the groups log.info("========== PRE-INIT (LOAD) ==========") toLoadList = [] for folder in Files.getDirsInDir(): if "Group " in folder: #If it a folder containing a group to load number = int(folder.split(" ")[-1]) obj = (number, folder,) #Tuple of number and folder name flag = True for i in range(len(toLoadList)): #Sort the list if number < toLoadList[i][0]: toLoadList.insert(i, obj) flag = False break if flag: #If did not insert anywhere else toLoadList.append(obj) #Loadsd the groups guarenteed in order for group in toLoadList: Groups.loadGroup(group[1]) log.info("Groups: ", Groups.getSortedList()) #Do init and post-init log.info("========== INIT ==========") for group in list(Groups.getSortedList()): group.init() ### Named groups should be made after INIT to avoid duplicated initial users testGroup = makeNamedGroup(1, "23199161", put) toriGroup = makeNamedGroup(15, "23317842", put, "DLARulez") groupFam = makeNamedGroup(2, "13972393", put, "easier") groupOldRocket = makeNamedGroup(10, "26730422", put, "password") rocketMainGroup = makeCollective(20, "33057510", put) electronicsGroup = makeCollector(21, "33057523", put, rocketMainGroup) designAndMGroup = makeCollector(22, "33058451", put, rocketMainGroup) propulsionGroup = makeCollector(23, "33058488", put, rocketMainGroup) civGroup = makeCollective(30, "36614847", put, classType = Groups.Group) #Just a collective because I'm lazy in properly naming things. Is a normal group try: #This is so we can have our finally block remove any extra threads in case of error log.info("========== POST-INIT ==========") for group in list(Groups.getSortedList()): try: group.postInit() except AssertionError: pass log.info("========== GROUP CLEANUP ==========") deletionList = Groups.getSortedList() deletionList.reverse() for i in deletionList.copy(): if i.markedForDeletion: log.info("Deleting group", i) i.deleteSelf() del i del deletionList #try: def postEarlyMorningFact(): joke = Jokes.funFacts.getJoke() if type(joke) == tuple: return Jokes.funFacts._postJoke(groupFam, ("Oh boy 3 A.M.!\n"+joke[0], joke[1])) return Jokes.funFacts._postJoke(groupFam, "Oh boy 3 A.M.!\n" + joke) def updateAllMsgLists(): for searcher in MsgSearch._searcherList: #We could also probably get from all active groups instead of the searcher list searcher.GenerateCache() def postCivReminder(): civGroup.handler.write("Don't forget to do your civ turn!") server = Server(('', Network.SERVER_CONNECTION_PORT), ServerHandler) #Update things for the groups every day at 5 a.m. log.info("Starting daily triggers") updaterDaily = Events.DailyUpdater( time(5, 0), Groups.groupDailyDuties) updaterWebsite = Events.DailyUpdater( time(4,58), Website.securityPurge) #Just do this seperately earlyMorningFacts = Events.DailyUpdater( time(3, 0), postEarlyMorningFact) monthlyMsgRefresh = Events.WeeklyUpdater(time(5,10), Events.WEEKDAY.SATURDAY, updateAllMsgLists, unitDifference = 4) #Once a month dailyCivReminder = Events.DailyUpdater( time(15,0), postCivReminder) log.info("========== BEGINNING SERVER RECEIVING ==========") try: log.web("Starting server on port",Network.SERVER_CONNECTION_PORT) server.serve_forever() except KeyboardInterrupt: pass if server.exitValue != None: #Value of none means exited due to KeyboardInterrupt or something else log.info("Server shutting down from user input") if server.exitValue: #Exit value true means restart return 0; else: #False means shutdown raise AssertionError("Signal to main that we are done") #TESTING CODE: if Events.IS_TESTING: import traceback while True: print("> ", end = "") try: statement = input() if statement.lower() == "quit": break elif "=" in statement: exec(statement) else: print(eval(statement)) except Exception as e: if isinstance(e, KeyboardInterrupt) or isinstance(e, EOFError): from os import _exit _exit(0) #Screw this crap, just get out of here. It's only for testing else: traceback.print_exc() raise AssertionError("Signal to main that we are done") #We need to kill all threads before exiting finally: Events.stopAllTimers() Events.SyncSave().saveAll(final = True)
def __init__(self, window_class, window, fpsclock): self.window_class = window_class self.window = window self.clock = fpsclock self.groups = Groups() self.fps = False self.fpsmeter = None self.player = Player(window_class, (450, 450), 10, 10, (0, 0), self.groups) self.deathscreen_ticker = 255 self.groups.addtogroup(self.player, self.groups.sprites) with open('levels/lvl_1.json', 'r') as data_file: data = json.loads(data_file.read(), parse_float=decimal.Decimal) for object in data["scene"]["objects"]: if data["scene"]["objects"][object]["type"] == 'wall': x = int(data["scene"]["objects"][object]["x"]) y = int(data["scene"]["objects"][object]["y"]) width = int(data["scene"]["objects"][object]["width"]) height = int(data["scene"]["objects"][object]["height"]) color = ( int(data["scene"]["objects"][object]["color"][0]), int(data["scene"]["objects"][object]["color"][1]), int(data["scene"]["objects"][object]["color"][2]) ) damp = float(data["scene"]["objects"][object]["dampening"]) fric = float(data["scene"]["objects"][object]["friction"]) soft = bool(data["scene"]["objects"][object]["soft"]) emitter = bool(data["scene"]["objects"][object]["emitter"]) wall = Wall(x, y, width, height, color, damp, fric, soft) self.groups.addtogroup(wall, self.groups.walls) if emitter: self.groups.addtogroup(wall, self.groups.emitters) elif data["scene"]["objects"][object]["type"] == "text": text = data["scene"]["objects"][object]["text"] x = int(data["scene"]["objects"][object]["x"]) y = int(data["scene"]["objects"][object]["y"]) font = data["scene"]["objects"][object]["font"] size = int(data["scene"]["objects"][object]["size"]) antialias = bool(data["scene"]["objects"][object]["antialias"]) color = ( int(data["scene"]["objects"][object]["color"][0]), int(data["scene"]["objects"][object]["color"][1]), int(data["scene"]["objects"][object]["color"][2]) ) textobj = Text(self.window, x, y, size, font, text, antialias, color) self.groups.addtogroup(textobj, self.groups.text) for property in data["scene"]["properties"]: if property == "music": music = pygame.mixer.Sound(data["scene"]["properties"]["music"]) music.play(-1, fade_ms=1000) elif property == "fps" and bool(data["scene"]["properties"]["fps"]): self.fps = True pos = ( int(data["scene"]["properties"]["fps_pos"][0]), int(data["scene"]["properties"]["fps_pos"][1]) ) fpstext = str(self.clock.get_fps()) + " FPS" self.fpsmeter = Text(self.window, pos[0], pos[1], 20, None, fpstext, True, (255, 255, 255)) self.groups.addtogroup(self.fpsmeter, self.groups.text)
def __init__(self, window_class, window, fpsclock): self.window_class = window_class self.window = window self.clock = fpsclock self.groups = Groups() self.fps = False self.fpsmeter = None self.player = Player(window_class, (450, 450), 10, 10, (0, 0), self.groups) self.deathscreen_ticker = 255 self.groups.addtogroup(self.player, self.groups.sprites) with open('levels/lvl_1.json', 'r') as data_file: data = json.loads(data_file.read(), parse_float=decimal.Decimal) for object in data["scene"]["objects"]: if data["scene"]["objects"][object]["type"] == 'wall': x = int(data["scene"]["objects"][object]["x"]) y = int(data["scene"]["objects"][object]["y"]) width = int(data["scene"]["objects"][object]["width"]) height = int(data["scene"]["objects"][object]["height"]) color = (int(data["scene"]["objects"][object]["color"][0]), int(data["scene"]["objects"][object]["color"][1]), int(data["scene"]["objects"][object]["color"][2])) damp = float(data["scene"]["objects"][object]["dampening"]) fric = float(data["scene"]["objects"][object]["friction"]) soft = bool(data["scene"]["objects"][object]["soft"]) emitter = bool(data["scene"]["objects"][object]["emitter"]) wall = Wall(x, y, width, height, color, damp, fric, soft) self.groups.addtogroup(wall, self.groups.walls) if emitter: self.groups.addtogroup(wall, self.groups.emitters) elif data["scene"]["objects"][object]["type"] == "text": text = data["scene"]["objects"][object]["text"] x = int(data["scene"]["objects"][object]["x"]) y = int(data["scene"]["objects"][object]["y"]) font = data["scene"]["objects"][object]["font"] size = int(data["scene"]["objects"][object]["size"]) antialias = bool(data["scene"]["objects"][object]["antialias"]) color = (int(data["scene"]["objects"][object]["color"][0]), int(data["scene"]["objects"][object]["color"][1]), int(data["scene"]["objects"][object]["color"][2])) textobj = Text(self.window, x, y, size, font, text, antialias, color) self.groups.addtogroup(textobj, self.groups.text) for property in data["scene"]["properties"]: if property == "music": music = pygame.mixer.Sound( data["scene"]["properties"]["music"]) music.play(-1, fade_ms=1000) elif property == "fps" and bool( data["scene"]["properties"]["fps"]): self.fps = True pos = (int(data["scene"]["properties"]["fps_pos"][0]), int(data["scene"]["properties"]["fps_pos"][1])) fpstext = str(self.clock.get_fps()) + " FPS" self.fpsmeter = Text(self.window, pos[0], pos[1], 20, None, fpstext, True, (255, 255, 255)) self.groups.addtogroup(self.fpsmeter, self.groups.text)
def main(): """Initialize All Modules""" tokenList = Files.getTokenList() #[0] should be mine, and [1] should be my alt for group creation log.debug("Tokens:",tokenList) #Just my user id and token put = ("27094908", tokenList[0]) #Totally Not The NSA Token Groups.Group.overlord = tokenList[1] #Just things #log.network.debug.disable() log.command.low.enable() log.user.low.enable() #First load all the groups log.info("========== PRE-INIT (LOAD) ==========") toLoadList = [] for folder in Files.getDirsInDir(): if "Group " in folder: #If it a folder containing a group to load number = int(folder.split(" ")[-1]) obj = (number, folder,) #Tuple of number and folder name flag = True for i in range(len(toLoadList)): #Sort the list if number < toLoadList[i][0]: toLoadList.insert(i, obj) flag = False break if flag: #If did not insert anywhere else toLoadList.append(obj) #Loadsd the groups guarenteed in order for group in toLoadList: Groups.loadGroup(group[1]) log.info("Groups: ", Groups.getSortedList()) #Do init and post-init log.info("========== INIT ==========") for group in list(Groups.getSortedList()): group.init() ### Named groups should be made after INIT to avoid duplicated initial users testGroup = makeNamedGroup(1, "23199161", put) toriGroup = makeNamedGroup(15, "23317842", put) groupFam = makeNamedGroup(2, "13972393", put) groupFam.setBot("cfe41d49a83d73874f4aa547b9") try: #This is so we can have our finally block remove any extra threads in case of error log.info("========== POST-INIT ==========") for group in list(Groups.getSortedList()): try: group.postInit() except AssertionError: pass log.info("========== GROUP CLEANUP ==========") deletionList = Groups.getSortedList() deletionList.reverse() for i in deletionList.copy(): if i.markedForDeletion: log.info("Deleting group", i) i.deleteSelf() del i del deletionList #try: def postEarlyMorningFact(): joke = Jokes.funFacts.getJoke() if type(joke) == tuple: return Jokes.funFacts._postJoke(groupFam, ("Oh boy 3 A.M.!\n"+joke[0], joke[1])) return Jokes.funFacts._postJoke(groupFam, "Oh boy 3 A.M.!\n" + joke) server = Server(('', Network.SERVER_CONNECTION_PORT), ServerHandler) #Update things for the groups every day at 5 a.m. log.info("Starting daily triggers") updaterDaily = Events.PeriodicUpdater(time(5, 0), timedelta(1), Groups.groupDailyDuties) earlyMorningFacts = Events.PeriodicUpdater(time(3, 0), timedelta(1), postEarlyMorningFact) log.info("========== BEGINNING SERVER RECEIVING ==========") try: server.serve_forever() except KeyboardInterrupt: pass if server.exitValue != None: #Value of none means exited due to KeyboardInterrupt or something else log.info("Server shutting down from user input") if server.exitValue: #Exit value true means restart return 0; else: #False means shutdown raise AssertionError("Signal to main that we are done") #TESTING CODE: if Events.IS_TESTING: import traceback while True: print("> ", end = "") try: statement = input() if statement.lower() == "quit": break elif "=" in statement: exec(statement) else: print(eval(statement)) except Exception as e: if isinstance(e, KeyboardInterrupt) or isinstance(e, EOFError): from os import _exit _exit(0) #Screw this crap, just get out of here. It's only for testing else: traceback.print_exc() raise AssertionError("Signal to main that we are done") #We need to kill all threads before exiting finally: Events.stopAllTimers() Events.SyncSave().saveAll(final = True)
i = p1[0] j = p2[0] image = proj.image_list[i] image.match_list[j].append([p1[1], p2[1]]) # for i in range(len(proj.image_list)): # print(len(proj.image_list[i].match_list)) # print(proj.image_list[i].match_list) # for j in range(len(proj.image_list)): # print(i, j, len(proj.image_list[i].match_list[j]), # proj.image_list[i].match_list[j]) else: proj.load_match_pairs(extra_verbose=False) # compute the group connections within the image set. groups = Groups.groupByFeatureConnections(proj.image_list, matches) #groups = Groups.groupByConnectedArea(proj.image_list, matches) #groups = Groups.groupByImageConnections(proj.image_list) groups.sort(key=len, reverse=True) Groups.save(args.project, groups) print('Main group size:', len(groups[0])) # this is extra (and I'll put it here for now for lack of a better # place), but for visualization's sake, create a gnuplot data file # that will show all the match connectivity in the set. file = os.path.join(args.project, 'connections.gnuplot')
'interactively review reprojection errors from worst to best and select for deletion or keep.' ) args = parser.parse_args() proj = ProjectMgr.ProjectMgr(args.project) proj.load_area_info(args.area) area_dir = os.path.join(args.project, args.area) source = 'matches_grouped' print("Loading matches:", source) matches = pickle.load(open(os.path.join(area_dir, source), "rb")) print('Number of original features:', len(matches)) # load the group connections within the image set groups = Groups.load(area_dir) print('Group sizes:', end=" ") for group in groups: print(len(group), end=" ") print() opt = Optimizer.Optimizer(args.project) if args.initial_pose: opt.setup(proj, groups, args.group, matches, optimized=False) else: opt.setup(proj, groups, args.group, matches, optimized=True) x0 = np.hstack((opt.camera_params.ravel(), opt.points_3d.ravel(), opt.K[0, 0], opt.K[0, 2], opt.K[1, 2], opt.distCoeffs)) error = opt.fun(x0, opt.n_cameras, opt.n_points, opt.by_camera_point_indices, opt.by_camera_points_2d)
def GroupsTool(self): self.close() self.groups = Groups.Ui_Groups() self.groups.show()
proj.load_image_info() proj.load_features() proj.undistort_keypoints() #print("Loading direct matches...") #matches = pickle.load( open( os.path.join(args.project, 'matches_direct'), 'rb' ) ) print("Loading grouped matches...") matches = pickle.load(open(os.path.join(args.project, 'matches_grouped'), 'rb')) print("features:", len(matches)) # compute the group connections within the image set (not used # currently in the bundle adjustment process, but here's how it's # done...) #groups = Groups.groupByFeatureConnections(proj.image_list, matches) groups = Groups.groupByConnectedArea(proj.image_list, matches) Groups.save(args.project, groups) print('Main group size:', len(groups[0])) # this is extra (and I'll put it here for now for lack of a better # place), but for visualization's sake, create a gnuplot data file # that will show all the match connectivity in the set. file = os.path.join(args.project, 'connections.gnuplot') f = open(file, 'w') pair_dict = {} for match in matches: for m1 in match[1:]: for m2 in match[1:]: if m1[0] == m2[0]: # skip selfies