def inicio(path): datalist=[('Component',[0,'1st','2nd','3rd']),] met=fedit(datalist, title="Select Method") if met==[0]: name='/comp1.tif' if met==[1]: name='/comp2.tif' if met==[2]: name='/comp3.tif' image=np.array(Image.open(path+'/'+name)) clahe(image) datalist=[('Clip Limit',[0,'None','2','4','6','8','10','12']),] met=fedit(datalist, title="Select Clip Limit") if met==[1]: cl=2.0 if met==[2]: cl=4.0 if met==[3]: cl=6.0 if met==[4]: cl=8.0 if met==[5]: cl=10.0 if met==[6]: cl=12.0 image=cv2.createCLAHE(clipLimit=cl, tileGridSize=(4,4)).apply(image.astype(np.uint8)) plt.close() maps=[m for m in plt.cm.datad if not m.endswith("_r")] maps=[0]+maps maps.sort() print maps """colormap(image)
def delete_location(self): datalist = [('Location Name', '')] result = fedit(datalist, title="Delete location", comment="Leave empty to delete all locations") if result is None: return name = result[0] if self._srv_delete_location is None: self._srv_delete_location = rospy.ServiceProxy( 'location_service/delete_location', DeleteLocation) try: result = self._srv_delete_location(name) self.update_state(0) self._location_ok = True if result.success: rospy.loginfo(result.reason) else: rospy.logwarn("Deleting location %s failed: %s", name, result.reason) except rospy.ServiceException, e: rospy.logwarn("location service unavailable") self.update_state(1) self._location_ok = False
def save_current_location(self): location_alignments = ['N', 'W', 'S', 'E'] location_pickup_sides = ['left', 'front'] datalist = [('Location Name', ''), ('Location Align', [0] + location_alignments), ('Location Pickup Side', [0] + location_pickup_sides)] result = fedit(datalist, title="New location", comment="") if result is None: return name = result[0] alignment = location_alignments[result[1]] pickup_side = location_pickup_sides[result[2]] if self._srv_store_location is None: self._srv_store_location = rospy.ServiceProxy( 'location_service/store_location', StoreLocation) try: result = self._srv_store_location(name, alignment, pickup_side) self.update_state(0) self._location_ok = True if result.success: rospy.loginfo("Location %s stored", name) else: rospy.logwarn("Storing location %s failed: %s", name, result.reason) except rospy.ServiceException, e: rospy.logwarn("location service unavailable") self.update_state(1) self._location_ok = False
def setUpMenu(): Tk().withdraw() try: with open(CONFIGLOCATION,"r") as f: options = pickle.load(f) except (IOError, EOFError, pickle.PickleError): options = ConfigOptions() menuData = [ ('Color',[options.color,'Green','Blue']), ('Number of trials',options.numTrials), ('Number of licks for reward',options.licks), ('Reward Size (mL)',options.reward), ('Lick Time (ms)',options.lickTime), ('Stimulus Length (ms)',options.lightTime), ('Reward %',[str(options.catchRatio),'0.00','0.25','0.5','0.75','1.00']), ('Intertrial Interval Time',options.itiTime), ('Max Number of ITI', options.maxIti) ] newData = fedit(menuData,title="LED Stimulus Options") if newData is None: exit() path = asksaveasfilename(initialdir="\\".join(options.logLocation.split('\\')[:-1]),title="Save log as...",defaultextension = ".log",initialfile="\\LEDLick"+strftime("%Y-%m-%d_%H.%M.%S")+".log") if path is not '': newData.append(path) options = ConfigOptions(*newData) with open(CONFIGLOCATION,"w+") as f: pickle.dump(options,f) return options
def color_class(num,datalist,a): from formlayout import fedit col1,col2,col3,col4,col5,col6,col7=fedit(datalist,title="Assign colors") if a==1: num=zeros((7,3),int) col1 = col1.lstrip('#') num[0,0],num[0,1],num[0,2]=tuple(int(col1[i:i+2], 16) for i in range(0, 6, 2)) col2 = col2.lstrip('#') num[1,0],num[1,1],num[1,2]=tuple(int(col2[i:i+2], 16) for i in range(0, 6, 2)) col3 = col3.lstrip('#') num[2,0],num[2,1],num[2,2]=tuple(int(col3[i:i+2], 16) for i in range(0, 6, 2)) col4 = col4.lstrip('#') num[3,0],num[3,1],num[3,2]=tuple(int(col4[i:i+2], 16) for i in range(0, 6, 2)) col5 = col5.lstrip('#') num[4,0],num[4,1],num[4,2]=tuple(int(col5[i:i+2], 16) for i in range(0, 6, 2)) col6 = col6.lstrip('#') num[5,0],num[5,1],num[5,2]=tuple(int(col6[i:i+2], 16) for i in range(0, 6, 2)) col7 = col7.lstrip('#') num[6,0],num[6,1],num[6,2]=tuple(int(col7[i:i+2], 16) for i in range(0, 6, 2)) return num
def delete_location(self): datalist = [ ('Location Name', '') ] result = fedit(datalist, title="Delete location", comment="Leave empty to delete all locations") if result is None: return name = result[0] if self._srv_delete_location is None: self._srv_delete_location = rospy.ServiceProxy('location_service/delete_location', DeleteLocation) try: result = self._srv_delete_location(name) self.update_state(0) self._location_ok = True if result.success: rospy.loginfo(result.reason) else: rospy.logwarn("Deleting location %s failed: %s", name, result.reason) except rospy.ServiceException, e: rospy.logwarn("location service unavailable") self.update_state(1) self._location_ok = False
def save_current_location(self): location_alignments = ['N', 'W', 'S', 'E'] location_pickup_sides = ['left', 'front'] datalist = [ ('Location Name', ''), ('Location Align', [0] + location_alignments), ('Location Pickup Side', [0] + location_pickup_sides) ] result = fedit(datalist, title="New location", comment="") if result is None: return name = result[0] alignment = location_alignments[result[1]] pickup_side = location_pickup_sides[result[2]] if self._srv_store_location is None: self._srv_store_location = rospy.ServiceProxy('location_service/store_location', StoreLocation) try: result = self._srv_store_location(name, alignment, pickup_side) self.update_state(0) self._location_ok = True if result.success: rospy.loginfo("Location %s stored", name) else: rospy.logwarn("Storing location %s failed: %s", name, result.reason) except rospy.ServiceException, e: rospy.logwarn("location service unavailable") self.update_state(1) self._location_ok = False
def dBox(): ### maybe I could scrape to get a list of cities? location_list = [ 0, 'Minneapolis St Paul (MSP)', 'Seattle (Any)', 'IllAddMoreCitiesLater' ] datalist = [('Start', datetime.date(2010, 10, 10)), ('End', datetime.date(2020, 8, 10)), ('Home', location_list), ('Destination', location_list)] #### version without apply button or function response_dict = fedit(datalist, title="Date Range Selector", comment="Aye Homie, pick a date range.", cancel='Cancel', ok='Submit', result='dict', type='questions', scrollbar=True, background_color='#6c6', widget_color='#cf9') return response_dict
def scattererDetail(self): sel = self.ui.treeView_Scatterer.selectedIndexes() if(len(sel) != 0): row = sel[0].row() scatterer = self.simul.scatterers[row] datalist = [('X_min', scatterer.shape.min_x), ('Y_min', scatterer.shape.min_y), ('Z_min', scatterer.shape.min_z), ('X_max', scatterer.shape.max_x), ('Y_max', scatterer.shape.max_y), ('Z_max', scatterer.shape.max_z), ('Epsilon', scatterer.medium.eps), ('Mu', scatterer.medium.mu), ('Sigma', scatterer.medium.sig) ] data = fedit(datalist, title="Scatterer Detail", comment="Set the parameters about the Scatterer:") if data != None: scatterer.shape = Brick(vector_3(data[0], data[1], data[2]), vector_3(data[3], data[4], data[5])) scatterer.medium = Medium(data[6], data[7], data[8]) self.scatterer_model.setItem(row, 1, QtGui.QStandardItem("%.2f, %.2f, %.2f" % (data[0], data[1], data[2]))) self.scatterer_model.setItem(row, 2, QtGui.QStandardItem("%.2f, %.2f, %.2f" % (data[3], data[4], data[5]))) self.scatterer_model.setItem(row, 3, QtGui.QStandardItem(str(data[6]))) self.scatterer_model.setItem(row, 4, QtGui.QStandardItem(str(data[7]))) self.scatterer_model.setItem(row, 5, QtGui.QStandardItem(str(data[8])))
def load_samples(scenarioDatabase): try: if scenarioDatabase.currentTime is None: defaultTime = 1 else: defaultTime = scenarioDatabase.currentTime + 1 while True: nodeKeys = scenarioDatabase.nodeNameToID.keys() datalist = [('Location', ''), ('Time', defaultTime), ('Anomaly Detected', [0, 'No', 'Yes'])] myComment = 'Please enter the sample information and press ' + \ '"Cancel" when complete' feedback = fedit(datalist, title='Enter sample', comment=myComment) if feedback is None: break # nodeName = nodeIdToName[feedback[0].__str__()] nodeName = feedback[0].lower() if not scenarioDatabase.nodeNameToID.has_key(nodeName) and \ not scenarioDatabase.nodeIdToName.has_key(nodeName): print ' *** Location "%s" does not exist!' % nodeName continue nde = nodeName time = feedback[1] if feedback[2] == 'No': detect = False else: detect = True ct = len(scenarioDatabase.sampleResults.keys()) scenarioDatabase.add_result(nde, time, detect, ct) if scenarioDatabase.verbosity > 0: print scenarioDatabase.sampleResults scenarioDatabase.get_remaining_scenarios() except (KeyboardInterrupt, EOFError): print '\n Done reading data from user.' return
def show_mbal_dialog(): mbal_params = [(pvt_datalist(), "PVT", "Insert PVT Data: "), (drive_mechanisms_datalist(), "Drive Mechanisms", "")] dialog_result = fedit(mbal_params, "Material Balance", "") result = {} result['Boi'] = dialog_result[0][0] result['Bgi'] = dialog_result[0][1] result['Bo'] = dialog_result[0][2] result['Bg'] = dialog_result[0][3] result['Bw'] = dialog_result[0][4] result['Bwinj'] = dialog_result[0][5] result['Bginj'] = dialog_result[0][6] result['Rsi'] = dialog_result[0][7] result['Rsb'] = dialog_result[0][8] result['Pi'] = dialog_result[0][9] result['Pavg'] = dialog_result[0][10] result['GasCap'] = dialog_result[1][0] result['m'] = dialog_result[1][1] result['WaterInflux'] = dialog_result[1][2] result['We'] = dialog_result[1][3] result['PoreVolumereductionandConnateWaterexpansion'] = dialog_result[1][4] result['cw'] = dialog_result[1][5] result['cf'] = dialog_result[1][6] result['Swi'] = dialog_result[1][7] return result
def set_ruler(self): p = self.pane() datalist = [('Ruler start at', p._ruler_startpos), ('ATG start at', p._ruler_atgframe)] result = formlayout.fedit(datalist, title='Ruler setting') p._ruler_startpos = result[0] p._ruler_atgframe = result[1] p.update()
def setWall(self): datalist = [('Epsilon', self.simul.wall_medium.eps), ('Mu', self.simul.wall_medium.mu), ('Sigma', self.simul.wall_medium.sig), ('Thickness', self.simul.wall_thick), ] data = fedit(datalist, title="Configure the Wall", comment="Set the parameters about the wall:") if data != None: self.simul.setWall(data[3], Medium(data[0], data[1], data[2]))
def change_settings(self, title="Edit advanced settings" ): newSettings = fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else: self.settingsList[i] = (self.settingsList[i][0],newSetting) self.update_dict()
def example_2(arg): """A form that uses scrollbars.""" page1 = [("pressure" , 123.4) ,("velocity" , 36 ) ,("temperature" , 25.0 ) ,("serial Number" , "s/n acme xxx") ] page2 = [("Name" , "Paul") ,(None , None) ,(None , "Qt.jpg") ,(None , "Information:") ,("Age" , 30) ,("Sex" , [0, "Male", "Female"]) ,("Size" , 12.1) ,("Eyes" , "cyan") ,("Hair" , "#954535") ,("Married1" , True) ,("Married2" , True) ,("Married3" , True) ,("Married4" , True) ,("Married5" , True) ,("Married6" , True) ,("Married7" , True) ,("Married8" , True) ,("Married9" , True) ,("Married10" , True) ,("Married11" , True) ,("Married12" , True) ,("Married13" , True) ,("Married14" , True) ,("Married15" , True) ,("Married16" , True) ,("Married17" , True) ,("Married18" , True) ,("Married19" , True) ,("Married20" , True) ] result = formlayout.fedit( ((page1,"page1","<h1>title for page1</h1><hr>") ,(page2,"page2","title for page2") ) ,result = "dict" # ["list", "dict", "OrderedDict", "JSON", "XML"] ,type = "form" # ["form", "questions"] ,title = arg ,comment = "This is just an <b>example</b>." ,scrollbar = True ,background_color = "cyan" ,widget_color = "pink" ) return result
def setUpMenu(): Tk().withdraw() try: with open(CONFIGLOCATION, "r") as f: options = pickle.load(f) except (IOError, EOFError, pickle.PickleError): options = ConfigOptions() experimentOptions = [ ('Number of trials', options.numTrials), ('Lick Time (ms)', options.lickTime), ('ITI Time (ms)', options.itiTime), ('Max Number of ITI', options.maxIti), ] stimulusOptions = [ ('Left Stimulus Color', [options.leftColor, 'Green', 'Blue']), ('Right Stimulus Color', [options.rightColor, 'Green', 'Blue']), ('Stimulus Duration', options.stimulusTime), ('Stimulus Intensity', options.stimulusIntensity), ] rewardOptions = [ ('Number of licks for reward', options.licks), ('Reward Size (mL)', options.rewardSize), ('Reward %', [str(options.catchRatio), '0.00', '0.25', '0.5', '0.75', '1.00']) ] newData = fedit( ((experimentOptions, "Experiment", ""), (stimulusOptions, "Stimulus", ""), (rewardOptions, "Reward", "")), "Experiment Settings") if newData is None: exit() path = asksaveasfilename( initialdir="\\".join(options.logLocation.split('\\')[:-1]), title="Save log as...", defaultextension=".log", initialfile="\\LEDLick" + strftime("%Y-%m-%d_%H.%M.%S") + ".log") if path is not '': newData.append(path) options = ConfigOptions(*newData) with open(CONFIGLOCATION, "w+") as f: pickle.dump(options, f) return options
def setWall(self): datalist = [ ('Epsilon', self.simul.wall_medium.eps), ('Mu', self.simul.wall_medium.mu), ('Sigma', self.simul.wall_medium.sig), ('Thickness', self.simul.wall_thick), ] data = fedit(datalist, title="Configure the Wall", comment="Set the parameters about the wall:") if data != None: self.simul.setWall(data[3], Medium(data[0], data[1], data[2]))
def short_term_features(data, Fs, main_win): datalist = [("Window size", .05), ("Step size", .05), ("Result alias", "STF")] res = fedit( datalist, title="Short term features", comment="Returns a matrix that consists of 34 feature time series.") if res is not None: win_size, step_size, alias = res arr = Array(alias=alias, data=audioFeatureExtraction.stFeatureExtraction( data, Fs, win_size * Fs, step_size * Fs)) main_win._add_resource(arr) return arr
def multi(): """Scan for functions named 'examples_*' and offer them to the user.""" while True: #try: # # the messagebox is is not included in the standard formlayout # if not formlayout.messageBoxYesNo("so tell me","are you ready to rock?"): # break #except: # pass # build up a list of examples from this code units python namespace # formlayout wants the selected value as the first item examples = (1,*[ x for x in globals() if x.startswith("example_") ]) # create a form with two controls, # the name of the example to run # a greeting to pass as an argument to that example (displayed as a title) formdata = [("UsersChoice", examples) ,("greeting" , "salut!") ,(None , "<hr>") ,(None , "<center style='background-color:pink;'>CANCEL will exit the program!</small>") ] # get the users choices result = formlayout.fedit(formdata ,result = "dict" ,title = "a plethora of examples" ,comment = "<center style='margin:0 25px 0 25px;'>Select the example <b>you</b> want to run<br><i>although i suggest you use example 0</i></center>" ,scrollbar = True #,style = "QDialog{background:#bff; color:blue;} *{color:blue};" # not with background or widget color ,style = "QDialog{background:url(opal.jpg); color:blue;} *{color:blue};" # not with background or widget color ,icon = "opal.jpg" ) if result: # get the choice of example examplename = examples[result["UsersChoice"]] greeting = "{} ( {} )".format(examplename,result["greeting"]) print("**********************************") print(examplename) print("**********************************") # invoke the selected example function result_from_example = globals()[examplename](greeting) # all the examples return the form result, format it for display via PrettyPrinter print("the form data as rendered by pprint") pprint.PrettyPrinter(indent=2).pprint(result_from_example) else: break
def show_curve_coeffs_dialog(exp_params, wcut_params, wor_params, apply_callback): forecast_ui_params = [ (None, "Exponential and Hyperbolic Forecasts"), ("Decline Rate", exp_params), (None, "Water Cut Forecast"), ("Slope", wcut_params[0]), ("Intercept", wcut_params[1]), (None, "Water Oil Ratio Forecast"), ("Slope", wor_params[0]), ("Intercept", wor_params[1]), ] return fedit(forecast_ui_params, title="Decline Curve Coefficients", apply=apply_callback)
def example_4(arg): """Present Multiple pages, no scroll bars.""" # action buttons, other than apply, would be nice #def on_button_1(arg1,arg2): print(f"button_1 pressed({arg1},{arg2}") #def on_button_2(arg1,arg2): print(f"button_2 pressed({arg1},{arg2}") #def on_button_3(arg1,arg2): print(f"button_3 pressed({arg1},{arg2}") pageV = [("pressure" ,123.4) ,("velocity" ,36 ) ,("temperature" ,25.0 ) ,("serial Number" ,"s/n acme xxx") ] pageT = [("Name" ,"something") ,(None ,None) ] pageP = [("Name" ,"something") ,(None ,None) ] pageR = [("Name *::this is a tooltip" , "something") ,(None , None) #,("pumpit" , ("button",on_button_1)) #,("drain valve" , ("button",on_button_2)) #,("fill tank" , ("button",on_button_3)) ,("motion","slider:500:1000") ,("radios",(2,("a","12"),("b","22"),("c","34"),("d","36"))) ] result = formlayout.fedit( ((pageV,"Valve" ,"valve page") ,(pageT,"Tank" ,"tank page") ,(pageP,"Pump" ,"pump page") ,(pageR,"Run Controls" ,"Run controls") ) ,result = "dict" # ["list", "dict", "OrderedDict", "JSON", "XML"] ,type = "form" # ["form", "questions"] ,title = arg ,comment = "This is just an <b>example</b>." ) return result
def transform_array(resource, main_win): datalist = [("Alias for result", "{}_transformed".format(resource.alias)), ("Code to run", "_data + 1\n")] res = fedit(datalist, title="Transform array", comment="Applies arbitrary ipython statements to data. Use _data to access the data structure.") if res is not None: alias, code = res main_win.consoleDock.push_vars({"_data": resource.data}) main_win.consoleDock.execute_command(code + ";") data = main_win.consoleDock.pull_var("_data", delete=True) arr = Array(alias=alias, data=data) # copy sample rate if it applies if hasattr(resource, "sample_rate"): arr.sample_rate = resource.sample_rate main_win._add_resource(arr) return arr
def run_enterdata(self): datalist = [ ('Area:', str(self._test_measurements.area)), ('Min Area:', str(self._test_measurements.min_area)), ('Gauge:', str(self._test_measurements.gauge)), ] dataout = formlayout.fedit(datalist, parent=self) self._test_measurements.area = float(dataout[0]) self._test_measurements.min_area = float(dataout[1]) self._test_measurements.gauge = float(dataout[2]) print(self._test_measurements) results = '\n## Image Measures\n\n' + str(self._test_measurements) self.updateInfoPane(results)
def example_1(arg): """A simple example.""" formfields = [("Name" , "Paul") ,(None , None) ,(None , "Information:") ,("Age" , 30) ,("Sex" , [0, "Male", "Female"]) ,("Size" , 12.1) ,("Eyes" , "cyan") ,("Married" , True) ] result = formlayout.fedit(formfields ,result = "dict" # ["list", "dict", "OrderedDict", "JSON", "XML"] ,type = "form" # ["form", "questions"] ,title = arg ,comment = "This is just an <b>example</b>." ) return result
def showPreferences(): width = settings.value('width', 400).toInt()[0] height = settings.value('height', 200).toInt()[0] server = settings.value('server', False).toBool() panels = settings.value('panels', False).toBool() room = str(settings.value('room', '').toString()) map = str(settings.value('map', '').toString()) datalist = [('Width', width), ('Height', height), ('Disable socket server', server),('Show panels', panels),('Start room', room), ('Map file', map)] result = fedit(datalist, title="Preferences") if result is not None: settings.setValue('width', result[0]) settings.setValue('height', result[1]) settings.setValue('server', result[2]) settings.setValue('panels', result[3]) settings.setValue('room', result[4]) settings.setValue('map', result[5])
def on_actParams_triggered(self): data = [ ('Корректировка', self._instrumentController.result.adjust), ('Калибровка', self._instrumentController.cal_set), ('Только основные', self._plotWidget.only_main_states), ('Набор для коррекции', [1, '+25', '+85', '-60']), ] values = fedit(data=data, title='Параметры') if not values: return adjust, cal_set, only_main_states, adjust_set = values self._instrumentController.result.adjust = adjust self._instrumentController.result.adjust_set = adjust_set self._instrumentController.cal_set = cal_set self._instrumentController.only_main_states = only_main_states self._instrumentController.result.only_main_states = only_main_states self._plotWidget.only_main_states = only_main_states
def short_term_features(data, Fs, main_win): """ Short term features: 1 Zero Crossing Rate The rate of sign-changes of the signal during the duration of a particular frame. 2 Energy The sum of squares of the signal values, normalized by the respective frame length. 3 Entropy of Energy The entropy of sub-frames' normalized energies. It can be interpreted as a measure of abrupt changes. 4 Spectral Centroid The center of gravity of the spectrum. 5 Spectral Spread The second central moment of the spectrum. 6 Spectral Entropy Entropy of the normalized spectral energies for a set of sub-frames. 7 Spectral Flux The squared difference between the normalized magnitudes of the spectra of the two successive frames. 8 Spectral Rolloff The frequency below which 90% of the magnitude distribution of the spectrum is concentrated. 9-21 MFCCs Mel Frequency Cepstral Coefficients form a cepstral representation where the frequency bands are not linear but distributed according to the mel-scale. 22-33 Chroma Vector A 12-element representation of the spectral energy where the bins represent the 12 equal-tempered pitch classes of western-type music (semitone spacing). 34 Chroma Deviation The standard deviation of the 12 chroma coefficients. """ feat_labels = ["Zero Crossing Rate", "Energy", "Entropy of Energy", "Spectral Centroid", "Spectral Spread", "Spectral Entropy", "Spectral Flux", "Spectral Rolloff"] for i in range(13): feat_labels.append("MFCC_{}".format(i)) for i in range(2): feat_labels.append("ChromaVector_{}".format(i)) feat_labels.append("Chroma Deviation") datalist = [("Window size", .05), ("Step size", .05), ("Result alias", "STF")] res = fedit(datalist, title="Short term features", comment="Returns a matrix that consists of 34 feature time series.") if res is not None: win_size, step_size, alias = res data = audioFeatureExtraction.stFeatureExtraction(data, Fs, win_size * Fs, step_size * Fs) series = [] for row, label in zip(data, feat_labels): series.append(pd.Series(data=row, name=label)) print("{} series produced, of length {}".format(len(series), len(series[0]))) data = pd.concat(series, axis=1) arr = Array(alias=alias, data=data) main_win._add_resource(arr) return arr
def handleSlewToCoordButton(self): """ An input window will be presented where AzEl coordinates are required to be input. The SRT will then slew to these coordinates. """ # azel, ok = QtGui.QInputDialog.getText(self, 'Input', # 'Enter Az Alt:') # Use formlayout to make the form equatorialgroup = ( [('Right Ascension', ''), ('Declination', '')], "Equatorial", "Input equatorial coordinates." ) horizontalgroup = ( [('Azimuth',''), ('Altitude','')], "Horizontal", "Input Horizontal coordinates." ) galacticgroup = ( [('Longitude', ''), ('Latitude', '')], "Galactic", "Input galactic coordinates." ) result = fedit([equatorialgroup, horizontalgroup, galacticgroup]) print result if result: # Need to parse the output of the form skycoord = self._parseInput(result) if skycoord: #self.parent().srt.slew(self.parent().skymap,(azf,elf)) currentPos = self.parent().srt.getCurrentPos() targetPos = skycoord print targetPos state = self.parent().srt.drive.skycoord() if state != Status.SLEWING: if targetPos == currentPos: print("Already at that position.") #self.targetPos = currentPos self.parent().skymap.setTargetPos(currentPos) self.srt.setStatus(Status.READY) else: print("Slewing to " + str(targetPos)) self.parent().srt.setStatus(Status.SLEWING) self.parent().skymap.setTargetPos(targetPos) self.parent().srt.slew(targetPos) #self.parent().skymap.setCurrentPos(targetPos) #self.parent().updateStatusBar() else: print("Already Slewing. Please wait until finished.")
def get_options(options): datalist = [('Event database', 'events.dat'), ('Scenario library', 'scenarios.dat'), ('Node name library', 'nodes.dat'), ('Sample entry mode', [0, 'From File', 'Interactive']), ('Sample results', 'samples.dat'), ('Output possible scenarios', 'possible_scenarios.dat'), ('Output next sample locs', 'sample_next.dat'), ('Number of sample teams', 6)] feedback = fedit(datalist, title="Configure Scenario Match", comment="Please configure scenario match tool") options.timedat = feedback[0] options.slibfile = feedback[1] options.nlibfile = feedback[2] if feedback[3] == 'Interactive': options.interactive = True else: options.interactive = False options.resfileout = feedback[4] options.psfileout = feedback[5] options.pnfileout = feedback[6] options.nodes = feedback[7] return options
def scattererDetail(self): sel = self.ui.treeView_Scatterer.selectedIndexes() if (len(sel) != 0): row = sel[0].row() scatterer = self.simul.scatterers[row] datalist = [('X_min', scatterer.shape.min_x), ('Y_min', scatterer.shape.min_y), ('Z_min', scatterer.shape.min_z), ('X_max', scatterer.shape.max_x), ('Y_max', scatterer.shape.max_y), ('Z_max', scatterer.shape.max_z), ('Epsilon', scatterer.medium.eps), ('Mu', scatterer.medium.mu), ('Sigma', scatterer.medium.sig)] data = fedit(datalist, title="Scatterer Detail", comment="Set the parameters about the Scatterer:") if data != None: scatterer.shape = Brick(vector_3(data[0], data[1], data[2]), vector_3(data[3], data[4], data[5])) scatterer.medium = Medium(data[6], data[7], data[8]) self.scatterer_model.setItem( row, 1, QtGui.QStandardItem("%.2f, %.2f, %.2f" % (data[0], data[1], data[2]))) self.scatterer_model.setItem( row, 2, QtGui.QStandardItem("%.2f, %.2f, %.2f" % (data[3], data[4], data[5]))) self.scatterer_model.setItem(row, 3, QtGui.QStandardItem(str(data[6]))) self.scatterer_model.setItem(row, 4, QtGui.QStandardItem(str(data[7]))) self.scatterer_model.setItem(row, 5, QtGui.QStandardItem(str(data[8])))
def example_3(arg): """Groups and lists. example code from other places""" def create_datalist_example(): return [("str", "this is a string"), ("str", """this is a MULTILINE string"""), ("list", [0, "1", "3", "4"]), ("list2", ["--", ("none", "None"), ("--", "Dashed"),("-.", "DashDot"), ("-", "Solid"),("steps", "Steps"), (":", "Dotted")]), ("float", 1.2), (None, "Other:"), ("int", 12), ("font", ("Arial", 10, False, True)), ("color", "#123409"), ("bool", True), ("date", datetime.date(2010, 10, 10)), ("datetime", datetime.datetime(2010, 10, 10)),] def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, "Category 1", "Category 1 comment"), (datalist, "Category 2", "Category 2 comment"), (datalist, "Category 3", "Category 3 comment")) datalist = create_datalist_example() #--------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() result = formlayout.fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist ,"Title 2", "Tab 2 comment"), (datalist ,"Title 3", "Tab 3 comment")), title = arg) return result
# -*- coding: utf-8 -*- # # Copyright © 2009 Pierre Raybaut # Licensed under the terms of the MIT License # (see formlayout.py for details) """ Simple formlayout example Please take a look at formlayout.py for more examples (at the end of the script, after the 'if __name__ == "__main__":' line) """ from formlayout import fedit datalist = [ ('Name', 'Paul'), ('Age', 30), ('Sex', [0, 'Male', 'Female']), ('Size', 12.1), ('Eyes', 'green'), ('Married', True), ] print( "result:", fedit(datalist, title="Describe yourself", comment="This is just an <b>example</b>."))
if event == cv2.EVENT_MOUSEMOVE: if drawing==1: cv2.circle(img,(x,y),thickness,value['color'],-1) """cv2.circle(mask,(x,y),thickness,value['val'],-1)""" if event == cv2.EVENT_RBUTTONDOWN: cv2.circle(img,(x,y),thickness,value['color'],-1) classarry=np.load('nclass.npy') l=[] l.append(0) for a in classarry: l.append(a) datalist=[('Layer to edit',l),] met=fedit(datalist, title="Select Class to edit") numb_class=int(met[0]) BLACK = [255,255,255] # sure BG DRAW_BG = {'color' : BLACK, 'val' : 255} drawing=0 thickness = 10 # brush thickness if len(sys.argv) == 2: try: with open(sys.argv[1]+'/kmeans_edited.tif'): filename = sys.argv[1]+'/kmeans_edited.tif' except: filename = sys.argv[1]+'/kmeans.tif' img2=np.array(Image.open(filename))
def importCmud(fileName=None): if fileName is False or fileName is None: fileName = QtGui.QFileDialog.getOpenFileName( None, 'Open CMUD map for import...', Serializer.getHomeDir(), 'Map (*.dbm)') if not fileName or fileName is None or str(fileName[0]) is "": return fileName = str(fileName) import sqlite3 conn = sqlite3.connect(fileName) conn.text_factory = str cur = conn.cursor() cur.execute("PRAGMA encoding = \"UTF-8\";") cur.execute('SELECT * FROM ZoneTbl') rows = cur.fetchall() zoneMove = {} zones = [] for row in rows: zones.append((row[0], row[1])) zoneMove[row[0]] = (row[21], row[22]) zones.insert(0, zones[0][0]) datalist = [('Zone', zones)] from formlayout import fedit result = fedit(datalist, title="Zone to import") if result is None: return zoneid = zones[result[0] + 1][0] cur.execute('SELECT * FROM `ObjectTbl` where Z = 0 AND ZoneId = %d' % zoneid) rows = cur.fetchall() factory = Serializer.factory from PyQt4 import QtCore levels = Serializer.registry.levels() factor = 120 / Serializer.config.getSize() * 2 importedRooms = {} for row in rows: width = (row[9] - zoneMove[zoneid][0]) / factor height = (row[10] - zoneMove[zoneid][1]) / factor QPoint = QtCore.QPointF(width, height) room = factory.createAt(QPoint, levels[0].getView(), row[0]) importedRooms[row[0]] = room """def linkRooms(self, leftRoom, leftExit, rightRoom, rightExit, QGraphicsScene=None, leftLinkCustomLabel=None, rightLinkCustomLabel=None, leftLinkRebind=None, rightLinkRebind=None):""" cur.execute('SELECT * FROM `ExitTbl`') rows = cur.fetchall() directories = { 1: model.Direction.N, 2: model.Direction.NE, 3: model.Direction.E, 4: model.Direction.SE, 5: model.Direction.S, 6: model.Direction.SW, 7: model.Direction.W, 8: model.Direction.NW, 9: model.Direction.U, 10: model.Direction.D } alreadyLinked = [] for row in rows: if row[0] in alreadyLinked or row[1] in alreadyLinked: continue leftRoom = row[2] rightRoom = row[3] leftExit = row[19] + 1 rightExit = row[20] + 1 alreadyLinked.append(row[0]) alreadyLinked.append(row[1]) if leftExit not in range(1, 10) or rightExit not in range(1, 10): continue if leftRoom not in importedRooms or rightRoom not in importedRooms: continue leftRoom = importedRooms[leftRoom] rightRoom = importedRooms[rightRoom] leftExit = directories[leftExit] rightExit = directories[rightExit] try: leftRoom.addExit(leftExit) rightRoom.addExit(rightExit) factory.linkRooms(leftRoom, leftExit, rightRoom, rightExit, levels[0].getView()) except: pass
def second_function(result, widgets): print('second') print('result:', result) print('widgets:', widgets) for widget in widgets: if isinstance(widget, QLineEdit) and not widget.validator(): widget.setText(widget.text() + ' Second !') #--------- datalist example datalist = create_datalist_example() print("result:", fedit(datalist, title="Example", comment="This is just an <b>example</b>.", apply=('Custom &Apply button', apply_function), ok='Custom &OK button', cancel='Custom &Cancel button', result='dict', type='questions', scrollbar=True, background_color='#6c6', widget_color='#cf9')) #--------- datagroup example datagroup = create_datagroup_example() print("result:", fedit(datagroup, "Global title", result='JSON', background_color='#000000', widget_color='#ffff7f')) #--------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist, "Title 2", "Tab 2 comment"),
def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, "Category 1", "Category 1 comment"), (datalist, "Category 2", "Category 2 comment"), (datalist, "Category 3", "Category 3 comment")) # --------- datalist example datalist = create_datalist_example() def apply_test(data): print("data:", data) print("result:", fedit(datalist, title="Example", comment="This is just an <b>example</b>.", apply=apply_test)) # --------- datagroup example datagroup = create_datagroup_example() print("result:", fedit(datagroup, "Global title")) # --------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist, "Title 2", "Tab 2 comment"), (datalist, "Title 3", "Tab 3 comment")), "Global title"))
from math import * from cmath import * from scipy import linalg as nn import numpy as np import csv from scipy import signal as sg from csvtonum import * from formlayout import fedit ########################### datalist = [("Provide file name",""), ('Number of cycles',3), ('Save report',True), ('Current channel',1) ] filename=fedit(datalist,title="Pokuya",comment="Please provide") print "File name:" ########################### ##########Single phase tests ###########inputs part name=str(filename[0]) fe=float(50) #electrical frequecy. Eur=50Hz, American countries=60Hz Ncycle=filename[1] #number of cycles to be analyzed saverep=filename[2] channcurr=filename[3] ###########output ports reportname='{0}{1}'.format('reportof_',name) ######################## ##open the file with data
('steps', 'Steps'), (':', 'Dotted')]), ('float', 1.2), (None, 'Other:'), ('int', 12), ('color', '#123409'), ('bool', True), ] def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, "Category 1", "Category 1 comment"), (datalist, "Category 2", "Category 2 comment"), (datalist, "Category 3", "Category 3 comment")) #--------- datalist example datalist = create_datalist_example() print("result:", fedit(datalist, title="Example", comment="This is just an <b>example</b>.")) #--------- datagroup example datagroup = create_datagroup_example() print("result:", fedit(datagroup, "Global title")) #--------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist, "Title 2", "Tab 2 comment"), (datalist, "Title 3", "Tab 3 comment")), "Global title"))
# -*- coding: utf-8 -*- # # Copyright © 2009 Pierre Raybaut # Licensed under the terms of the MIT License # (see formlayout.py for details) """ Simple formlayout example Please take a look at formlayout.py for more examples (at the end of the script, after the 'if __name__ == "__main__":' line) """ from formlayout import fedit datalist = [ ("Name", "Paul"), ("Age", 30), ("Sex", [0, "Male", "Female"]), ("Size", 12.1), ("Eyes", "green"), ("Married", True), ] print("result:", fedit(datalist, title="Describe yourself", comment="This is just an <b>example</b>."))
widget.setText(widget.text() + ' First !') def second_function(result, widgets): print('second') print('result:', result) print('widgets:', widgets) for widget in widgets: if isinstance(widget, QLineEdit) and not widget.validator(): widget.setText(widget.text() + ' Second !') #--------- datalist example datalist = create_datalist_example() print("result:", fedit(datalist, title="Example", comment="This is just an <b>example</b>.", apply=('Custom &Apply button', apply_function), ok='Custom &OK button', cancel='Custom &Cancel button', result='dict', type='questions', scrollbar=True)) #--------- datagroup example datagroup = create_datagroup_example() print("result:", fedit(datagroup, "Global title", result='JSON')) #--------- datagroup inside a datagroup example datalist = create_datalist_example() datagroup = create_datagroup_example() print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), (datalist, "Title 2", "Tab 2 comment"), (datalist, "Title 3", "Tab 3 comment")), "Global title", result='XML'))
def example_0(arg): """Demonstrate as many formlayout variants as possible.""" page0 = [(None,"this page intentionally left blank")] page1 = [(None , "<center><i>This screen illustrates a variety of widgets<br>some appear the same and differ only in their return value</i></center>") # some info text ,(None , None) # a divider line ,(None ,"line2") #("line1","line2","line3")) ,("int1" , 12) ,("int2" , 3456789) ,("float1" , 1.2) ,("float2" , 22.1) ,("str1::this is a tooltip" , "this is a string with a tooltip") # note the ' *' is part of the field name.. that seems awkward ,("str2 *::the red star indicates a required item", "") ,("str3 *" , "this required item has no tooltip") ,("str4" , "just a string") # [ list : drop down list with item '2' selected ,("list1" , [3, "0", "1", "2", "3", "4"]) # [ list : drop down list with item '--' selected ,("list2" , ["--", ("none", "None"), ("--", "Dashed"),("-.", "DashDot"), ("-", "Solid"),("steps", "Steps"), (":", "Dotted")]) # ( tuple : vertical radio buttons with item '--' selected ,("list3" , ("--", ("none", "None"), ("--", "Dashed"),("-.", "DashDot"), ("-", "Solid"),("steps", "Steps"), (":", "Dotted"))) # ( tuple : vertical radio buttons with item 'Solid' selected ,("list4" , (4, "None", "Dashed", "DashDot", "Solid"," Steps", "Dotted") ) # [ list : drop down list with item 'Solid' selected ,("list5" , [4, "None", "Dashed", "DashDot", "Solid"," Steps", "Dotted"] ) ,(None , "linebreak1") ,("slider1" , "slider:500:1000") ,("slider2" , "slider:-100:100@-50") ,(None , "linebreak2") ,("font1" , ("Arial", 10, False, True)) ,("color1" , "red") ,("color2" , "green") ,("color4" , "#0000ff") ,("color3" , "#b00") # this format does not seem to be accepted # note extended syntax begin { ,("checkbox1" , ("0h" ,"cb1a","cb1b","cb1c","cb1d")) # horizontal default off ,("checkbox2" , ("1h" ,"cb2a","cb2b","cb2c","cb2d")) # horizontal default on ,("checkbox3" , ("0h1010","cb3a","cb3b","cb3c","cb3d")) # horizontal specified states ,("checkbox4" , ("1v0101","cb4a","cb4b","cb4c","cb4d")) # vertical specified states # note extended syntax end } ,("checkbox5" , False) ,("checkbox6" , True) ,("radio1" , ((2, ("radio1a","radio1alabel") ,("radio1b","radio1blabel") ,("radio1c","radio1clabel") ,("radio1d","radio1dlabel") ))) ,("password1" , "password") ,("time1" , datetime.time(12, 34, 56)) ,("date1" , datetime.date(2010, 12, 24)) ,("datetime1" , datetime.datetime(2010, 12, 24)) ,("calendar1" , "calendar") ,("calendar2" , "calendar:") ,("calendar3" , "calendarM") ,("calendar4" , "calendarM@2010,12,24") ,("file1" , "file") ,("file2" , "file:*.py") ,("dir1" , "dir") ,("str2" , """str2 this is a \nMULTILINE\nstring""") ,("image1" , "Qt.jpg") # will not render if there is a label ,(None , "Qt.jpg") # file must exist in local folder ] page2 = [("pressure" ,123.4) ,("velocity" ,36 ) ,("temperature" ,25.0 ) ,("Calibration certificate #", "s/n acme xxx") ] def on_apply_pressed(data,other): print("woohoo!!! you pressed apply and the data was: {}".format(data)) #print(f"other data was {other}")` result = formlayout.fedit(((page1, "page1tab", "page 1 Tabcomment" + " "*100) # 100 space padding required to expand tabbed form ,(page2 ,"page2tab", "page 2 Tabcomment") ) ,title = arg ,comment = "This is comment1." # gets lost on tabbed dialog ,icon = "Qt.jpg" ,parent = None ,apply = ("&APPLY",on_apply_pressed) ,ok = "&OKAY" ,cancel = "&NO-WAY" ,result = "dict" # ["list", "dict", "OrderedDict", "JSON", "XML"] ,outfile = None # "outfile" # will get .py ,.json ,.xml file extension ,type = "form" # ["form", "questions"] ,scrollbar = True ,background_color = None #,widget_color= None # djb additions ,size = (600,1000) ,position = (600,200) ) return result
def importCmud(fileName=None): if fileName is False or fileName is None: fileName = QtGui.QFileDialog.getOpenFileName( None, "Open CMUD map for import...", Serializer.getHomeDir(), "Map (*.dbm)" ) if not fileName or fileName is None or str(fileName[0]) is "": return fileName = str(fileName) import sqlite3 conn = sqlite3.connect(fileName) conn.text_factory = str cur = conn.cursor() cur.execute('PRAGMA encoding = "UTF-8";') cur.execute("SELECT * FROM ZoneTbl") rows = cur.fetchall() zoneMove = {} zones = [] for row in rows: zones.append((row[0], row[1])) zoneMove[row[0]] = (row[21], row[22]) zones.insert(0, zones[0][0]) datalist = [("Zone", zones)] from formlayout import fedit result = fedit(datalist, title="Zone to import") if result is None: return zoneid = zones[result[0] + 1][0] cur.execute("SELECT * FROM `ObjectTbl` where Z = 0 AND ZoneId = %d" % zoneid) rows = cur.fetchall() factory = Serializer.factory from PyQt4 import QtCore levels = Serializer.registry.levels() factor = 120 / Serializer.config.getSize() * 2 importedRooms = {} for row in rows: width = (row[9] - zoneMove[zoneid][0]) / factor height = (row[10] - zoneMove[zoneid][1]) / factor QPoint = QtCore.QPointF(width, height) room = factory.createAt(QPoint, levels[0].getView(), row[0]) importedRooms[row[0]] = room """def linkRooms(self, leftRoom, leftExit, rightRoom, rightExit, QGraphicsScene=None, leftLinkCustomLabel=None, rightLinkCustomLabel=None, leftLinkRebind=None, rightLinkRebind=None):""" cur.execute("SELECT * FROM `ExitTbl`") rows = cur.fetchall() directories = { 1: model.Direction.N, 2: model.Direction.NE, 3: model.Direction.E, 4: model.Direction.SE, 5: model.Direction.S, 6: model.Direction.SW, 7: model.Direction.W, 8: model.Direction.NW, 9: model.Direction.U, 10: model.Direction.D, } alreadyLinked = [] for row in rows: if row[0] in alreadyLinked or row[1] in alreadyLinked: continue leftRoom = row[2] rightRoom = row[3] leftExit = row[19] + 1 rightExit = row[20] + 1 alreadyLinked.append(row[0]) alreadyLinked.append(row[1]) if leftExit not in range(1, 10) or rightExit not in range(1, 10): continue if leftRoom not in importedRooms or rightRoom not in importedRooms: continue leftRoom = importedRooms[leftRoom] rightRoom = importedRooms[rightRoom] leftExit = directories[leftExit] rightExit = directories[rightExit] try: leftRoom.addExit(leftExit) rightRoom.addExit(rightExit) factory.linkRooms(leftRoom, leftExit, rightRoom, rightExit, levels[0].getView()) except: pass
def new_archive_file( args ): #start/end are for the different windows. Variables are not segregated along those lines, just the visuals. #start------------------------------ #get name of desired subdir, and make sure it is unique subdirs = [dr for dr in os.listdir(os.getcwd()) if os.path.isdir(dr)] archdir = try_command_line(args, "fondsname") print("XXX", archdir) dirname = formlayout.fedit( [("Archive directory", archdir)], title="CSDH 2014 : Daniel Simeone", comment="Choose a name for the directory (no spaces).")[0] while not is_dir_name_new(dirname, subdirs): dirname = formlayout.fedit( [("Archive directory", "")], title="CSDH 2014 : Daniel Simeone", comment= "ERROR. Directory already exists. Choose a new name for the directory (no spaces)." )[0] #end------------------------------ #start--------------------------- #the citation type goes with the corresponding set of citation fields citation_types = ["article", "book", "misc"] citation_desc = [ "For journal articles.", "For monographs.", "For other types of material." ] #ensure that citationkey is the in the first entry. For all the rest, the order is arbitrary citation_fields = [ ["citationkey", "author", "title", "journal", "number", "year"], ["citationkey", "author", "title", "year", "publisher", "address"], ["citationkey", "author", "title", "year", "pages", "howpublished"] ] chosentype = formlayout.fedit( [("Bibliographic type", ["article"] + citation_types)], title="CSDH 2014 : Daniel Simeone", comment="Choose type of bibliographic entry.")[0] #end--------------------- #start-------------------- chosentype_idx = -1 for i in range(len(citation_types)): if str(citation_types[i]) == str(chosentype): chosentype_idx = i datalist = use_command_line_args(args, citation_fields, chosentype_idx, dirname) field_data = formlayout.fedit(datalist, "CSDH 2014 : Daniel Simeone") bibfile = ("@" + citation_types[chosentype_idx] + "{" + field_data[0] + ",\n") for i in range(len(field_data) - 1): bibfile += citation_fields[chosentype_idx][ i + 1] + " = {" + field_data[i + 1] + "},\n" bibfile += "}\n" #now, create directory dirname and write citation.bib to dirname - we do it now to make sure that it the next screen crashes, we've saved user data - if no changes are made in next screen, then this write is the only write. If some are, then the file is re-written. os.makedirs(dirname) with open(dirname + "/citation.bib", "w") as text_file: text_file.write(bibfile) #end ------------------------- #start------------------------ bibfile_ed = formlayout.fedit( [("Bibtex Entry", bibfile)], "CSDH 2014 : Daniel Simeone", comment="This is the BibTeX entry that will be used. Edit it as need." )[0] if bibfile != bibfile_ed: with open(dirname + "/citation.bib", "w") as text_file: text_file.write(bibfile_ed) #end--------------------------- return dirname