def main(argv=None): """main can also be called in the python interpreter, by supplying the command line as the argument.""" if argv is None: argv = sys.argv[1:] def destroy(*args): # call back for terminating the main eventloop gtk.main_quit() Configuration.set_logfile("fpdb-log.txt") import Options (options, argv) = Options.fpdb_options() if options.usage == True: #Print usage examples and exit sys.exit(0) if options.sitename: options.sitename = Options.site_alias(options.sitename) if options.sitename == False: usage() config = Configuration.Config(file = "HUD_config.test.xml") db = Database.Database(config) sql = SQL.Sql(db_server = 'sqlite') main_window = gtk.Window() main_window.connect('destroy', destroy) replayer = GuiReplayer(config, sql, main_window, options=options, debug=True) main_window.add(replayer.get_vbox()) main_window.set_default_size(800,800) main_window.show() gtk.main()
def downloadFile(url): # compression header: #Accept-Encoding: gzip, deflate, sdch file_name = url.split('/')[-1] header={ #"Accept-Encoding": "gzip, deflate, sdch" "Accept-Encoding": "gzip" } lastupdate=0 updateinterval=0.5 def formatprogress(file_size_dl,file_size): if file_size is not None: return "\r%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) else: return "\r%10d" % file_size_dl rq=request.Request(url,None,header) with request.urlopen(rq) as req: meta = req.info() block_sz = 8192 filebuffer="" file_size=None if meta.get('Content-Encoding') == 'gzip': # gunzip - download all in one go print("Downloading: %s" % file_name) filebuffer=req.read() else: if meta.get("Content-Length") is not None: # if we known file length, have fancy progress indication file_size = int(meta.get("Content-Length")) print("Downloading: %s Bytes: %s" % (file_name, file_size)) else: print("Downloading: %s" % file_name) while True: buffer = req.read(block_sz) if not buffer: break filebuffer+=str(buffer) if time.time()-updateinterval > lastupdate: # console may slow us down so keep update intervals lastupdate=time.time() sys.stdout.write(formatprogress(len(filebuffer),file_size)) with open(Options.getPath(file_name), 'w') as file: if meta.get('Content-Encoding') == 'gzip': # gunzip #buf = StringIO( filebuffer ) buf = BytesIO( filebuffer ) f = gzip.GzipFile(fileobj=buf) filebuffer = f.read().decode("utf-8") file.write(filebuffer) sys.stdout.write(formatprogress(len(filebuffer),file_size)) print(" - Done!") last_modified = meta.get('last-modified') #time_struct = time.strptime(last_modified, '%a, %d %b %Y %H:%M:%S %Z') #timestamp=time.mktime(time_struct) Options.set("EDDB-lastmodified-"+file_name,last_modified)
def OnAbout(self, event): # Show a short dialog that includes the description of the program dlg = wx.MessageDialog( self, Options.GetAbout(), "About data-elaborator " + str(Options.GetVersion()), wx.OK) dlg.ShowModal() dlg.Destroy()
def __init__(self, edcePath, db, postMarketData, verificationCodeInputFn): self.verificationFn = verificationCodeInputFn self.db = db self.lock = threading.RLock() self.disabled = None sys.path.insert(0, edcePath) sys.path.insert(0, os.path.join(edcePath, "edce")) import edce.query import edce.error import edce.util import edce.eddn import edce.config import edce.globals edce.eddn.testSchema = False edce.query.minimumDelay = 0 print(Options.getPath()) import configparser edce.config.setConfigFile(Options.getPath("edce.ini")) edce.config.writeConfig(Options.get("elite-username", ""), Options.get("elite-password", ""), True, Options.getPath(), Options.getPath(), Options.getPath()) self.resultsUpdated = True self.resultsLastUpdated=0 self.activeThreads = [] self.result = None self.finishedListeners = [] self.postMarkedData = postMarketData self.lastUpdatedInfo = {"starportName" : "", "systemName" : "", "docked" : False}
def main(argv=None): """main can also be called in the python interpreter, by supplying the command line as the argument.""" if argv is None: argv = sys.argv[1:] def destroy(*args): # call back for terminating the main eventloop gtk.main_quit() Configuration.set_logfile("fpdb-log.txt") import Options (options, argv) = Options.fpdb_options() if options.usage == True: #Print usage examples and exit sys.exit(0) if options.sitename: options.sitename = Options.site_alias(options.sitename) if options.sitename == False: usage() config = Configuration.Config(file = "HUD_config.test.xml") db = Database.Database(config) sql = SQL.Sql(db_server = 'sqlite') main_window = gtk.Window() main_window.connect('destroy', destroy) replayer = GuiReplayer(config, sql, main_window, options=options, debug=True) main_window.add(replayer.get_vbox()) main_window.set_default_size(800,800) main_window.show() gtk.main()
def OnSetupFlags(self, event): """ This method creates a dialog in which flag can be selected and fixed in value, usefull to setup flags inside the data-analisys script """ SetupFlagsDlg = Dialogs.FlagsDialog( self, "Select Flag value", "All the analisys flags are listed above, set them value at your whishes", Options.GetFlagsNames(), ["True", "False"]) if SetupFlagsDlg.ShowModal() == wx.ID_OK: # Take the value from the selected flag flags = Options.GetFlagsNames() for i in range(0, len(flags)): value = SetupFlagsDlg.cmbs[i].GetValue() # Check that all the values are correctly setted if not (value in ["True", "False"]): err_dlg = wx.MessageDialog( self, "Error, all the flags must have a valid value", "Error", wx.ICON_ERROR) err_dlg.ShowModal() err_dlg.Destroy() return Options.SetFlagByName(flags[i], value) SetupFlagsDlg.Destroy()
def _restoreSearchStatus(self): self.currentSystemCombo.setCurrentText( Options.get(self._optName("current_system"), "Sol")) self.targetSystemCombo.setCurrentText( Options.get(self._optName("target_system"), "Lave")) self.maxDistanceSpinBox.setValue( int(Options.get(self._optName("maximum_distance"), "50"))) self.minProfitSpinBox.setValue( int(Options.get(self._optName("minimum_profit"), "1000"))) self.graphDepthSpin.setValue( int(Options.get(self._optName("search_max_depth"), "5"))) self.graphMinDepthSpin.setValue( int(Options.get(self._optName("search_min_depth"), "1"))) self.smugglingCheckBox.setChecked( Options.get(self._optName("blackmarket"), "0") == '1') self._refreshCurrentStationlist() # populate station lists self._refreshTargetStationlist() self.currentStationCombo.setCurrentText( Options.get(self._optName("current_station"), "Abraham Lincoln")) self.targetStationCombo.setCurrentText( Options.get(self._optName("target_station"), "Lave Station")) self.searchType = Options.get(self._optName("search_type"), "direct") if self.searchType.isdigit(): self.searchType = self.searchTypes[int( self.searchType)][0] # old version shim for si in range(len(self.searchTypes)): if self.searchTypes[si][0] == self.searchType: self.searchTypeCombo.setCurrentIndex(si) self._searchtypeChanged(si)
def OnMeanLambda(self, event): # If data is not filled show an error message if not self.Data: dialog = wx.MessageDialog( self, "Error, you nead to analyze some data before mean on lambda.", "Error", wx.ICON_ERROR) dialog.ShowModal() dialog.Destroy() return # Replot the last mean graphics wl0_mean = Options.ToFloatNumber(self.wl0_mean_txt.GetValue()) wl1_mean = Options.ToFloatNumber(self.wl1_mean_txt.GetValue()) w0 = Options.ToFloatNumber(self.w0_zoom_txt.GetValue()) w1 = Options.ToFloatNumber(self.w1_zoom_txt.GetValue()) self.axes_bottom.clear() self.Data.PlotMeanLambda(wl0_mean, wl1_mean, w0, w1, self.axes_bottom) # Draw model lines for mode in self.ModelModes: self.axes_bottom.axvline(mode, color="r", ls="dashed") # Set limits self.axes_bottom.set_xlim((w0, w1)) self.canvas_bottom.draw()
def OnAddFile(self, event): """ Add a data file inside the file list """ # Show a file reader message LoadFileDialog = wx.FileDialog(self, "Load", "", "", "all (*.*) |*.*", wx.FD_OPEN | wx.FD_MULTIPLE) if LoadFileDialog.ShowModal() == wx.ID_OK: filepaths = LoadFileDialog.GetPaths() # If the selected files are more than one for filepath in filepaths: # Add the choosen file in the file list self.DataFiles.append(filepath) index = len(self.DataFiles) - 1 # Now get the a shorter version of the name of the data file to be shown in the list first_dir = filepath.rfind(Options.GetFileBar()) second_dir = filepath.rfind(Options.GetFileBar(), 0, first_dir) show_path = "..." + filepath[second_dir:] # Add the text on the combo list self.FileList.InsertItems([show_path], index) LoadFileDialog.Destroy() event.Skip()
def onElitePathClicked(self): path = self._selectPathDialog("Select Elite path", self.ElitePathTxt.text()) if path is not None: self.ElitePathTxt.setText(path) OptionsParams.set("Elite-path", path) self.analyzer.setPath(self.ElitePathTxt.text())
def start(): global ce if editorRunning: ce = CapsuleEditor.ce CapsuleEditor.root.mainloop() else: Options.setOptions() ce = CapsuleEditor.CapsuleEditor(Tkinter.Toplevel())
def update(force=False): # return None or 'http://downloadurl' file_name = updateUrl.split('/')[-1] if Options.get("Merchant-version",'?')=='?': # can't check for version without local build (nonbinary linux, macos) return None if force or checkUpdated(updateUrl) or not os.path.exists( Options.getPath( file_name ) ): downloadFile(updateUrl) return checkVersionFile(updateUrl)
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" import Options Options.load_options() global options from Options import options self.change_db()
def onSoundsChanged(self): OptionsParams.set("sounds-startup", self.soundStartupTxt.text() ) OptionsParams.set("sounds-search",self.soundSearchTxt.text() ) OptionsParams.set("sounds-error",self.soundErrorTxt.text() ) OptionsParams.set("sounds-enabled", self.soundEnabledChk.isChecked() and "1" or "0" ) OptionsParams.set("sounds-volume", self.soundVolumeSlider.value() ) if self.mainwindow is not None: self.mainwindow.sounds.refreshSounds()
def OnPopupMenuSortCrescent(self, event): #Take Date n_rows = self.Table.GetNumberRows() col_datas = np.zeros(n_rows) for i in range(0, n_rows): tmp = self.Table.GetCellValue(i, self.CurrentCol) # The column is not full, we cant sort if not tmp: dlg = wx.MessageDialog( self, "Error, there are some empty cells in the given column", "Error", wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return # Check if the given data is a number tmp_number = Options.ToFloatNumber(tmp) try: float(tmp) except: return # Append Datas col_datas[i] = tmp_number # Save the permutation array during sorting permutation = col_datas.argsort() # Apply the current permutation to all arrays datas = [] for i in range(0, self.Table.GetNumberCols()): tmp_array = np.zeros(n_rows) for j in range(0, n_rows): tmp = self.Table.GetCellValue(j, i) # Empty values will be considered as 0 if not tmp: tmp = "0" # Check if the given data is a number tmp_number = Options.ToFloatNumber(tmp) try: float(tmp) except: return tmp_array[j] = tmp_number # Apply the permutation datas.append(tmp_array[permutation]) # Rewrite all the cell for i in range(0, self.Table.GetNumberCols()): for j in range(0, n_rows): self.Table.SetCellValue(j, i, str(datas[i][j]))
def onTestEdceConnectionClicked(self): path = OptionsParams.get("EDCE-path", "") try: self.edceConnectionStatusTxt.setText("Testing connection...") postMarketData = OptionsParams.get("EDCE-uploads-results", "1") != "0" self.edceWrapper = EdceWrapper.EdceWrapper(path, self.db, postMarketData, self._verificationCheck) self.edceWrapper.fetchNewInfo() except Exception as ex: self.edceConnectionStatusTxt.setText(str(ex))
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" # Re-read the options. import Options Options.load_options() global options from Options import options self.change_db()
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" self.state.bayes.store() import Options Options.load_options() global options from Options import options self.state = self.state_recreator()
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" # Re-read the options. self.classifier.store() import Options Options.load_options() global options from Options import options
def OnAnalyzeData(self, event): # Check if data is filled with something if self.Data: dialog = wx.MessageDialog( self, "Some data are already been analized, do you want to cancel them?", "Attention", wx.NO_DEFAULT | wx.YES_NO) if dialog.ShowModal() == wx.ID_NO: event.Skip() dialog.Destroy() return dialog.Destroy() # Now create the data t0 = float(self.t0_txt.GetValue()) T = float(self.T_txt.GetValue()) wl0 = float(self.probe_wl_start_txt.GetValue()) wl1 = float(self.probe_wl_end_txt.GetValue()) N_wl = float(self.probe_N_wl.GetValue()) ZP_len = int(self.zp_txt.GetValue()) KW_beta = Options.ToFloatNumber(self.kw_txt.GetValue()) # Create progress bar dialog pb_dlg = wx.ProgressDialog(title="Progress information", message="Data analisys initialized...", maximum=len(self.DataFiles), parent=self, style=wx.PD_CAN_ABORT) self.Data = DataAnalisys.Data(self.DataFiles, t0, t0 + T, wl0, wl1, N_wl, ZP_len, pb_dlg, KW_beta) # Now destroy the dialog pb_dlg.Destroy() # Check if the data are been correctly evaluated # Select the mean lambda window wl0_mean = float(self.wl0_mean_txt.GetValue()) wl1_mean = float(self.wl1_mean_txt.GetValue()) w0 = Options.ToFloatNumber(self.w0_zoom_txt.GetValue()) w1 = Options.ToFloatNumber(self.w1_zoom_txt.GetValue()) # Clear existing figures self.axes_top.clear() self.axes_bottom.clear() self.Data.PlotColorMap(self.axes_top, wl0_mean, wl1_mean, w0, w1) self.Data.PlotMeanLambda(wl0_mean, wl1_mean, w0, w1, self.axes_bottom) for mode in self.ModelModes: self.axes_bottom.axvline(mode, color="r", ls="dashed") self.axes_top.axvline(mode, color="k", ls="dashed") # Draw all self.canvas_top.draw() self.canvas_bottom.draw()
def update(db,force=False): print("Checking for EDDB database update") Options.set("EDDB-last-updated", int(datetime.datetime.now().timestamp())) anyUpdated=False for file in eddbUrls: if force or checkUpdated(file,eddbUrls[file]): anyUpdated=True downloadFile(eddbUrls[file]) if anyUpdated: importDownloaded(db)
def OnSetWRange(self, event): # Get the new w range try: w0 = float(self.w0_zoom_txt.GetValue()) w1 = float(self.w1_zoom_txt.GetValue()) N_w = int(self.Nw_txt.GetValue()) except: dlg = wx.MessageDialog( self, u"Error, you must specify correctly both the \u03C9 range (floating point numbers) and the \u03C9 sampling (integer).", "Error", wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return # Check that some data already exists if not self.Data: dlg = wx.MessageDialog( self, u"Error, before setting the \u03C9 range you must analyze some data.", "Error", wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return # Reanalize data print(w0, w1, N_w) self.Data.MeanAnalyzedData(w0, w1, N_w) # Now plot the new data # Clear existing figures self.axes_top.clear() self.axes_bottom.clear() # Select the mean lambda window wl0_mean = Options.ToFloatNumber(self.wl0_mean_txt.GetValue()) wl1_mean = Options.ToFloatNumber(self.wl1_mean_txt.GetValue()) # Set the correct w range (and lambda) l0 = Options.ToFloatNumber(self.probe_wl_start_txt.GetValue()) l1 = Options.ToFloatNumber(self.probe_wl_end_txt.GetValue()) self.axes_top.set_xlim(w0, w1) self.axes_top.set_ylim(l0, l1) self.axes_bottom.set_xlim(w0, w1) self.Data.PlotMeanLambda(wl0_mean, wl1_mean, w0, w1, self.axes_bottom) self.Data.PlotColorMap(self.axes_top, l0, l1, w0, w1) for mode in self.ModelModes: self.axes_bottom.axvline(mode, color="r", ls="dashed") self.axes_top.axvline(mode, color="k", ls="dashed") # Draw all self.canvas_top.draw() self.canvas_bottom.draw()
def _restoreSearchStatus(self): self.maxDistanceSpinBox.setValue(int(Options.get(self._optName("maximum_distance"), "200"))) self.importComboBox.setCurrentIndex(int(Options.get(self._optName("importexport"), "0"))) self.commodityCombobox.setCurrentIndex(int(Options.get(self._optName("commodity"), "0"))) systemName=Options.get(self._optName("current_system"), "Sol") systems = self.db.getSystemByName(systemName) if len(systems) == 0: return self.currentSystemCombo.setCurrentText(systemName) self.currentSystem = systems[0]
def update(force=False): # return None or 'http://downloadurl' file_name = updateUrl.split('/')[-1] if Options.get( "Merchant-version", '?' ) == '?': # can't check for version without local build (nonbinary linux, macos) return None if force or checkUpdated(updateUrl) or not os.path.exists( Options.getPath(file_name)): downloadFile(updateUrl) return checkVersionFile(updateUrl)
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" # Reload the options. self.state.bayes.store() import Options Options.load_options() global options from Options import options # Recreate the state. self.state = self.state_recreator()
def get_options(): parser = optparse.OptionParser() Options.addCommonOptions(parser) Options.addSEOptions(parser) # base output directory to use. # # This takes precedence over gem5's built-in outdir option parser.add_option("--directory", type="str", default="m5out") parser.set_defaults( # Default to writing to program.out in the current working directory # below, we cd to the simulation output directory output='./program.out', errout='./program.err', mem_size=64 * 1024 * 1024, caches = True ) (options, args) = parser.parse_args() # Always enable caches, DerivO3CPU will not work without it. if not options.directory: eprint("You must set --directory to the name of an output directory to create") sys.exit(1) #if os.path.exists(options.directory): # eprint("Output directory %s already exists -- refusing to overwrite" % (options.directory)) # sys.exit(1) # Some features are not supported by this script, but are added to parser by # Options.addSEOptions and Options.addCommonOptions # I check for these here to avoid confusion # If you are failing an assertion here, removing the assertion will not make the option work. assert(not options.smt) assert(options.num_cpus == 1) assert(not options.fastmem) assert(not options.standard_switch) assert(not options.repeat_switch) assert(not options.take_checkpoints) assert(not options.fast_forward) assert(not options.maxinsts) assert(not options.l2cache) if args: print "Error: script doesn't take any positional arguments" sys.exit(1) return options
def __init__(self, master, ): self.loop = False # Allows you to deactivate or not the popup after pressing the confirm button. self.login_file = "accounts.txt" self.folder = "file/" + self.login_file self.password_folder = "file/security" # Path to password file. self.file_password = "******" self.save_folder = "file/backup" # Destination file for saving identifiers. self.save_file_rename = "accounts_" + self.date_formatting(time.localtime()) + ".txt" # File name once saved. if not os.path.exists(self.save_folder): # If the backup folder does not exist, it is created. os.mkdir(self.save_folder) self.number_file = len(os.listdir(self.save_folder)) self.title_text = 'Accounts Storage - Page de connexion' # Popup settings. self.color_bg = '#353535' # Popup settings. self.color_fg = 'white' # Popup settings. self.size_bd = 5 # Popup settings. self.font = 'Courier' # Text settings. self.font_style = 'bold italic' # Text settings. self.size = "375x200" # Popup settings. self.window = master # Arguments to interact with the main window and the connection popup window. self.attempts = 0 # Set the number of connection attempts to zero. if not os.path.exists(self.password_folder): # If the security folder does not exist, it is created. os.mkdir(self.password_folder) if not os.path.exists(self.password_folder + '/' + self.file_password): # If the file password doesn't exist, open pop-up create password. self.creation_password = tk.Toplevel(master) # Create popup for create a password. self.creation_password.title(self.title_text) # Popup settings. self.creation_password.geometry(self.size) # Popup settings. self.creation_password.resizable(width=False, height=False) # Popup settings. self.creation_password.config(background=self.color_bg) # Popup settings. self.title_create = tk.Label(self.creation_password, text=" Créer mot de passe: ", font=(self.font, 20, self.font_style), bg=self.color_bg, fg=self.color_fg, justify=tk.CENTER) # Title Frame. self.title_create.pack(expand=tk.YES) self.entry_password = tk.Entry(self.creation_password, show='*', bg=self.color_bg, fg=self.color_fg, width=20, bd=self.size_bd, font=(self.font, 14, self.font_style)) # Apply inputs. self.entry_password.pack(pady=7) # Apply labels and inputs. self.button_confirm = tk.Button(self.creation_password, text='Confirmer', bg=self.color_bg, fg=self.color_fg, bd=self.size_bd, command=self.encrypt_password, font=(self.font, 20, self.font_style)) # Apply button. self.button_confirm.pack(expand=tk.YES) self.creation_password.bind('<Escape>', lambda e: self.window.destroy()) # Link the escape key to the popup displayed in order to exit the application if you close the popup. self.creation_password.bind('<Return>', lambda e: self.encrypt_password()) # When we press enter it validates the connection. self.creation_password.protocol("WM_DELETE_WINDOW", self.closing_app) # Make sure that you close the popup with the cross that quits the application. Options.window_centering(self.creation_password) # Centers the popup on the screen. else: # Else open pop-up connect. self.login_window = tk.Toplevel(master) # Create connexion popup. self.login_window.title(self.title_text) # Popup settings. self.login_window.geometry(self.size) # Popup settings. self.login_window.resizable(width=False, height=False) # Popup settings. self.login_window.config(background=self.color_bg) # Popup settings. self.title_connect = tk.Label(self.login_window, text=" Entrer mot de passe: ", font=(self.font, 20, self.font_style), bg=self.color_bg, fg=self.color_fg, justify=tk.CENTER).pack(expand=tk.YES) # Apply inputs. self.password_entry = tk.Entry(self.login_window, show='*', bg=self.color_bg, fg=self.color_fg, width=20, bd=self.size_bd, font=(self.font, 14, self.font_style)) # Apply inputs. self.password_entry.pack(pady=7) self.button_connect = tk.Button(self.login_window, text='Connexion', bg=self.color_bg, fg=self.color_fg, bd=self.size_bd, command=self.cleanup, font=(self.font, 18, self.font_style)).pack(expand=tk.YES) # Apply button. self.login_window.bind('<Escape>', lambda e: self.window.destroy()) # Link the escape key to the popup displayed in order to exit the application if you close the popup. self.login_window.bind('<Return>', lambda e: self.cleanup()) # When we press enter it validates the connection. self.login_window.protocol("WM_DELETE_WINDOW", self.closing_app) # Make sure that you close the popup with the cross that quits the application. Options.window_centering(self.login_window) # Centers the popup on the screen.
def make_short_iron_condor(options_chain, underlying_price, body_spread, wingspan): #we assume closest rather than closest above or closest below #TODO: need better on tie behavior! if (body_spread > 0.10): print "Warning, body spread is expecting a 0.0 to 1.0 percentage, received {0}!".format( body_spread) if len(options_chain.calls) == 0: print "no calls" raise Options.OptionNotAvailableException(options_chain) bear_call_lower = options_chain.call_near( (1.0 + body_spread) * underlying_price) try: bear_call_upper = options_chain.call_at(bear_call_lower.strike() + wingspan) except StopIteration: print "ran out of calls for bear call upper, needed {0}".format( bear_call_lower.strike() + wingspan) raise Options.OptionNotAvailableException(options_chain) #TODO: need better on_tie behavior! bull_put_upper = options_chain.put_near( (1.0 - body_spread) * underlying_price) try: bull_put_lower = options_chain.put_at(bull_put_upper.strike() - wingspan) except StopIteration: print "ran out of calls for bull put lower, needed {0}".format( bull_put_upper.strike() - wingspan) raise Options.OptionNotAvailableException(options_chain) if (bull_put_upper.bid < 0.001 or bull_put_lower.ask < 0.001 or bear_call_lower.bid < 0.001 or bear_call_upper.ask < 0.001): raise Options.NoTradesFound(options_chain) #errors.append(("No trades today.", (bull_put_upper.bid, bull-put_lower.ask, bear_call_lower.bid, bear_call_upper.ask, bull_put_upper.expiration_date()))) sic = ShortIronCondor(bear_call_lower, bear_call_upper, bull_put_upper, bull_put_lower, wingspan, body_spread) if (sic.holding_credit() >= wingspan or sic.holding_credit() < 0.0): raise ArbitrageException(sic) if (sic.bull_put_upper.bid - sic.bull_put_lower.ask >= wingspan): raise ArbitrageException(sic) if (sic.bear_call_lower.bid - sic.bear_call_upper.ask >= wingspan): raise ArbitrageException(sic) return sic
def save_file(self): # Copied the file with date of execution in other folder. if self.number_file >= 5: # If there are more than 5 files, we delete them to leave 2. while self.number_file > 2: file_list = os.listdir(self.save_folder) os.remove(r'' + self.save_folder + '/' + file_list[0]) self.number_file = len(os.listdir(self.save_folder)) if os.path.exists(self.save_folder + '/' + self.save_file_rename): Options.Write_log(" SAVE LEAVE !!! Il existe déja une sauvegarde du fichier identifiants à cette date.") else: shutil.copy(self.folder, self.save_folder) os.rename(r'' + self.save_folder + "/" + self.login_file, r'' + self.save_folder + "/" + self.save_file_rename) Options.Write_log(" SAVE OK !!! Sauvegarde du fichier identifiants.") tk.messagebox.showinfo('Sauvegarde', 'Fichier sauvegarder avec succès')
def checkVersionFile(url): file_name = url.split('/')[-1] versionjson=readJSON(Options.getPath(file_name)) if versionjson is not None: # ignore if version is same - or version unknown (nonbinary linux, macos) if versionjson['versionTxt']==Options.get("Merchant-version",'?') or Options.get("Merchant-version",'?')=='?': return None else: print('New version available! v'+versionjson['versionTxt']) return versionjson else: print('versionfile not valid JSON') return None
def reReadOptions(self): """Called by the config page when the user saves some new options, or restores the defaults.""" # Re-read the options. global state import Options Options.load_options() global options from Options import options # Recreate the state. state = self.state_recreator() self.classifier = state.bayes
def get_options(): parser = optparse.OptionParser() Options.addCommonOptions(parser) Options.addSEOptions(parser) # base output directory to use. # This takes precedence over gem5's built-in outdir option parser.add_option("--directory", type="str", default="m5out") # Set the configuration to run parser.add_option("--my-config", type="str", default="basic") # Set the branch predictor to use parser.add_option("--my-bpred", type="str", default="LocalBP") parser.set_defaults( # output='./program.out', # errout='./program.err', cpu_type='DerivO3CPU', mem_size=64 * 1024 * 1024, caches=True) (options, args) = parser.parse_args() if not options.directory: eprint( "You must set --directory to the name of an output directory to create" ) sys.exit(1) # Some features are not supported by this script, but are added to parser by # Options.addSEOptions and Options.addCommonOptions # I check for these here to avoid confusion # If you are failing an assertion here, removing the assertion will not make the option work. assert (not options.smt) assert (options.num_cpus == 1) # assert(not options.fastmem) assert (not options.standard_switch) assert (not options.repeat_switch) assert (not options.take_checkpoints) assert (not options.fast_forward) assert (not options.maxinsts) assert (not options.l2cache) if args: print("Error: script doesn't take any positional X XXX XXX arguments") sys.exit(1) return options
def _restoreSearchStatus(self): self.maxDistanceSpinBox.setValue( int(Options.get(self._optName("maximum_distance"), "200"))) self.importComboBox.setCurrentIndex( int(Options.get(self._optName("importexport"), "0"))) self.commodityCombobox.setCurrentIndex( int(Options.get(self._optName("commodity"), "0"))) systemName = Options.get(self._optName("current_system"), "Sol") systems = self.db.getSystemByName(systemName) if len(systems) == 0: return self.currentSystemCombo.setCurrentText(systemName) self.currentSystem = systems[0]
def __init__(self, screen_width, screen_height, title): super().__init__(screen_width, screen_height, title) file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) self.background = None self.button_list = None self.button_list = [] self.map_file = "map_1.csv" self.background_file = "map_1_background.csv" self.ai_mode = False # create our 3 options to select what map to load map1_button = Options.OptionButton((screen_width / 2) - 120, screen_height - 450, "Map 1") # map1 will be our default option map1_button.face_color = arcade.color.ALLOY_ORANGE map2_button = Options.OptionButton((screen_width / 2), screen_height - 450, "Map 2") map3_button = Options.OptionButton((screen_width / 2) + 120, screen_height - 450, "Map 3") # create our 2 option to select if user or AI will control player user_button = Options.OptionButton((screen_width / 2) - 60, screen_height - 550, "User") # user is the default option user_button.face_color = arcade.color.ALLOY_ORANGE ai_button = Options.OptionButton((screen_width / 2) + 60, screen_height - 550, "AI") self.button_list.append(map1_button) self.button_list.append(map2_button) self.button_list.append(map3_button) self.button_list.append(user_button) self.button_list.append(ai_button) # Set the background color arcade.set_background_color(arcade.color.DARK_SLATE_GRAY) self.background = arcade.load_texture("graphics/menuBackground.png") self.state = "menu" # Map stuff self.map = None self.map_background = None self.view_left = 0 self.view_bottom = 0
def checkVersionFile(url): file_name = url.split('/')[-1] versionjson = readJSON(Options.getPath(file_name)) if versionjson is not None: # ignore if version is same - or version unknown (nonbinary linux, macos) if versionjson['versionTxt'] == Options.get( "Merchant-version", '?') or Options.get( "Merchant-version", '?') == '?': return None else: print('New version available! v' + versionjson['versionTxt']) return versionjson else: print('versionfile not valid JSON') return None
def queryCommodities(db, x, y, z, maxDistance, minPadSize,jumprange ,importexport,commodityid): queryparams=dict() queryparams['x']=x queryparams['y']=y queryparams['z']=z queryparams['maxdistance']=maxDistance queryparams['landingPadSize']=minPadSize queryparams['jumprange']=jumprange queryparams['lastUpdated']=int(Options.get('Market-valid-days',7)) queryparams['importexport']=importexport queryparams['commodityId']=commodityid results=db.getCommoditiesInRange(queryparams) #sort by time/value relation like usual for result in results: result['exportPh']=result['hours']/(result['exportPrice']+0.1) # can't be 0 result['importPh']=result['importPrice']/result['hours'] if importexport==0: results.sort(key=operator.itemgetter('importPh'),reverse=True) else: results.sort(key=operator.itemgetter('exportPh')) return results[:5000] # only winners go home
def OnPlotWizardMenu(self, event): # Open the dialog to set the plotting options # THe function PlotWizard in dialog is already done (to be tested) title = self.plot_title xlab = self.plot_xlabel ylab = self.plot_ylabel col_names = [] for i in range(0, self.Table.GetNumberCols()): if self.ColumnProprieties[i][Options.GRAPH_RULE] == "Y": col_names.append(self.ColumnProprieties[i][Options.NAME]) dialog = Dialogs.PlotWizard(self, title, xlab, ylab, col_names, self.plot_styles, self.plot_colors, self.plot_linesize, self.plot_linestyle) # Setup the dialogs legend values dialog.cmb_legend.SetValue(str(self.plot_legend)) dialog.cmb_legend_loc.SetValue(self.plot_legend_position) if dialog.ShowModal() == wx.ID_OK: self.plot_title = dialog.title_text.GetValue() self.plot_xlabel = dialog.xlabel_text.GetValue() self.plot_ylabel = dialog.ylabel_text.GetValue() for i in range(0, len(col_names)): self.plot_colors[i] = dialog.Colors[i].GetValue() self.plot_styles[i] = dialog.Markers[i].GetValue() self.plot_linesize[i] = Options.ToIntNumber( dialog.LineSizes[i].GetValue()) self.plot_linestyle[i] = dialog.LineStyles[i].GetValue() self.plot_legend = bool(dialog.cmb_legend.GetValue()) self.plot_legend_position = dialog.cmb_legend_loc.GetValue()
def event(self, event): if event.type == PG.MOUSEBUTTONDOWN: if Menu.Menu.check_mouse(Menu.Menu(), 340, 40, 20, 20): if (G.Globals.FX_VOL - 1) >= 0: G.Globals.FX_VOL -= 1 elif Menu.Menu.check_mouse(Menu.Menu(), 430, 40, 20, 20): if (G.Globals.FX_VOL + 1) <= 10: G.Globals.FX_VOL += 1 elif Menu.Menu.check_mouse(Menu.Menu(), 340, 100, 20, 20): if (G.Globals.MUSIC_VOL - 1) >= 0: G.Globals.MUSIC_VOL -= 1 elif Menu.Menu.check_mouse(Menu.Menu(), 430, 100, 20, 20): if (G.Globals.MUSIC_VOL + 1) <= 10: G.Globals.MUSIC_VOL += 1 elif Menu.Menu.check_mouse(Menu.Menu(), G.Globals.WIDTH - (self.save_x + 20), G.Globals.HEIGHT, self.save_surf.get_width(), self.save_surf.get_height()): G.set_vol() G.Globals.STATE = Options.Options()
def FireEmblem(screen): inGame = True nbSave = 0 state = ["Title", "Scene1", 1] characters = [] while inGame: if state[0] == "Dialogue": state = DialogueScene.Dialogue(screen, state[1], state[2]) elif state[0] == "Battle": infosBattle = utils.loadBattle(state[1], nbSave) endBattle = Battle.battle(screen, infosBattle[0], infosBattle[1], infosBattle[2], infosBattle[3]) state = endBattle[0] characters = endBattle[1] if state[0] not in ["Quit", "Title"]: utils.save("auto", state[0], state[1], state[2], pygame.Surface((600, 600)), characters) elif state[0] == "Title": state = TitleScreen.TitleScreen(screen) elif state[0] == "Load": state = LoadMenu.loadMenu(screen) elif state[0] == "Save": state = SaveMenu.SaveMenu(screen, state[1], state[2], state[3], state[4], characters) elif state[0] == "Options": state = Options.Options(screen) elif state[0] == "Quit": inGame = False
def main(args): # Parse the command line options options, args = Options.parseCommandLine(args) if options.help_commands: printCommands() return 0 if not args: fail("Command missing. Use one of %s" % ", ".join(getCommands().keys())) command = args[0] commands = getCommands() if options.verbose: Log.quiet = False else: Log.debug = lambda msg: None if options.quiet: Log.quiet = True if not command in commands: fail("Bad command. Use one of %s" % ", ".join(getCommands().keys())) # Install a task monitor taskMon = Task.RateLimitedTaskMonitor(TracyTaskMonitor()) Task.setMonitor(taskMon) # Read the project file project = Project.Project(options = options, fileName = options.project) getCommands()[command][0](project, options, args[1:]) return 0
def get_prog_block_index(self, prog): duration = int(self.ui.duration.value()) prog_block_index, prog_index, offset = [], 0, 0 if len(prog) != 0: if self.ui.blocks.count() == 0: search_space = ["Block"] else: search_space = self.main.get_blocks().split(",") if self.last_prog_block == (prog, search_space): return self.last_prog_block_index self.last_prog_block = (prog, search_space) for x in search_space: parts = x.split() params = Options.parse_block_params(parts[1:]) dur = params['duration'] if 'duration' in params else duration for i in range(dur): prog_block_index.append((offset, parts[0], prog_index)) prog_offset = 0 for itk, tk in enumerate(prog[prog_index]): if itk != 0: offset += (tk[0] - prog_offset) * len(prog[prog_index][itk - 1][1]) prog_offset = tk[0] prog_index += 1 if prog_index >= len(prog): prog_index =0 self.last_prog_block_index = (0, offset, prog_block_index) return (1, offset, prog_block_index)
def readJSON(filename): try: with open(Options.getPath(filename), "r") as file: return json.loads(file.read()) except Exception as ex: print(ex) return None
def main(argv=None): if argv is None: argv = sys.argv[1:] (options, argv) = Options.fpdb_options() if options.usage == True: # Print usage examples and exit print _("USAGE:") sys.exit(0) if options.hhc == "PokerStarsToFpdb": print _("Need to define a converter") exit(0) Configuration.set_logfile("fpdb-log.txt") # These options should really come from the OptionsParser config = Configuration.Config() db = Database.Database(config) sql = SQL.Sql(db_server="sqlite") settings = {} settings.update(config.get_db_parameters()) settings.update(config.get_import_parameters()) settings.update(config.get_default_paths()) db.recreate_tables() runFake(db, config, options)
def main(args): # Parse the command line options options, args = Options.parseCommandLine(args) if options.verbose: Log.quiet = False if options.quiet: Log.quiet = True # If a project file was not given, present the possibilities if not options.project: projectFiles = getAvailableProjectFiles() try: projectFile = projectFiles[Console.chooseIndex("Choose a project file", [f[1] for f in projectFiles])][0] except TypeError: return else: projectFile = options.project # Read the project file project = Project.Project(options = options, fileName = projectFile) # Create the interactive analyzer analyzer = Analyzer.InteractiveAnalyzer(project, options) if options.execute: for command in options.execute: try: analyzer.execute(command) except Analyzer.ExecutionError: return 1 analyzer.run() return 0
def queryDirectTrades(db,queryparams): queryparams['minprofit']=1 queryparams['lastUpdated']=int(Options.get('Market-valid-days',7)) results=db.getTradeDirect(dict(queryparams)) if queryparams['blackmarket']: results+=db.getBlackmarketDirect(dict(queryparams)) return sorted(results,key=operator.itemgetter("profitPh"),reverse=True)
def readJSON(filename): try: with open(Options.getPath(filename), "r") as file: return json.loads(file.read()) except Exception as ex: print(ex) return None
def main(argv=None): """main can also be called in the python interpreter, by supplying the command line as the argument.""" if argv is None: argv = sys.argv[1:] def destroy(*args): # call back for terminating the main eventloop gtk.main_quit() Configuration.set_logfile("fpdb-log.txt") (options, argv) = Options.fpdb_options() if options.sitename: options.sitename = Options.site_alias(options.sitename) if options.usage == True: #Print usage examples and exit print _("USAGE:") sys.exit(0) Configuration.set_logfile("GuiBulkImport-log.txt") if options.config: config = Configuration.Config(options.config) else: config = Configuration.Config() settings = {} if os.name == 'nt': settings['os'] = 'windows' else: settings['os'] = 'linuxmac' settings.update(config.get_db_parameters()) settings.update(config.get_import_parameters()) settings.update(config.get_default_paths()) #Do something useful importer = Importer.Importer(False,settings, config, None) importer.addBulkImportImportFileOrDir(os.path.expanduser(options.filename)) importer.setCallHud(False) if options.archive: importer.setStarsArchive(True) importer.setFTPArchive(True) if options.testData: importer.setPrintTestData(True) (stored, dups, partial, errs, ttime) = importer.runImport() importer.clearFileList() print(_('Bulk import done: Stored: %d, Duplicates: %d, Partial: %d, Errors: %d, Time: %s seconds, Stored/second: %.0f')\ % (stored, dups, partial, errs, ttime, (stored+0.0) / ttime))
def play(self,sound): if sound not in self.sounds: print("[" + sound + "] is not a valid sound to play! call your local DJ and try again!") return if Options.get("sounds-enabled", "0")=="1": if self.sounds[sound] is not None: self.sounds[sound].play() else: print("[" + sound + "] is not loaded! check filename and format!")
def checkUpdated(url): with request.urlopen(url, timeout=30) as conn: meta=conn.info() last_modified = meta.get('last-modified') #time_struct = time.strptime(last_modified, '%a, %d %b %Y %H:%M:%S %Z') #timestamp=time.mktime(time_struct) if last_modified != Options.get("Merchant-versionfile-lastmodified",0): return True return False
def load_progression(self, prog_str): p = str(prog_str) parts = p.split(" ") if len(parts) == 0: return if len(parts) == 1 and p in Options.get_available_progressions(): x = Options.progression_to_string(getattr(Progressions, p)) return self.load_progression("%s %s" % (p, x)) self.ui.progressionname.setText(parts[0]) if len(parts) > 3: params = parts[2:-1] for x in params: r = x.split("*") if len(r) == 2: self.ui.progressionsequence.addItem("%d %s" % (int(r[0]), r[1])) if len(r) == 1 and x != "": self.ui.progressionsequence.addItem("0 %s" % r[0])
def setup(self): for x in ["From movement", 1, 2, 4, 8, 16, 32, 64, 128]: self.ui.resolution.addItem(str(x)) for x in ["From movement"] + diatonic.basic_keys: self.ui.key.addItem(x) for x in Options.get_available_blocks(): self.ui.blockcombo.addItem(x) self.connect(self.ui.buttonBox, QtCore.SIGNAL("accepted()"), lambda: self.save_block())
def mouseReleaseEvent(self, ev): if self.pressed == ev.scenePos(): x, y = self.get_box_coords(ev) if self.ui.instruments.count() == 0 or self.ui.progressions.count() == 0: return if x >= 0 and y >= 0: self.ui.instruments.setCurrentRow(y) instrument = self.ui.instruments.item(y) instr = str(instrument.text()).split() params = Options.parse_instrument_params(instr[1:]) play, stop = [], [] if 'must_not_play' in params: stop = [ int(z) for z in params['must_not_play'].split("-") ] if 'must_play' in params: play = [ int(z) for z in params['must_play'].split("-")] if x in play: play.remove(x) if x not in stop and not self.plays(params, x, True): stop.append(x) elif x in stop: stop.remove(x) if x not in play: play.append(x) else: if not self.plays(params, x, True): play.append(x) else: stop.append(x) stop = [ str(x) for x in stop ] play = [ str(x) for x in play ] if play != []: play.sort() params['must_play'] = "-".join(play) else: if params.has_key('must_play'): del params['must_play'] if stop != []: stop.sort() params['must_not_play'] = "-".join(stop) else: if params.has_key('must_not_play'): del params['must_not_play'] instrument.setText("%s { %s }" % (instr[0], " ".join([ "%s:%s" % (str(x), str(params[x])) for x in params ]) )) self.update() elif y >= 0: self.ui.instruments.setCurrentRow(y) self.update()
def defineBuildEnvironment(): """ create a custom build environment, define the basic compiler and linker flags, define locations in source and target tree, parse the commandline and pick up options """ EnsureSConsVersion(2,0) EnsurePythonVersion(2,6) Decider('MD5-timestamp') # detect changed files by timestamp, then do a MD5 buildVars = Variables([OPTCACHE, CUSTOPTFILE]) Options.defineCmdlineVariables(buildVars) env = LumieraEnvironment(buildSetup, buildVars) env.Replace( CPPPATH =["#src"] # used to find includes, "#" means always absolute to build-root , CPPDEFINES=['LUMIERA_VERSION='+VERSION ] # note: it's a list to append further defines , CCFLAGS='-Wall -Wextra -Wformat-security' , CXXFLAGS='-std=gnu++14 -Wno-enum-compare -Wno-noexcept-type' , CFLAGS='-std=gnu99' ) env.Append(LINKFLAGS='-Wl,--no-undefined') # require every dependency is given on link, in the right order env.Append(LINKFLAGS='-Wl,--as-needed') # by default only link against dependencies actually needed to resolve symbols handleVerboseMessages(env) handleNoBugSwitches(env) env.Append(CPPDEFINES = '_GNU_SOURCE') appendCppDefine(env,'DEBUG','DEBUG', 'NDEBUG') # appendCppDefine(env,'OPENGL','USE_OPENGL') appendVal(env,'ARCHFLAGS','CCFLAGS') # for both C and C++ appendVal(env,'OPTIMIZE', 'CCFLAGS', val=' -O3') appendVal(env,'DEBUG', 'CCFLAGS', val=' -ggdb') # setup search path for Lumiera plugins appendCppDefine(env,'PKGLIBDIR','LUMIERA_PLUGIN_PATH=\\"$PKGLIBDIR/:ORIGIN/modules\\"' ,'LUMIERA_PLUGIN_PATH=\\"ORIGIN/modules\\"') appendCppDefine(env,'PKGDATADIR','LUMIERA_CONFIG_PATH=\\"$PKGLIBDIR/:.\\"' ,'LUMIERA_CONFIG_PATH=\\"$DESTDIR/share/lumiera/:.\\"') Options.prepareOptionsHelp(buildVars,env) buildVars.Save(OPTCACHE, env) return env
def get_progressions(self): changed = 1 try: p = self.main.get_progressions().split(",") if self.last_progressions == p: changed = 0 self.last_progressions = p prog = [Options.parse_progression(x) for x in p] prog_text = [ x.split()[0] for x in p] return (changed, prog, prog_text) except: return (1, [], [])
def main(argv=None): if argv is None: argv = sys.argv[1:] (options, argv) = Options.fpdb_options() if options.usage == True: # or (len(argv) < 1): usage() print "WARNING:" print "This script will modify many files in the regression test suite" print "As a safety precaution, you need to edit the file manually to run it"