def update(self, idx): x = 2 * idx y = random.uniform(0, 1) if idx == 0: # Get the current time from the module constant previous_time = Initglobal.previous_time else: is_display = False while not is_display: current_time = int(time.time()) previous_time = Update.get_value() if current_time >= (previous_time + 2): is_display = True # Update the time into the module constant Update.update_value(current_time) else: time.sleep(0.010) self.xdata.append(x) self.ydata.append(y) # re-assign the x axis limits self.ax.set_xlim((self.xmax + self.xdata[-1]), max(self.xdata)) self.ax.figure.canvas.draw() self.line.set_data(self.xdata, self.ydata) return self.line,
def __init__(self, canvas, naam, unit, s): self.canvas = canvas self.naam = naam self.unit = unit self.s=s ###--- drawButtonsSide ---### nameModule = self.naam self.canvas.create_text(58,10, text='Module: %s'% nameModule, font = "Helvetica 14 bold", anchor=N) self.canvas.create_text(53,270, text='Manual:', anchor=N) self.buttonOn = Button(self.canvas, text = "On", state=NORMAL, command = self.manualOn) #Nog iets met dat die geselecteerd is, 'aan' staat self.buttonOn.configure(width = 7) # activebackground = "#33B5E5", self.buttonOn_window = self.canvas.create_window(66, 300, window=self.buttonOn) # anchor=NW, self.buttonOff = Button(self.canvas, text = "Off", state=DISABLED, command = self.manualOff) #anchor = SW , command = manual self.buttonOff.configure(width = 7) # activebackground = "#33B5E5", self.buttonOff_window = self.canvas.create_window(66, 325, window=self.buttonOff) # anchor=NW, # Updating the status and the temperature of the side controller updateSideController = Update(s, 2000, self.unit, self.canvas) updateSideController.keepPlotting()
def test(): # data cal_housing = fetch_california_housing() X = cal_housing['data'] Y = np.reshape(cal_housing['target'], (-1, 1)) # train models iters = 100 name = ["0", "1", "2", "3", "4"] model = [ SCNN(8, 1, 0, update=Update.Rprop()), SCNN(8, 1, 1, update=Update.Rprop()), SCNN(8, 1, 2, update=Update.Rprop()), SCNN(8, 1, 3, update=Update.Rprop()), SCNN(8, 1, 4, update=Update.Rprop()) ] error = np.zeros((len(model), iters)) for i in range(iters): for m in range(len(model)): error[m, i] = model[m].partial_fit(X, Y) print(i + 1, "complete") # plot results plt.figure() plt.title('Error Curves') for m in range(len(model)): plt.semilogy(error[m], label=name[m]) plt.legend() plt.show()
def update_command(): item = tview.item(tview.focus(), 'values') if (item == ""): pass else: Update.update(item) view_command()
def update(): uid = request.form['uid'] course = request.form['course'] newGrade = request.form['grade'] import Update if 'sig' in request.form: return Update.Update(uid, course, newGrade, request.form['sig']) else: return Update.Update(uid, course, newGrade)
def initializeMenu(InitFile="Standard"): Update.updateCupType('Init/Cups.ini') #updates the cup volume list Update.updateIngredientAlcohol( 'Init/AlcoholContent.ini' ) #updates the alcholic content of ingredients list Update.updateIngredientPump('Init/' + InitFile + '/Pumps.ini') #updates the ingredient pumps Update.updateIngredientList( 'Init/' + InitFile + '/Ingredients.ini') #updates a list of available ingredients Update.updateMenu('Init/' + InitFile + '/Menu.ini') #updates the menu and recipe instructions
def scrape_update(url): print print("Scraping {0}").format(url.strip()) page = urllib2.urlopen(url) soup = BeautifulSoup(page) scraped_update_url = url project_title = str(soup.find("div", {"class": "container"})) project_title_strip = [ '\n', "<div class=\"container\"><h1>", "</h1></div>" ] project_title = text_stripper(project_title, project_title_strip) if project_title == "Project not found": out_url = url.strip() + "\n" print url.strip( ) + " is an invalid url or the project has been removed from the domain." insert_count = 0 update_file("page_not_found.txt", out_url) else: project_title = str(soup.find("div", {"class": "container"})) project_title_strip = [ '\n', "<div class=\"container\"><h1>", "</h1></div>" ] project_title = text_stripper(project_title, project_title_strip) project_title = regex_strip(project_title, r"(.*?)<.*") print "Project Title: " + project_title update_list = soup.findAll("div", {"class": "update-box"}) insert_count = 0 for update in update_list: strip = ["\n"] strip_update = text_stripper(str(update), strip) strip = r".*?>.*?>(.*?)<.*" update_title = regex_strip(strip_update, strip) strip = r".*?>.*?>.*?>(.*?)<.*" update_date = regex_strip(strip_update, strip) update_strip = ["\n", "on"] update_date = text_stripper(update_date, update_strip) strip = r".*?>.*?>.*?>.*?>.*?>(.*)" update_text = regex_strip(strip_update, strip) update_text_strip = ['\n', "<br />", "<p>", "</p>", "</div>"] update_text = text_stripper(update_text, update_text_strip) out_update = Update(scraped_update_url, project_title, update_title, update_date, update_text) check = out_update.is_in_database() if check == False: print "Inserting {0} into database.".format( out_update.update_title) out_update.insert_into_database() insert_count += 1 else: print "'{0}' update already in database.".format( out_update.update_title) return insert_count
def start(): #TODO maby test internet and newsserver connection Settings.ROOT_PATH = Core.storage.join_path(Core.storage.join_path(Core.app_support_path, Core.config.bundles_dir_name) , 'PlexSpotnet.bundle' , 'Contents') Settings.IMAGE_DIR = Core.storage.join_path(Settings.ROOT_PATH , 'Resources' , "%s.jpg") Settings.DB_DIR = Core.storage.join_path(Settings.ROOT_PATH , 'Database') Settings.POST_DB = PostDatabase() Settings.FILTER_DB = FilterDatabase() if Settings.UPDATE_ON_BOOT: Update.start_update() return True
def check_online_updates(self): """Check for software updates in background""" import Update try: updates = Update.check_updates(options.get('check_beta'), options.get('update_winapp2'), self.append_text, lambda: gobject.idle_add(self.cb_refresh_operations)) if updates: gobject.idle_add(lambda: Update.update_dialog(self.window, updates)) except: traceback.print_exc() self.append_text(_("Error when checking for updates: ") + str(sys.exc_info()[1]), 'error')
def check_online_updates(self): """Check for software updates in background""" import Update try: updates = Update.check_updates(options.get('check_beta'), options.get('update_winapp2'), self.append_text, lambda: gobject.idle_add(self.cb_refresh_operations)) if updates: gobject.idle_add( lambda: Update.update_dialog(self.window, updates)) except: traceback.print_exc() self.append_text( _("Error when checking for updates: ") + str(sys.exc_info()[1]), 'error')
def update(self, url, currentVersion, key=None, fileName=None, targetPath=None, install=False): """Search for updates. If an update is found, it can notify the user or install the update and notify the end user that the update has been installed. Args: url (str): The url to download the package to install. currentVersion (str): The current version of the app running. key (str): If the system needs a key to access. Defaults to None. Return: str or None: The url found if install flag is False or None if no update is found. """ update = Update.Update(url, currentVersion) updateUrl = update.checkUpdates() if not updateUrl: return return updateUrl
def __init__(self, inputSize, outputSize, outputAct=Activation.Identity(), iweight=Initialize.zero, update=Update.Momentum(), error=Error.Mse(), regularization=Regularize.Zero()): # structure settings self.inputSize_ = inputSize + 1 self.outputSize_ = outputSize self.nParameters_ = self.inputSize_ * self.outputSize_ self.outputActivationObj_ = outputAct self.outputActivation_ = self.outputActivationObj_.f # training settings self.iweight_ = iweight self.errorObj_ = error self.errorFunc_ = error.f self.updateObj_ = update self.update_ = update.step self.regObj_ = regularization self.regLoss_ = self.regObj_.f # put in clean state self.initialize_()
def Check_hosts(): if Setting.getServer() == '': return None url = Update.GetUrl() try: remote = urllib2.urlopen(url + ':5009/hosts') Logger.info("Read the hosts file successful!") except: Logger.info("Read the hosts file unsuccessful!") return server_dict = {} while True: buf = remote.readline() if not buf: break if buf.startswith("#") or \ buf.startswith("127.0.0.1") or \ buf.startswith("::1"): pass else: splits = buf.split() if len(splits) >= 2: key = " ".join(splits[1:]) server_dict[key] = splits[0] update_hosts(server_dict)
def _flow_stats_reply_handler(self, ev): body = ev.msg.body self.logger.info('datapath ' 'in-port out-port eth-dst ' 'eth-src packets bytes ' 'ip-src ip-dst ') self.logger.info('---------------- ' '-------- -------- ----------------- ' '----------------- -------- --------' '----------------- -----------------') bytsum = 0 for stat in sorted([flow for flow in body if flow.priority == 1]): src = None bytsum = bytsum + stat.byte_count if 'eth_src' in stat.match: src = stat.match['eth_src'] self.logger.info('%016x %8x %8x %17s %17s %8d %8d', ev.msg.datapath.id, stat.match['in_port'], stat.instructions[0].actions[0].port, stat.match['eth_dst'], src, stat.packet_count, stat.byte_count) #, # stat.match['ipv4_src'], stat.match['ipv4_dst']) for stat in sorted([flow for flow in body if flow.priority == 1]): Update.Update_CP(stat.instructions[0].actions[0].port, stat.match['eth_dst'], stat.byte_count * 1.0 / bytsum * 100)
def Simulate(self, simulation_loop=1, state_value_report=True): for looptime in range(simulation_loop): R = 0 is_end = False next_feature = False current_feature = -1 current_label = -1 self.Reset() while True: if is_end: Update.MonteCarlo_Update(R, self.state_list, self.state_action_label_value_map) break else: next_feature = Select.MonteCarlo_Epsilon_Select( self.feature_remaining, current_feature, current_label, self.state_action_label_value_map) Select.Erase_Feature(self.feature_remaining, next_feature) self.hypo_remaining_set = Observe.Observe_Subset( self.true_hypothesis, self.hypo_remaining_set, next_feature) Observe.Clear_Overlap(self.feature_remaining, self.hypo_remaining_set) is_end = Observe.Check_End(self.hypo_remaining_set) self.state_list.append( (current_feature, next_feature, current_label)) R += -1 current_label = self.true_hypothesis[next_feature] current_feature = next_feature if state_value_report: Report.Report_State_Value_Map(self.state_action_label_value_map)
def __init__(self, parent=None): QDialog.__init__(self, parent) #self.setAttribute(Qt.WA_DeleteOnClose) self.uiup = up.Ui_Dialog() self.a = self.uiup.setupUi(self) self.uiup.Btn_studentInf.clicked.connect(self.cont) self.uiup.Btn_Grade.clicked.connect(self.contGrade)
def update(self): Update.Update() infoBox = QMessageBox() infoBox.setIcon(QMessageBox.Information) infoBox.setText("Updated") infoBox.setWindowTitle("Information") infoBox.setStandardButtons(QMessageBox.Ok) infoBox.exec_()
def linearMnist(): model = LLS(n_components, 10, outputAct=Activation.Softmax(), update=Update.Rprop(), error=Error.JsDivergence(), regularization=Regularize.Ridge()) testMnist(model)
def start(): #TODO maby test internet and newsserver connection Settings.ROOT_PATH = Core.storage.join_path( Core.storage.join_path(Core.app_support_path, Core.config.bundles_dir_name), 'PlexSpotnet.bundle', 'Contents') Settings.IMAGE_DIR = Core.storage.join_path(Settings.ROOT_PATH, 'Resources', "%s.jpg") Settings.DB_DIR = Core.storage.join_path(Settings.ROOT_PATH, 'Database') Settings.POST_DB = PostDatabase() Settings.FILTER_DB = FilterDatabase() if Settings.UPDATE_ON_BOOT: Update.start_update() return True
def scrape_update(url): print print ("Scraping {0}").format(url.strip()) page = urllib2.urlopen(url) soup = BeautifulSoup(page) scraped_update_url = url project_title = str(soup.find("div", { "class" : "container"})) project_title_strip = ['\n', "<div class=\"container\"><h1>", "</h1></div>"] project_title = text_stripper(project_title, project_title_strip) if project_title == "Project not found": out_url = url.strip() + "\n" print url.strip() + " is an invalid url or the project has been removed from the domain." insert_count = 0 update_file("page_not_found.txt", out_url) else: project_title = str(soup.find("div", { "class" : "container"})) project_title_strip = ['\n', "<div class=\"container\"><h1>", "</h1></div>"] project_title = text_stripper(project_title, project_title_strip) project_title = regex_strip(project_title, r"(.*?)<.*") print "Project Title: " + project_title update_list = soup.findAll("div", { "class" : "update-box"}) insert_count = 0 for update in update_list: strip = ["\n"] strip_update = text_stripper(str(update), strip) strip = r".*?>.*?>(.*?)<.*" update_title = regex_strip(strip_update, strip) strip = r".*?>.*?>.*?>(.*?)<.*" update_date = regex_strip(strip_update, strip) update_strip = ["\n", "on"] update_date = text_stripper(update_date, update_strip) strip = r".*?>.*?>.*?>.*?>.*?>(.*)" update_text = regex_strip(strip_update, strip) update_text_strip = ['\n', "<br />", "<p>", "</p>", "</div>"] update_text = text_stripper(update_text, update_text_strip) out_update = Update(scraped_update_url, project_title, update_title, update_date, update_text) check = out_update.is_in_database() if check == False: print "Inserting {0} into database.".format(out_update.update_title) out_update.insert_into_database() insert_count += 1 else: print "'{0}' update already in database.".format(out_update.update_title) return insert_count
def end_turn(swap_turn): global game_state global player1 global player2 any_token = False if Update.end_game(player1, player2) is True: game_state = 1 if game_state != 1: if game_state == 2: for each in player2: if each[1].action_taken > 0: any_token = True if game_state == 3: for each in player1: if each[1].action_taken > 0: any_token = True # Check swap state and change game state if true if swap_turn is True and any_token is True: if game_state == 2: game_state = 3 elif game_state == 3: game_state = 2 # Set reset value reset = True # Loop though player 1 token for each in player1: # Check if token has action left if each[1].action_taken > 0: # Update reset reset = False # Loop though player 2 token for each in player2: # Check if token has action left if each[1].action_taken > 0: # Update reset reset = False # If all token have used all there moves reset the phase if reset is True: # Loop though token in player 1 for each in player1: # Reset action value and unlock token each[1].action_taken = each[1].action_value each[1].locked = False # Loop though token in player 2 for each in player2: # Reset action value and unlock token each[1].action_taken = each[1].action_value each[1].locked = False
def scnnMnist(): model = SCNN(n_components, 10, hiddenSize=1, hiddenAct=Activation.Selu(), iweight=Initialize.lecun_normal, outputAct=Activation.Softmax(), update=Update.Rprop(), error=Error.JsDivergence(), regularization=Regularize.Ridge()) testMnist(model)
def LoadFromFile(self, filename): """ Loads an old run from a file Parameters ---------- filename : string Name of the file that everything will be saved to Returns ------- None """ data = np.load(filename, allow_pickle=True).item() from FEM import FEM self.fem = FEM() self.fem.Load(data['fem']) if data['update']['type'] == 'OC': self.update = Update.OCUpdateScheme(0.2, 0.5, 0.5 * np.ones(self.fem.nElem), np.zeros(self.fem.nElem), np.ones(self.fem.nElem)) elif data['update']['type'] == 'MMA': self.update = Update.MMA(0.5 * np.ones(self.fem.nElem), 1, np.zeros(self.fem.nElem), np.ones(self.fem.nElem)) self.update.Load(data['update']) self.Filter = data['opt']['Filter'] try: self.R = data['opt']['R'] except: pass import Functions as Funcs for objective in data['opt']['objectives']: self.AddFunction(getattr(Funcs, objective['function']), objective['weight'], objective['min'], objective['max'], 'objective') for constraint in data['opt']['constraints']: self.AddFunction(getattr(Funcs, constraint['function']), constraint['constraint'], constraint['min'], constraint['max'], 'constraint')
def retranslateUi(self, ChangeAvatarWin): _translate = QtCore.QCoreApplication.translate ChangeAvatarWin.setWindowTitle( _translate( "ChangeAvatarWin", "Change Avatar / Iconit v" + str(self.ver) + " (" + str(Update.get_update_release_date()) + ")", )) self.WinTitle.setText(_translate("ChangeAvatarWin", "Change Avatar")) self.Change_btn.setText(_translate("ChangeAvatarWin", "Change Avatar")) self.Download_btn.setText( _translate("ChangeAvatarWin", "Download Avatar")) self.Prev_btn.setText(_translate("ChangeAvatarWin", "Previous")) self.Next_btn.setText(_translate("ChangeAvatarWin", "Next")) self.ResizeUpload_btn.setText( _translate("ChangeAvatarWin", "Resize && Upload")) self.AccountName.setText( _translate("ChangeAvatarWin", self.getAccountName())) self.AccountID_label.setText( _translate("ChangeAvatarWin", "AccountID:")) self.TotalAccount_label.setText( _translate("ChangeAvatarWin", "Total Accounts")) self.Revert_btn.setText( _translate("ChangeAvatarWin", "Revert to original")) self.label1.setText( _translate("ChangeAvatarWin", "This is the Original Avatar.")) self.label2.setText( _translate("ChangeAvatarWin", "Do you want to revert back to original avatar?")) self.firstName_label.setText( _translate("ChangeAvatarWin", "First name: ")) self.firstName.setPlaceholderText(_translate("ChangeAvatarWin", "")) self.lastName_label.setText( _translate("ChangeAvatarWin", "Last name: ")) self.lastName.setPlaceholderText(_translate("ChangeAvatarWin", "")) self.Rename_btn.setText(_translate("ChangeAvatarWin", "Rename account")) self.Title_label_2.setText( _translate( "ChangeAvatarWin", '<html><head/><body><p align="center"><a href="https://twitter.com/OfficialAhmed0"><span style=" font-family:\'verdana\'; font-size:14pt; text-decoration: underline; color:#90f542; vertical-align:super;">Created By @OfficialAhmed0</span></a></p></body></html>', )) self.SupportMe.setText( _translate( "ChangeAvatarWin", '<html><head/><body><p align="center"><a href="https://www.paypal.com/paypalme/Officialahmed0"><span style=" font-family:\'verdana\'; font-size:14pt; text-decoration: underline; color:#90f542; vertical-align:super;">Support me (PayPal)</span></a></p></body></html>', )) self.AccountID.setText(_translate("ChangeAvatarWin", self.user[0])) self.TotalAccounts.setText(_translate("ChangeAvatarWin", "1/4")) # Keyboard recognition v4.07 self.Next_btn.setShortcut("Right") self.Prev_btn.setShortcut("Left")
def OnUpdate(self, event): try: ret = Update.CheckNow() ''' if ret['version'] <= Version.string('python-hav-gclient', 3): Util.MessageBox(self, u'系统已经是最新,无需更新!', u'信息', wx.OK | wx.ICON_INFORMATION) return ''' if Util.MessageBox(self, '当前版本是: %s\n最新版本是: %s\n\n您确定要更新到最新版吗?' % (Version.string('python-hav-gclient', 3), ret['version']), u'确认', wx.YES_NO | wx.ICON_QUESTION) == wx.ID_NO: return Update.DownloadPackage(ret['filename'], ret['md5']) Update.InstallPackage(ret['filename'], ret['hav_gclient'],ret['spice_glib'],ret['spice_gtk'],ret['spice_gtk_tools'],ret['virt_viewer'],ret['add']) #Update.InstallPackage(ret['filename']) Util.MessageBox(self, '更新成功!\n新版程序会在下次系统启动时生效。', u'成功', wx.OK | wx.ICON_INFORMATION) except: Util.MessageBox(self, '检查更新失败!如果需要更新系统,请联系系统管理员。', u'错误', wx.OK | wx.ICON_ERROR | wx.BORDER_DOUBLE)
def setupUi(self, Message, MessageType): self.ver = Update.get_update_version() self.releaseDate = Update.get_update_release_date() self.copyright = "\nhttps://twitter.com/OfficialAhmed0\nThanks for using Iconit" self.Type = MessageType Message.setObjectName("Message") Message.resize(357, 208) Message.setMinimumSize(QtCore.QSize(357, 208)) Message.setMaximumSize(QtCore.QSize(357, 208)) Message.setStyleSheet('font: 75 12pt "Comic Sans MS";') Message.setWindowIcon( QtGui.QIcon(str(os.getcwd()) + "\Data\Pref\ic1.@OfficialAhmed0")) self.buttonBox = QtWidgets.QDialogButtonBox(Message) self.buttonBox.setGeometry(QtCore.QRect(-40, 160, 261, 51)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Close) self.buttonBox.setObjectName("buttonBox") self.Message = QtWidgets.QPlainTextEdit(Message) self.Message.setGeometry(QtCore.QRect(3, 10, 351, 151)) font = QtGui.QFont() font.setFamily("Comic Sans MS") font.setPointSize(12) font.setWeight(9) self.Message.setFont(font) self.Message.setFrameShape(QtWidgets.QFrame.Box) self.Message.setFrameShadow(QtWidgets.QFrame.Plain) self.Message.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.Message.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.Message.setReadOnly(True) self.Message.setCenterOnScroll(False) self.Message.setObjectName("Message") self.retranslateUi(Message) self.buttonBox.accepted.connect(Message.accept) self.buttonBox.rejected.connect(Message.reject) QtCore.QMetaObject.connectSlotsByName(Message)
def delegate(conn, user_in): user_in = user_in.lower() if user_in == "create": print("\n") return Create.Create(conn) elif user_in == "read": print("\n") return Read.Read(conn) elif user_in == "update": print("\n") return Update.Update(conn) elif user_in == "delete": print("\n") return Delete.Delete(conn) else: raise Exception("Invalid User input: " + user_in)
def OpenUpdatePageAndQuery(self, evt): initNum2 = self.Return_TotalStore() if (self.GoodsIDSelected() != None): dlg = Update.UpdatePage(self.GoodsIDSelected()) dlg.ShowModal() rows = [] index = long(self.SearchList_Report.GetFirstSelected()) try: GoodsInfo = str(getattr( self, "GoodsInfo_Text").GetValue()) ##获取非中文时, 用这句 except: GoodsInfo = repr((getattr( self, "GoodsInfo_Text").GetValue()).encode('gb2312')) #获取中文时,用这句 GoodsInfo = sub(r"\'", "", GoodsInfo) #由于用了repr,所以需要把字符串的两个单引号去掉, 所以去'' GoodsInfo = sub( r"\\", "", GoodsInfo) #由于带\的所有gb2312编码的字符串都无法进行查询,替换等工作, 所以去\ if (GoodsInfo == ""): rows = self.Return_AllData() else: rows = self.Return_QueryData() self.ListDisplay(rows) self.SearchList_Report.Select(index) ###返回到刚才的选中项 initNum2 = self.Return_TotalStore() - initNum2 self.statusbar.SetStatusText( u"商品总数: %d 款" % self.Return_TotalGoods(), 0) self.statusbar.SetStatusText( u"库存总数: %d 件" % self.Return_TotalStore(), 1) if (initNum2 > 0): self.statusbar.SetStatusText( u"修改了1款商品, 增加库存数: %d 件" % abs(initNum2), 2) else: self.statusbar.SetStatusText( u"修改了1款商品, 减少库存数: %d 件" % abs(initNum2), 2) dlg.Destroy() else: pass
def test(): # base data X = np.random.randn( 1000, 1 ) * 10 + 50 Y = X * 2 - 10 # add noise X += np.random.randn( 1000, 1 ) * 2 Y += np.random.randn( 1000, 1 ) * 2 # split trainX = X[ :900 ] trainY = Y[ :900 ] testX = X[ 900: ] testY = Y[ 900: ] # for prediction line plotX = np.array( [ min( X ), max( X ) ] ) iters = 2000 name = [ "RMSProp", "Momentum", "Nesterov", "SGD", "Rprop", "Adam" ] model = [ LLS( 1, 1, update=Update.RmsProp() ), LLS( 1, 1, update=Update.Momentum( 1e-7 ) ), LLS( 1, 1, update=Update.NesterovMomentum( 1e-7 ) ), LLS( 1, 1, update=Update.Sgd( 1e-7 ) ), LLS( 1, 1, update=Update.Rprop() ), LLS( 1, 1, update=Update.Adam() ) ] error = np.zeros( ( len( model ), iters ) ) for i in range( iters ): for m in range( len( model ) ): error[ m, i ] = model[ m ].partial_fit( trainX, trainY ) print( i + 1, "complete" ) # plot results plt.figure() plt.title( 'Data Space' ) plt.scatter( trainX, trainY, label='train' ) plt.scatter( testX, testY, label='test' ) plt.plot( plotX, model[ 4 ].predict( plotX ).x_, label='prediction' ) plt.legend() plt.figure() plt.title( 'Error Curves' ) for m in range( len( model ) ): plt.semilogy( error[ m ], label=name[ m ] ) plt.legend() plt.show()
def main(): update_init_print = Update_say("Welcome to Guess a Number!") update_init_nextstate = Update_set(field='current_state', value='choose') state_init = State([update_init_print, update_init_nextstate]) update_guessed_num = Update_get('guessed_num', int, "Guess a number: ") update_victory = Update_set( field='victory', value_expression=lambda _fields: _fields['number_to_guess'] == _fields[ 'guessed_num']) update_guess_branch = Update( branch_state_true='high', branch_state_false='low', branch_expression=lambda _fields: _fields['guessed_num'] > _fields[ 'number_to_guess']) state_choose = State( [update_guessed_num, update_victory, update_guess_branch]) update_high_say = Update_say("Too high!") update_high_nextstate = Update_set(field='current_state', value='choose') state_high = State([update_high_say, update_high_nextstate]) update_low_say = Update_say("Too low!") update_low_nextstate = Update_set(field='current_state', value='choose') state_low = State([update_low_say, update_low_nextstate]) game = Game( fields, { "init": state_init, "choose": state_choose, "low": state_low, "high": state_high }) while (not fields['victory']): game.step() print("You won!")
def __init__(self, inputSize, outputSize, hiddenSize=100, recurrent=False, hiddenAct=Activation.Relu(), outputAct=Activation.Identity(), iweight=Initialize.he, update=Update.Momentum(), error=Error.Mse(), regularization=Regularize.Zero()): # structure settings self.inputSize_ = inputSize + 1 self.outputSize_ = outputSize self.hiddenSize_ = hiddenSize self.valueInSize_ = self.inputSize_ + hiddenSize self.valueOutSize_ = hiddenSize + outputSize self.nParameters_ = self.valueInSize_ * self.valueOutSize_ self.hiddenActivationObj_ = hiddenAct self.hiddenActivation_ = self.hiddenActivationObj_.f self.outputActivationObj_ = outputAct self.outputActivation_ = self.outputActivationObj_.f self.recurrent_ = recurrent # training settings self.iweight_ = iweight self.errorObj_ = error self.errorFunc_ = error.f self.updateObj_ = update self.update_ = update.step self.regObj_ = regularization self.regLoss_ = self.regObj_.f # put in clean state self.initialize_()
def process_cmd_line(): """Parse the command line and execute given commands.""" # TRANSLATORS: This is the command line usage. Don't translate # %prog, but do translate usage, options, cleaner, and option. # More information about the command line is here # http://bleachbit.sourceforge.net/documentation/command-line usage = _("usage: %prog [options] cleaner.option1 cleaner.option2") parser = optparse.OptionParser(usage) parser.add_option("-l", "--list-cleaners", action="store_true", help=_("list cleaners")) parser.add_option("-c", "--clean", action="store_true", # TRANSLATORS: predefined cleaners are for applications, such as Firefox and Flash. # This is different than cleaning an arbitrary file, such as a # spreadsheet on the desktop. help=_("run cleaners to delete files and make other permanent changes")) parser.add_option("-s", "--shred", action="store_true", help=_("shred specific files or folders")) parser.add_option("--sysinfo", action="store_true", help=_("show system information")) parser.add_option("--gui", action="store_true", help=_("launch the graphical interface")) if 'nt' == os.name: uac_help = _("do not prompt for administrator privileges") else: uac_help = optparse.SUPPRESS_HELP parser.add_option("--no-uac", action="store_true", help=uac_help) parser.add_option("-p", "--preview", action="store_true", help=_("preview files to be deleted and other changes")) parser.add_option("--preset", action="store_true", help=_("use options set in the graphical interface")) if 'nt' == os.name: parser.add_option("--update-winapp2", action="store_true", help=_("update winapp2.ini, if a new version is available")) parser.add_option("-v", "--version", action="store_true", help=_("output version information and exit")) parser.add_option('-o', '--overwrite', action='store_true', help=_('overwrite files to hide contents')) (options, args) = parser.parse_args() did_something = False if options.version: print """ BleachBit version %s Copyright (C) 2014 Andrew Ziem. All rights reserved. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.""" % APP_VERSION sys.exit(0) if 'nt' == os.name and options.update_winapp2: import Update print "Checking online for updates to winapp2.ini" Update.check_updates(False, True, lambda x: sys.stdout.write("%s\n" % x), lambda: None) # updates can be combined with --list, --preview, --clean did_something = True if options.list_cleaners: list_cleaners() sys.exit(0) if options.preview or options.clean: operations = args_to_operations(args, options.preset) if not operations: print 'ERROR: No work to do. Specify options.' sys.exit(1) if options.preview: preview_or_clean(operations, False) sys.exit(0) if options.overwrite: if not options.clean or options.shred: print 'NOTE: --overwrite is intended only for use with --clean' Options.options.set('shred', True, commit=False) if options.clean: preview_or_clean(operations, True) sys.exit(0) if options.gui: import gtk import GUI shred_paths = args if options.shred else None GUI.GUI(uac=not options.no_uac, shred_paths=shred_paths) gtk.main() sys.exit(0) if options.shred: # delete arbitrary files without GUI # create a temporary cleaner object backends['_gui'] = create_simple_cleaner(args) operations = {'_gui': ['files']} preview_or_clean(operations, True) sys.exit(0) if options.sysinfo: import Diagnostic print Diagnostic.diagnostic_info() sys.exit(0) if not did_something: parser.print_help()
# Set a 'storing' counter for audio clips. storing_c = 0 # Wash, Rinse, Repeat. while True: print("Collecting tweets!") # Retrieves the messages container. tweets = Twitter.get_tweets() # Create the llm file LLM.build_llm(tweets) # Send a message to the display to retrieve the LLM file. Update.update_display(Settings.filename) # Play audio when a 'storing' is discovered. if storing_c < tweets.storingen: # Play the audio file. Audio.storing() # Set the counter to the 'storing' level. storing_c = tweets.storingen # Wait for a set amount of time. time.sleep(Settings.tweet_loop) # Stops the HTTP server that is serving llm files. httpd.stop()
def main(): filesInf = rf.readFile() # ... nCells = filesInf['ndiv'] nPoints = filesInf['ndiv'] + 1 length = filesInf['length'] preName = filesInf['output'] nStep = filesInf['nstep'] # ...................................................................... # ... gera o grid x, xc, cells, dx = gr.grid(length, nPoints, nCells) # ...................................................................... # ... timeWres = timeUpdate = 0.e0 # ... t = 0.0 dt = filesInf['dt'] k = np.full(nCells, filesInf['prop'][0], dtype=float) ro = np.full(nCells, filesInf['prop'][1], dtype=float) cp = np.full(nCells, filesInf['prop'][2], dtype=float) cc = np.array([filesInf['cce'], filesInf['ccd']]) sQ = np.zeros(nCells, dtype=float) nodeTemp = nPoints * [0.0] cellTemp = nCells * [0.0] cellTemp0 = nCells * [filesInf['initialt']] nodeTemp = np.zeros(nPoints, dtype=float) cellTemp0 = np.full(nCells, filesInf['initialt'], dtype=float) cellTemp = np.zeros(nCells, dtype=float) # ................................................................. # ... fileResCell = open(preName + '_cell.python', 'w') fileResNode = open(preName + '_node.python', 'w') # ................................................................. # ... gr.nodalInterpol(cells, cc, cellTemp0, nodeTemp, nCells, nPoints) # ................................1................................. # ... time0 = tm.time() gr.res(0, 0.0, xc, nCells, fileResCell) gr.res(0, 0.0, x, nPoints, fileResNode) timeWres += tm.time() - time0 # ................................................................. # ... temperatura inicial time0 = tm.time() gr.res(0, 0.0, cellTemp0, nCells, fileResCell) gr.res(0, 0.0, nodeTemp, nPoints, fileResNode) timeWres += tm.time() - time0 # ................................................................. # ... delta critico dtCrit = (min(ro) * min(cp) * dx**2) / (2.0 * min(k)) print("DeltaT Critico = {0}\n"\ "DeltaT = {1}".format(dtCrit, dt)) # ................................................................. # ... print("Running ...") for j in range(1, nStep + 1): # ... # print("Step : {0}\nTime(s) : {1}".format(j, t)) t += dt # ............................................................. # ... atualizada temp n time0 = tm.time() up.update(cellTemp, cellTemp0, sQ, k, ro, cp, dt , cc,\ dx, nCells) timeUpdate += tm.time() - time0 # ............................................................. # ... gr.nodalInterpol(cells, cc, cellTemp, nodeTemp, nCells, nPoints) # ............................................................. # ... temperatura inicial time0 = tm.time() gr.res(j, t, cellTemp, nCells, fileResCell) gr.res(j, t, nodeTemp, nPoints, fileResNode) timeWres += tm.time() - time0 # ............................................................. # ................................................................. # ... print("done.") # ................................................................. # ... print("Time Update(s) : {0:.4f}\n"\ "Time Wres(s) : {1:.4f}".format(timeUpdate, timeWres)) # ................................................................. # ... fileResCell.close() fileResNode.close()
os.chdir(dirname(abspath(__file__))) seed() from HTTPServer import LoadingServer preServer = LoadingServer() preServer.serve_bg() # We give stasis a single lock for all DiskMaps, but there will only be one DiskMap from rorn.Lock import getLock, setStackRecording from stasis.Lock import setMutexProvider setMutexProvider(lambda: getLock('#stasis')) from Options import option, parse as parseOptions parseOptions() Update.check() if option('lock-tracking'): setStackRecording(True) from stasis.Singleton import set as setDB from stasis.DiskMap import DiskMap from LoadValues import dbFilename def cacheLog(table): sys.__stdout__.write("[%s] [%s] %s\n" % (datetime.now().replace(microsecond = 0), 'stasis', "Backfilling table: %s" % table)) setDB(DiskMap(dbFilename, cache = True, nocache = ['log', 'sessions'], cacheNotifyFn = cacheLog)) from LoadValues import bricked from Log import console from Cron import Cron from HTTPServer import server as getServer, ServerError from Settings import PORT, settings