def main(): opts = parser.parse_args() # shared settings if opts.root: root = opts.root else: root = os.getcwd() if opts.config: config = Config(opts.config) else: default_config = os.path.join(root, "config") if os.path.isfile(default_config): config = Config(default_config) else: config = Config() # subcommands if "setup" == opts.subcommand: setup(root) elif "update-repos" == opts.subcommand: org = opts.org or config.organisation_name if org is None: update_repos_parser.print_help() sys.exit(1) token = opts.token or config.github_token if opts.file is None: filename = os.path.join(root, "repository-urls") else: filename = opts.file update_organisation_repos(org, token, filename) elif "scan-repo" == opts.subcommand: repo_location = opts.location scan_repo(repo_location, root) elif "scan-repo-list" == opts.subcommand: if opts.file is None: repo_urls_filename = os.path.join(root, "repository-urls") else: repo_urls_filename = opts.file scan_repo_list(repo_urls_filename, root) elif "history" == opts.subcommand: history_message = opts.message or "Dupin search results" history(root, history_message, opts.notify, config) elif "auto-scan-all" == opts.subcommand: repo_urls_filename = os.path.join(root, "repository-urls") scan_repo_list(repo_urls_filename, root) history(root, "Dupin search results", opts.notify, config) return
def create_game(self): self.end = False self.c = config() self.f = field(True, self.c.width, self.c.height, self.c.game) self.old_score = 0 self.history = history() self.history.save_state(self.f, self.f.p)
def save_image(url, tweet_url): # move to the repository os.chdir(os.path.dirname(os.path.abspath(__file__))) # load history hist = history() if os.path.exists("misc/history.pickle"): with open("misc/history.pickle", "rb") as f: hist = pickle.load(f) # save images basename = os.path.basename(url) filepath = "tmp/" + basename if not hist.contains(basename): hist.append(tweet_url, basename) r = requests.get(url) if r.status_code == 200: content_type = r.headers["content-type"] if "image" in content_type: # save an image if not os.path.isdir("tmp"): os.mkdir("tmp") with open(filepath, "wb") as f: f.write(r.content) # save history with open("misc/history.pickle", "wb") as f: pickle.dump(hist, f)
def __init__(self, surface, x, y, maxw, maxh, xspacing = 75, yspacing = 36): self.container = None #set by container when added self.x = x self.y = y self.xspacing = xspacing self.yspacing = yspacing self.border = 1 self.colour = colours['grey90'] self.shardhist = history(self) cols = maxw / self.xspacing # int div rows = maxh / self.yspacing self.width = cols*xspacing self.height = rows*yspacing xborder = (maxw - self.width)/2 yborder = (maxh - selfheight)/2 coldividers = [i*self.xspacing + xborder for i in xrange(0, cols)] rowdividers = [i*self.yspacing + yborder for i in xrange(0, rows)] self.cols = [column(self, c, y, xspacing, self.height, yspacing) for c in coldividers] self.rows = [row(self, x, r, yspacing, self.width, xspacing) for r in rowdividers] self.surface = pygame.Surface((maxw, maxh)).convert() self.surface.fill(colours["white"]) for c in self.cols: c.draw(surface)
def __init__(self, suffix, name, main, num_episodes): self.total_steps = 0 self.batch_size = 64 self.gamma = 0.99 self.gradient_update_step = 1 self.main_update_step = 2 self.grads = {} self.env = gym.make(name) oshape = self.env.observation_space.shape assert main.output_size == self.env.action_space.n assert oshape[0] == main.input_shape self.steps = history.history(self.batch_size) self.main = main self.num_episodes = num_episodes self.current_state = state.state(oshape[0], main.state_size) self.network = ann.ann('thread_' + suffix, main.input_size, main.output_size, main.swriter) self.network.import_params(main.network.export_params()) self.thread = threading.Thread(target=self.run)
def history_(): parent_directory = "/home/pi/Desktop/Apps/FireBeetleTesting/LightMonitor/TestData/" today = datetime.date.today() day = request.form.get("day", str(today.day)) if len(day) == 1: day = "0" + day month = request.form.get("month", str(today.month)) if len(month) == 1: month = "0" + month year = request.form.get("year", str(today.year)) daystring = f"{year}-{month}-{day}" path = parent_directory + daystring filepath = os.path.join(str(path), "dataFile.txt") submit = request.form.get("submit") if submit: return history(filepath, daystring, submit) return history(filepath, daystring, submit)
def send_ok(): sns =boto.sns.connect_to_region('ap-northeast-1') topics = sns.get_all_topics()["ListTopicsResponse"]["ListTopicsResult"]["Topics"] mytopic = topics[0] msg = u"Boss:\n Everything is ready !" print datetime.now().month, datetime.now().day msg+=u'\n\n\n\n\n'+ history.history(datetime.now().month,datetime.now().day).string subj = "成功完成等保申报任务" res = sns.publish(mytopic['TopicArn'], msg, subj)
def main(): global ourList # global list of all directives global defDict # global dictionary of DEFinitions global MDict # global dictionary of Messages global ADict # global dictionary of Actions signal.signal( signal.SIGALRM, signal.SIG_IGN ) signal.signal( signal.SIGHUP, SigHandler ) signal.signal( signal.SIGINT, SigHandler ) signal.signal( signal.SIGTERM, SigHandler ) # TODO: Is there a simpler Python-way of getting hostname ?? # TODO: Get the hostname at program startup, not here... tmp = os.popen('uname -n', 'r') hostname = tmp.readline() log.hostname = hostname[:-1] # strip \n off end tmp.close() # New history object history.eddieHistory = history.history() # initialise our global lists/dicts ourList = directive.Rules() defDict = {} MDict = definition.MsgDict() ADict = {} # read in config and rules parseConfig.readFile(config_file, ourList, defDict, MDict, ADict) directive.ADict = ADict # make ADict viewable in directive module action.MDict = MDict # make MDict viewable in action module # Main Loop while 1: try: # perform guts of Eddie eddieguts(history.eddieHistory) # email admin the adminlog if required log.sendadminlog() # sleep for set period - only quits with CTRL-c log.log( '<eddie>main(), sleeping for %d secs' % (config.scanperiod), 6 ) #print 'Press CTRL-C to quit' # Sleep by setting SIGALRM to go off in scanperiod seconds #time.sleep( config.scanperiod ) signal.alarm( config.scanperiod ) signal.pause() except KeyboardInterrupt: # CTRL-c hit - quit now log.log( '<eddie>main(), KeyboardInterrupt encountered - quitting', 1 ) print "\nEddie quitting ... bye bye" break
def run(self, num_episodes): rewards = history.history(100) for i in xrange(num_episodes): reward = self.episode() rewards.append(reward) print("{:4d}: steps: {:6d}, epsilon: {:.2f}, reward: {:2.1f}, average reward per {:3d} last episodes: {:.2f}".format( i, self.total_steps, self.epsilon, reward, rewards.size(), np.mean(rewards.whole())))
def send_ok(): sns = boto.sns.connect_to_region('ap-northeast-1') topics = sns.get_all_topics( )["ListTopicsResponse"]["ListTopicsResult"]["Topics"] mytopic = topics[0] msg = u"Boss:\n Everything is ready !" print datetime.now().month, datetime.now().day msg += u'\n\n\n\n\n' + history.history(datetime.now().month, datetime.now().day).string subj = "成功完成等保申报任务" res = sns.publish(mytopic['TopicArn'], msg, subj)
def show_history_page(self): interp = wi.wiki_interpreter(self.name) cont = "" if not interp.exists: self.show_edit_page(interp) return pageHist = history(self.name) out = templates.history_template(self.name, pageHist.listVersions()) self.send_response(out)
def save_wiki_page(self, page, content): LOG.debug("Saving WikiPage " + page) title = path.basename(page) wikipath = path.join(wiki_dir, title + ".txt") if content.strip() in ("remove", "delete"): os.remove(wikipath) return False else: f = open(wikipath, 'w') f.write(content) f.close() pageHist = history(title) pageHist.addPage(content) return True
def post(): # move to the repository os.chdir(os.path.dirname(os.path.abspath(__file__))) slack = slackweb.Slack(url=config.SLACK_URL) hist = history() with open("misc/history.pickle", "rb") as f: hist = pickle.load(f) files = os.listdir("img") for f in files: slack.notify(text=hist.get_url(f)) os.remove("img/" + f) os.removedirs("img")
def __init__(self, state_shape, actions, output_path): self.alpha = 1 self.gamma = 0.99 self.random_action_alpha = 1 self.random_action_alpha_cap = 1 self.ra_range_begin = 0.05 self.ra_range_end = 0.99 self.total_actions = 0 self.lam = 0.9 self.history_size = 100000 self.batch_size = 256 self.actions = actions self.history = history.history(self.history_size) output_path += '/run.%d' % (time.time()) self.summary_writer = tf.summary.FileWriter(output_path) self.main = nn.nn("main", state_shape[0], actions, self.summary_writer)
def rollback_history(self): interp = wi.wiki_interpreter(self.name) cont = "" if not interp.exists: self.show_edit_page(interp) return versionlst = self.attributes.get('version') if versionlst == None: self.show_wiki_page() version = versionlst[0] pageHist = history(self.name) rawText = pageHist.getVersion(version) self.save_wiki_page(self.name, rawText) self.show_wiki_page()
def view_history_page(self): interp = wi.wiki_interpreter(self.name) cont = "" if not interp.exists: self.show_edit_page(interp) return version = 'v1' if self.attributes.has_key('version'): version = self.attributes['version'][0] pageHist = history(self.name) rawText = pageHist.getVersion(version) interp = wi.wiki_interpreter(self.name, rawText) content = interp.parsed_content() out = templates.view_history_template(self.name, content, "NOT IMPLEMENTED", version) self.send_response(out)
def __init__(self, config): self.total_steps = 0 self.env = gym.make(config.get('game')) self.env = MaxAndSkipEnv(self.env) self.env = FireResetEnv(self.env) self.input_shape = config.get('input_shape') self.state_steps = config.get('state_steps') self.batch_size = config.get('batch_size') self.train_interval = config.get('train_interval') self.start_train_after_steps = config.get('start_train_after_steps') self.update_follower_steps = config.get('update_follower_steps') self.current_state = state.state(self.input_shape, self.state_steps) self.actions = self.env.action_space.n config.put('actions', self.actions) # used in network to create N outputs, one per action self.epsilon_start = config.get('epsilon_start') self.epsilon_end = config.get('epsilon_end') self.initial_explore_steps = config.get('initial_explore_steps') self.total_explore_steps = config.get('total_explore_steps') self.epsilon = self.epsilon_start self.alpha = config.get('q_alpha') self.discount_gamma = config.get('discount_gamma') self.history = history.history(config.get('history_size')) output_path = config.get('output_path') output_path += '/run.%d' % (time.time()) self.summary_writer = tf.summary.FileWriter(output_path) config.put('summary_writer', self.summary_writer) # used in network with tf.variable_scope('main') as vscope: self.main = network.network('main', config) with tf.variable_scope('follower') as vscope: self.follower = network.network('follower', config) self.follower.import_params(self.main.export_params(), 0)
def __init__(self, config): lg.debug("cli::__init__") self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(1) curses.curs_set(0) self.maxY, self.maxX = self.stdscr.getmaxyx() self.MAX_LIST_ITEMS = self.maxY - BOTTOM_OFFSET - 2 lg.debug("Maximum number for items is " + str(self.MAX_LIST_ITEMS)) self.MODE = mode.VIM hm = config.get("history_max", 5) self.browser = config.get("browser", None) self.history = history(hm) self.currObject = None self.msg = None self.setMsg("Revi started, config loaded from file, " "word peace achieved") self.drawLoading() l = listing("", rLimit=self.MAX_LIST_ITEMS) if l.ok: self.setCurrentObject(l) else: self.setCurrentObject(error(l.status)) if self.MODE is mode.VIM: self.eval = eval_vim(self.stdscr) else: # self.eval = eval_emacs(self.stdscr) pass self.help = help()
def __init__(self, config: Config): self.qna_maker = QnAMaker( QnAMakerEndpoint( knowledge_base_id=config.QNA_KNOWLEDGEBASE_ID, endpoint_key=config.QNA_ENDPOINT_KEY, host=config.QNA_ENDPOINT_HOST, ), QnAMakerOptions(score_threshold=0.9)) luis_application = LuisApplication( config.LUIS_APP_ID, config.LUIS_API_KEY, "https://" + config.LUIS_API_HOST_NAME, ) luis_options = LuisPredictionOptions(include_all_intents=True, include_instance_data=True) self.recognizer = LuisRecognizer(luis_application, luis_options, True) self.db_func = DB_function() self.favor = my_favorite() self.history = history()
def history(self): import history self.root.destroy() history.history(self.name)
import history imax = 160 hsize = 100 h = history.history(hsize) for i in range(imax): h.append(i) for i in h.sample(hsize): assert i >= imax - hsize and i < imax #print i for idx, stored in enumerate(h.whole()): assert stored == idx + imax - hsize #print stored
def bt2_clicked(self): self.form.hide() ui = history() ui.show() ui.exec_() self.form.show()
print '#'*75 print 'Yes , the installation will start quickly.' print '#'*75 print terminalColor.NONE else: print terminalColor.RED print '#'*75 print 'Sorry , now the script does not support this OS' print 'Of course , you can use -f option to continue.' print 'But I am not sure it will work' print '#'*75 print terminalColor.NONE sys.exit() if __name__ == '__main__': history.history() # check() createDir.createDir() pgplot.getPgplot() print '== Going to install calceph ===' calceph.install_calceph() print '== Going to install psrcat ===' psrcat.install_psrcat() print '== Going to install tempo ===' tempo.install_tempo() print '== Going to install tempo2 ===' tempo2.install_tempo2() print '== Going to install sigproc ===' sigproc.install_sigproc() print '== Going to install presto ===' presto.install_presto()
def train(epoch): toShow = [ "loss", "lossX", "lossY", "lossW", "lossH", "lossConf", "lossCls", "totalTime" ] trainHistory = history(trainHistoryFname, avgOver=averageHistoryOver, saveEvery=saveHistoryEvery, toShow=toShow) global processed_batches t0 = time.time() if ngpus > 1: cur_model = model.module else: cur_model = model train_loader = torch.utils.data.DataLoader(dataset.listDataset( trainlist, trainLabelFolder, shape=(init_width, init_height), shuffle=True, transform=transforms.Compose([ transforms.ToTensor(), ]), train=True, seen=cur_model.seen, batch_size=batch_size, num_workers=num_workers), batch_size=batch_size, shuffle=False, drop_last=True, **kwargs) lr = adjust_learning_rate(optimizer, processed_batches) logging('epoch %d, processed %d samples, lr %f' % (epoch, epoch * len(train_loader.dataset), lr)) model.train() t1 = time.time() for batch_idx, (data, target) in enumerate(train_loader): t2 = time.time() adjust_learning_rate(optimizer, processed_batches) processed_batches = processed_batches + 1 if use_cuda: data = data.cuda() #target= target.cuda() #this gets put on gpu later in region_loss, that way we only have 1 copy of it there t3 = time.time() data, target = Variable(data), Variable(target) t4 = time.time() optimizer.zero_grad() t5 = time.time() output = model(data) t6 = time.time() region_loss.seen = region_loss.seen + data.data.size(0) loss, lossData = region_loss(output, target) t7 = time.time() loss.backward() t8 = time.time() optimizer.step() t9 = time.time() lossData.update({ "loadDataTime": (t2 - t1), "cpuToCudaTime": t3 - t2, "cudaToVariableTime": t4 - t3, "zeroGradTime": t5 - t4, "forwardFeatureTime": t6 - t5, "forwardLossTime": t7 - t6, "backwardTime": t8 - t7, "stepTime": t9 - t8, "totalTime": t9 - t1 }) trainHistory(epoch, batch_idx, lossData) # log the history t1 = time.time() # reset at end to get data loading time if batch_idx % 50 == 0: print(trainHistory) if (epoch + 1) % save_interval == 0: logging('save weights to %s/%06d.weights' % (backupdir, epoch + 1)) cur_model.seen = (epoch + 1) * len(train_loader.dataset) cur_model.save_weights('%s/%06d.weights' % (backupdir, epoch + 1)) trainHistory.save( forceAll=True) # save all the remaining data in the history monitor
def school(ui, backgrounds, skill_list, pc): bg_by_name = { } for bg in backgrounds: bg_by_name[bg.name] = bg ui.clear() stuff = items.ItemCollection(items.ItemDefinitions(skill_list)) m = grid.Map(80, 24, stuff) apply_school_map(m, stuff) mm = grid.MapMemory(m) actors_by_pos = { } # add our boss npc_body = stuff.create_item('p', (textui.RED, textui.BLACK, textui.NORMAL), transparent=True, name="Iudictus", blocking=False) npc_stats = humans.Human() npc_stats.STR = 14 npc_stats.CON = 15 npc_stats.DEX = 14 npc_stats.SIZ = 15 npc_stats.compute() npc_stats.set_default_skills(bg_by_name["Legionary"], skill_list) npc_stats.skill_levels["Dodge"] = 100 npc_stats.skill_levels["Sword - Short"] = 140 gladius = stuff.create_item_from_def("gladius") npc_stats.equip_item(npc_stats.get_item(gladius)) tunic = stuff.create_item_from_def("tunic") npc_stats.equip_item(npc_stats.get_item(tunic)) boots = stuff.create_item_from_def("boots") npc_stats.equip_item(npc_stats.get_item(boots)) npc = humans.Observer(npc_stats, npc_body) m.drop_item_at(npc.human_item, 8, 12) actors_by_pos[(8, 12)] = npc # add some Christians npc_x = 4 npc_y = 3 for name in [ "Matthew", "Mark", ]: npc_body = stuff.create_item('p', NPC_COLOR, transparent=True, name="Christian", blocking=False) npc_stats = humans.Human() npc_stats.set_default_skills(bg_by_name["Christian"], skill_list) toga = stuff.create_item_from_def("toga") npc_stats.equip_item(npc_stats.get_item(toga)) sandals = stuff.create_item_from_def("sandals") npc_stats.equip_item(npc_stats.get_item(sandals)) npc = humans.Martyr(npc_stats, npc_body) m.drop_item_at(npc.human_item, npc_x, npc_y) actors_by_pos[(npc_x, npc_y)] = npc npc_x = npc_x + 2 npc_y = npc_y + 2 # add our player player = stuff.create_item('@', PLAYER_COLOR, True, blocking=False, name="you") player_x = 8 player_y = 5 pc.equip_item(pc.get_item(stuff.create_item_from_def("toga"))) pc.equip_item(pc.get_item(stuff.create_item_from_def("sandals"))) things_here = m.items_at(player_x, player_y) m.drop_item_at(player, player_x, player_y) player_actor = humans.Personality(pc, player) actors_by_pos[(player_x, player_y)] = player_actor (width, height) = ui.get_screen_size() player_history = history.history(width) # sprinkle some weapons around for club_loc in [(4,6), (5,7), (7,6), (8,6), (10,8)]: club = stuff.create_item_from_def("club") m.drop_item_at(club, club_loc[0], club_loc[1]) for shield_loc in [(2,6), (3,6), (5,6), (6, 7), (9, 8)]: shield = stuff.create_item_from_def("medium shield") m.drop_item_at(shield, shield_loc[0], shield_loc[1]) inv_ofs = 0 while True: player_state = pc.check_health() if player_state != "okay": return player_state textui.wait_for_minimum_size(ui, 80, 24) (width, height) = ui.get_screen_size() h_size = (width - 40) | 1 h_half = h_size // 2 v_size = ((height * 2) // 3) | 1 v_half = v_size // 2 view = mm.look_at(player_x - h_half, player_y - v_half, player_x + h_half, player_y + v_half, 8) display.main_display(ui, width, height, view, pc, player_history) # figure out what item we would get if we picked something up item_to_get = None for n in range(len(things_here)-2, -1, -1): if things_here[n].movable: item_to_get = n disabled = [ ] if item_to_get is None: disabled.append("g") if not m.can_move_onto(player_x, player_y-1): disabled.append("Up") if not m.can_move_onto(player_x, player_y+1): disabled.append("Down") if not m.can_move_onto(player_x-1, player_y): disabled.append("Left") if not m.can_move_onto(player_x+1, player_y): disabled.append("Right") attack = [ ] for (actor_x, actor_y) in actors_by_pos.keys(): if (actor_x == player_x-1) and (actor_y == player_y): attack.append("Left") elif (actor_x == player_x+1) and (actor_y == player_y): attack.append("Right") elif (actor_x == player_x) and (actor_y == player_y-1): attack.append("Up") elif (actor_x == player_x) and (actor_y == player_y+1): attack.append("Down") display.show_keys_help(ui, width, height, ("Esc", "Up", "Down", "Left", "Right", "g", "i"), disabled, attack) event = ui.get_input() if event is None: continue if event.event_type == 'resize': ui.clear() continue elif event.event_type == 'mouse': continue player_moved = False new_x = player_x new_y = player_y if event.event_type == 'keyboard': if event.key in keymap.keys_ul: new_x = player_x - 1 new_y = player_y - 1 elif event.key in keymap.keys_u: new_y = player_y - 1 elif event.key in keymap.keys_ur: new_x = player_x + 1 new_y = player_y - 1 elif event.key in keymap.keys_l: new_x = player_x - 1 elif event.key in keymap.keys_r: new_x = player_x + 1 elif event.key in keymap.keys_dl: new_x = player_x - 1 new_y = player_y + 1 elif event.key in keymap.keys_d: new_y = player_y + 1 elif event.key in keymap.keys_dr: new_x = player_x + 1 new_y = player_y + 1 elif event.key == ord('g'): if len(things_here) > 1: # TODO: need a menu of stuff to pick up if item_to_get is not None: if pc.get_item(things_here[item_to_get], player_history): m.pickup_item(things_here[item_to_get]) player_moved = True elif event.key == ord('i'): [ inv_ofs, drops ] = inventory(ui, pc, inv_ofs, player_history) for item in drops: m.drop_item_at(item, player_x, player_y) m.pickup_item(player) m.drop_item_at(player, player_x, player_y) ui.clear() elif event.key == textui.KEY_ESC: return # check for bump combat del actors_by_pos[(player_x, player_y)] if (new_x, new_y) in actors_by_pos: victim = actors_by_pos[(new_x, new_y)] victim_start_state = victim.human_info.check_health() combat.attack(pc, "You", pc.equip["right hand"], victim.human_info, "the %s" % victim.human_item.name, player_history) victim_end_state = victim.human_info.check_health() if victim_start_state == "okay": if victim_end_state == "dead": player_history.add("The %s dies" % victim.human_item.name) die_at(victim, m, new_x, new_y, player_history) del actors_by_pos[(new_x, new_y)] elif victim_end_state == "unconscious": player_history.add("The %s loses consciousness" % victim.human_item.name) elif victim_start_state == "unconscious": if victim_end_state == "dead": player_history.add("The %s dies" % victim.human_item.name) die_at(victim, m, new_x, new_y, player_history) del actors_by_pos[(new_x, new_y)] # we don't actually want to move, but we do use a turn new_x = player_x new_y = player_y player_moved = True # otherwise move elif m.can_move_onto(new_x, new_y): m.pickup_item(player) player_x, player_y = new_x, new_y things_here = m.items_at(player_x, player_y) if things_here: thing_str = map(lambda t: "a " + t.name.lower(), things_here) player_history.add("You see " + human_list(list(thing_str)) + " here") m.drop_item_at(player, player_x, player_y) player_moved = True actors_by_pos[(player_x, player_y)] = player_actor # if the player moved, the non-players can move too if player_moved: player.can_parry = True player.can_block = True player.can_dodge = True for actor in actors_by_pos.values(): if actor is player_actor: continue histories = [ ] if grid.item_in_view(actor.human_item, view): # TODO: each actor also needs a history... histories.append(player_history) if actor.human_info.check_health() == "okay": actor.take_turn(m, actors_by_pos, histories)
def test(epoch): def truths_length(truths): for i in range(50): if truths[i][1] == 0: return i toShow = ["loss", "precision", "recall", "fscore"] testHistory = history(testHistoryFname, avgOver=0, saveEvery=-1, toShow=toShow) #model.eval() # does not work in eval mode model.train() if ngpus > 1: cur_model = model.module else: cur_model = model num_classes = cur_model.num_classes anchors = cur_model.anchors num_anchors = cur_model.num_anchors totalOverall = 0.0 proposalsOverall = 0.0 correctOverall = 0.0 for batch_idx, (data, target) in enumerate(test_loader): total = 0.0 # reset these every batch proposals = 0.0 correct = 0.0 if use_cuda: data = data.cuda() data = Variable(data) #, volatile=True) output = model(data) _, lossData = region_loss( output, Variable(target) ) # don't need the loss values for anything, just the misc data optimizer.zero_grad() #remove the gradient from the optimizer output = output.data # get the data so we can work on it here all_boxes = get_region_boxes(output, conf_thresh, num_classes, anchors, num_anchors) for i in range(output.size(0)): boxes = all_boxes[i] boxes = nms(boxes, nms_thresh) #assert False # This is the function to draw the resulting boxes on the image #draw_img = plot_boxes_cv2(img, bboxes, None, class_names) truths = target[i].view(-1, 5) num_gts = truths_length(truths) total = total + num_gts for j in range(len(boxes)): if boxes[j][4] > conf_thresh: proposals = proposals + 1 for k in range(num_gts): box_gt = [ truths[k][1], truths[k][2], truths[k][3], truths[k][4], 1.0, 1.0, truths[k][0] ] best_iou = 0 best_j = -1 for j in range(len(boxes)): iou = bbox_iou(box_gt, boxes[j], x1y1x2y2=False) if iou > best_iou: best_j = j best_iou = iou if best_iou > iou_thresh and boxes[best_j][6] == box_gt[6]: correct = correct + 1 totalOverall += total proposalsOverall += proposals correctOverall += correct precision = 1.0 * correct / (proposals + eps) recall = 1.0 * correct / (total + eps) fscore = 2.0 * precision * recall / (precision + recall + eps) lossData.update({ "correctBBoxes": correct, "proposedBBoxes": proposals, "groundTruthBBoxes": num_gts, "totalBBoxes": total, "precision": precision, "recall": recall, "fscore": fscore }) testHistory(epoch, batch_idx, lossData) # log the history if batch_idx % 100 == 0: print(testHistory) precision = 1.0 * correctOverall / (proposalsOverall + eps) recall = 1.0 * correctOverall / (totalOverall + eps) fscore = 2.0 * precision * recall / (precision + recall + eps) logging("\nprecision: %f, recall: %f, fscore: %f" % (precision, recall, fscore)) testHistory.save(forceAll=True)
def main(): # Catch most important signals signal.signal( signal.SIGALRM, signal.SIG_IGN ) signal.signal( signal.SIGHUP, SigHandler ) signal.signal( signal.SIGINT, SigHandler ) signal.signal( signal.SIGTERM, SigHandler ) argflags = {} # dict of argument flags # Parse command-line arguments doArgs(sys.argv[1:], argflags) # parse arg-list (not program name) # TODO: Is there a simpler Python-way of getting hostname ?? tmp = os.popen('uname -n', 'r') hostname = tmp.readline() log.hostname = hostname[:-1] # strip \n off end tmp.close() #print "[DEBUG] hostname:",log.hostname # instantiate global Config object global Config Config = config.Config( '__main__' ) # New history object history.eddieHistory = history.history() # read in config and rules parseConfig.readConf(config_file, Config) if 'showconfig' in argflags.keys() and argflags['showconfig'] == 1: # Just display the configuration and exit print "---Displaying Eddie Configuration---" print Config eddieexit() # Main Loop while 1: try: # check if any config/rules files have been modified # if so, re-read config if Config.checkfiles(): log.log( '<eddie>eddieguts(), config files modified - reloading config', 7 ) # # reset config and read in config and rules global Config Config = config.Config( '__main__' ) # read in config and rules parseConfig.readConf(config_file, Config) # perform guts of Eddie eddieguts(Config, history.eddieHistory) # email admin the adminlog if required log.sendadminlog() # sleep for set period - only quits with CTRL-c log.log( '<eddie>main(), sleeping for %d secs' % (config.scanperiod), 6 ) #print '<eddie>main(), sleeping for %d secs' % (config.scanperiod) # Sleep by setting SIGALRM to go off in scanperiod seconds #time.sleep( config.scanperiod ) signal.alarm( config.scanperiod ) signal.pause() except KeyboardInterrupt: # CTRL-c hit - quit now log.log( '<eddie>main(), KeyboardInterrupt encountered - quitting', 1 ) print "\nEddie quitting ... bye bye" break
def webhook(): global reqContext print(request.get_json(silent=True, force=True)) reqContext = request.get_json(silent=True, force=True) print("webhook---->" + reqContext.get("result").get("action")) if reqContext.get("result").get("action") == "input.welcome.edwin": return welcome() elif reqContext.get("result").get("action") == "showpopularcategories": return showpopularcategories() elif reqContext.get("result").get("action") == "professionalcourses": return professional_courses.professionalcourses() elif reqContext.get("result").get("action") == "professionalcertificates": return professional_courses.professionalcertificates() elif reqContext.get("result").get("action") == "careeradvancement": return professional_courses.careeradvancement() elif reqContext.get("result").get("action") == "micromastersprograms": return professional_courses.micromastersprograms() elif reqContext.get("result").get("action") == "advancedskillsetcourses": return professional_courses.advancedskillsetcourses() elif reqContext.get("result").get("action") == "popularcourses": return popular_course.popularcourselist() elif reqContext.get("result").get("action") == "computerscience": return computer_science.computerscience() elif reqContext.get("result").get("action") == "data_and_statistics": return data_and_statistics.data_and_statistics() elif reqContext.get("result").get("action") == "business_management": return business_management.business_management() elif reqContext.get("result").get("action") == "language": return language.language() elif reqContext.get("result").get("action") == "economics_and_finance": return economics_and_finance.economics_and_finance() elif reqContext.get("result").get("action") == "engineering": return engineering.engineering() elif reqContext.get("result").get("action") == "humanities": return humanities.humanities() elif reqContext.get("result").get("action") == "life_sciences": return life_sciences.life_sciences() elif reqContext.get("result").get("action") == "science_courses": return science_courses.science_courses() elif reqContext.get("result").get("action") == "chemistry": return chemistry.chemistry() elif reqContext.get("result").get("action") == "electronics": return electronics.electronics() elif reqContext.get("result").get("action") == "environmental_studies": return environmental_studies.environmental_studies() elif reqContext.get("result").get("action") == "mathematics": return mathematics.mathematics() elif reqContext.get("result").get("action") == "medicine": return medicine.medicine() elif reqContext.get("result").get("action") == "physics": return physics.physics() elif reqContext.get("result").get("action") == "social_science": return social_science.social_science() elif reqContext.get("result").get("action") == "energy_and_earth_science": return energy_and_earth_science.energy_and_earth_science() elif reqContext.get("result").get("action") == "art_courses": return art_courses.art_courses() elif reqContext.get("result").get("action") == "architecture": return architecture.architecture() elif reqContext.get("result").get("action") == "art_and_culture": return art_and_culture.art_and_culture() elif reqContext.get("result").get("action") == "communication": return communication.communication() elif reqContext.get("result").get("action") == "design": return design.design() elif reqContext.get("result").get("action") == "food_and_nutrition": return food_and_nutrition.food_and_nutrition() elif reqContext.get("result").get("action") == "health_and_safety": return health_and_safety.health_and_safety() elif reqContext.get("result").get("action") == "history": return history.history() elif reqContext.get("result").get("action") == "music": return music.music() elif reqContext.get("result").get("action") == "law": return law.law() elif reqContext.get("result").get("action") == "BacktoWelcomeContent": return showpopularcategories() elif reqContext.get("result").get("action") == "BackToProfessionalCourses": return professional_courses.professionalcourses() else: print("Good Bye")
def history_route(): return history(db)
def main(): try: opts = parser.parse_args() # shared settings if opts.root: root = opts.root else: root = os.getcwd() if opts.config: config = Config(opts.config) else: default_config = os.path.join(root, "config") if os.path.isfile(default_config): config = Config(default_config) else: config = Config() # subcommands if "setup" == opts.subcommand: setup(root) elif "update-repos" == opts.subcommand: org = opts.org or config.organisation_name repo_exclusions = opts.repo_exclusions or config.repo_exclusions if org is None: update_repos_parser.print_help() sys.exit(1) token = opts.token or config.github_token include_forks = opts.include_forks or config.include_forks or False if opts.file is None: filename = os.path.join(root, "repository-urls") else: filename = opts.file update_organisation_repos(org, token, filename, repo_exclusions, include_forks) elif "scan-repo" == opts.subcommand: repo_location = opts.location scan_repo(repo_location, root) elif "scan-repo-list" == opts.subcommand: if opts.file is None: repo_urls_filename = os.path.join(root, "repository-urls") else: repo_urls_filename = opts.file scan_repo_list(repo_urls_filename, root) elif "history" == opts.subcommand: history_message = opts.message or "Dupin search results" history(root, history_message, opts.notify, config) elif "auto-scan-all" == opts.subcommand: repo_urls_filename = os.path.join(root, "repository-urls") scan_repo_list(repo_urls_filename, root) history(root, "Dupin search results", opts.notify, config) except: if config.smtp_configured(): stacktrace = traceback.format_exc().splitlines() message = dedent("""\ Dupin failed during execution of {operation} Failed at: {timestamp} Exception details: {stacktrace}""").format( operation=opts.subcommand, stacktrace="\n".join(stacktrace), timestamp=datetime.datetime.now().isoformat()) send_email_properly(message, config.notification_email, config.smtp_from, config.smtp_host, config.smtp_username, config.smtp_password) traceback.print_exc(file=sys.stderr) return
print 'Yes , the installation will start quickly.' print '#' * 75 print terminalColor.NONE else: print terminalColor.RED print '#' * 75 print 'Sorry , now the script does not support this OS' print 'Of course , you can use -f option to continue.' print 'But I am not sure it will work' print '#' * 75 print terminalColor.NONE sys.exit() if __name__ == '__main__': history.history() # check() createDir.createDir() pgplot.getPgplot() print '== Going to install calceph ===' calceph.install_calceph() print '== Going to install psrcat ===' psrcat.install_psrcat() print '== Going to install tempo ===' tempo.install_tempo() print '== Going to install tempo2 ===' tempo2.install_tempo2() print '== Going to install sigproc ===' sigproc.install_sigproc() print '== Going to install presto ===' presto.install_presto()