def _init(): global lang global package global currentFile global fileType currentFile = Editor.currentFile() fileType = currentFile[-2:] if not Editor.isValid() or currentFile == '': return lang = Project.targetLangCode() (path, pofilename) = os.path.split(Editor.currentFile()) (package, ext) = os.path.splitext(pofilename) currentFile = Editor.currentFile() if fileType == 'po': complilerPresent = cmd_exists('msgfmt') if complilerPresent: saveSameFolder() else: os.system('kdialog --sorry \ "The command <msgfmt> is not available.\nYou need to install the gettext package"') return # Alert for the wrong extension else: os.system('kdialog --sorry \ "This format is not supported"')
def convert(): if not Editor.isValid() or Editor.currentFile() == '': return xliffpathname = Editor.currentFile() (path, filename) = os.path.split(xliffpathname) if not filename.endswith('.xlf'): return store = factory.getobject(xliffpathname) odfpathname = store.getfilenames()[0] if odfpathname.startswith('NoName'): print 'translate-toolkit is too old' odfpathname = os.path.splitext(xliffpathname)[0] + '.odt' if not os.path.exists(odfpathname): return translatedodfpathname = os.path.splitext( odfpathname)[0] + '-' + Project.targetLangCode() + '.odt' print 'translatedodfpathname %s' % translatedodfpathname print 'odfpathname %s' % odfpathname xliffinput = XliffInput(xliffpathname, Editor.currentFileContents()) odf = open(odfpathname, 'rb') xliff2odf.convertxliff(xliffinput, translatedodfpathname, odf) ourpath = ([p for p in sys.path if os.path.exists(p + '/xliff2odf.py')] + [''])[0] os.system('python "' + ourpath + '/xliff2odf-standalone.py" "%s" "%s" &' % (translatedodfpathname, Editor.currentEntryId()))
def process_inputs(): """Manages the events and keyboard in the game, sending info to entities. """ # Managing events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for entity in Entity.collection: entity.process_event(event) Camera.process_event(event) Editor.process_event(event) # Managing keyboard and mouse. keys_pressed = pygame.key.get_pressed() for entity in Entity.collection: entity.process_inputs(keys_pressed) Camera.process_inputs(keys_pressed) Editor.process_inputs(keys_pressed)
def lookup(): if not Editor.isValid(): return word = Editor.currentEntryId().split('\n', 1)[-1] if not word: return os.system("kioclient exec 'http://translate.google.com.tr/#en/tr/%s'" % word)
class Tab(QWidget): def __init__(self, fileName, parent=None): self.fileName = fileName super(Tab, self).__init__(parent) self.setObjectName("tab2") self.textEdit = Editor(self) self.textEdit.setObjectName("textEdit2") horizontalLayout = QHBoxLayout(self) horizontalLayout.setMargin(0) horizontalLayout.setObjectName("horizontalLayout2") horizontalLayout.addWidget(self.textEdit) self.actionCloseTab = QAction(parent) # __init__ def getFileName(self): return self.fileName # getFileName() def openFile(self, arq): try: f = open(arq) self.textEdit.setText(f.read()) f.close() except: print 'unable to open script.'
class RFIDEUi(QMainWindow): def __init__(self): super(RFIDEUi, self).__init__() self.initMainUi() def initMainUi(self): self.tab_widget = QTabWidget() self.tab_widget.setTabsClosable(True) self.tab_widget.tabCloseRequested.connect(self.closeTab) self.resize(400, 400) #self.showMaximized() self.new_tab1 = Editor(self) self.tab_widget.addTab(self.new_tab1, 'test') self.toolbar = self.addToolBar('New') newAction = QAction('新增', self) newAction.triggered.connect(self.setValue) self.toolbar.addAction(newAction) self.setCentralWidget(self.tab_widget) def closeTab(self): i = self.tab_widget.currentIndex() self.tab_widget.removeTab(i) def setValue(self): self.new_tab1.get_value()
def lookup(): if not Editor.isValid(): return word = Editor.currentEntryId().split('\n', 1)[-1] if not word: return os.system("kioclient exec 'http://tureng.com/search/%s'" % word)
class EditorStringTests(unittest.TestCase): def setUp(self): self.e = Editor() def test_1_input(self): the_input = "abc male 23000" output = self.e.string_to_list(the_input) self.assertEqual(output, ["Abcm", "", "", "", "", ""]) def test_3_bad(self): the_input = "abc,male,23000" output = self.e.string_to_list(the_input) self.assertEqual(output, ["Abc", "M", "23000", "", "", ""]) def test_good_bad(self): the_input = "A123,male,23000" output = self.e.string_to_list(the_input) self.assertEqual(output, ["A123", "M", "23000", "", "", ""]) def test_good_bad_2(self): the_input = "T109,M,74,861,-,22" output = self.e.string_to_list(the_input) self.assertEqual(output, ["T109", "M", "74", "861", "-", "22"]) def test_good_bad_3(self): the_input = "A111, female, 1, 1, ob, 22" output = self.e.string_to_list(the_input) self.assertEqual(output, ["A111", "F", "01", "001", "Ob", "22"])
def getGame(): '''Getting user inputs, creating a subfolder for the desired video''' game = input('Enter Choice of Game\n1.Kabaddi\n2.Football\n3.Cricket\n') #@@ if game not in '123': #@@ input('Wrong Choice'); exit() vidName, extension = input('Enter Name of Video File: ').split('.') path = f'{os.getcwd()}/{vidName}' #Path of the working directory try: #Creating a folder for the given video shutil.rmtree(path) except: pass finally: os.mkdir(path); os.chdir(path) try: #Opening video file vid = cv2.VideoCapture(f'{path}.{extension}') #Video used for detecting the location of the scoreboard video = cv2.VideoCapture(f'{path}.{extension}') #Video used for actual extraction except: input('No such file'); exit() D.load(game) main(vid, video, game) E.combine(vidName, extension, timeStamps, path)
def convert(): if not Editor.isValid() or Editor.currentFile()=='': return xliffpathname=Editor.currentFile() (path, filename)=os.path.split(xliffpathname) if not filename.endswith('.xlf'): return store = factory.getobject(xliffpathname) odfpathname=store.getfilenames()[0] if odfpathname.startswith('NoName'): print 'translate-toolkit is too old' odfpathname=os.path.splitext(xliffpathname)[0]+'.odt' if not os.path.exists(odfpathname): return translatedodfpathname=os.path.splitext(odfpathname)[0]+'-'+Project.targetLangCode()+'.odt' print 'translatedodfpathname %s' % translatedodfpathname print 'odfpathname %s' % odfpathname xliffinput=XliffInput(xliffpathname,Editor.currentFileContents()) odf=open(odfpathname,'rb') xliff2odf.convertxliff(xliffinput, translatedodfpathname, odf) ourpath=([p for p in sys.path if os.path.exists(p+'/xliff2odf.py')]+[''])[0] os.system('python "'+ourpath+'/xliff2odf-standalone.py" "%s" "%s" &'%(translatedodfpathname, Editor.currentEntryId()))
def lookup(): if not Editor.isValid(): return word=Editor.selectionInTarget() if not word: word=Editor.selectionInSource() if not word: return os.system("kfmclient newTab 'http://multitran.ru/c/m.exe?l1=1&l2=2&s=%s'" % word)
def lookup(): if not Editor.isValid(): return word = Editor.selectionInTarget() if not word: word = Editor.selectionInSource() if not word: return os.system("kioclient exec 'http://tureng.com/search/%s'" % word)
def update(screen): """Updates the game state one step. """ for entity in Entity.collection: entity.update() Camera.update() Editor.update(screen.get_size())
def mouseDoubleClickEvent(self, event): #鼠标双击操作,弹出属性框编辑 if self.m_chooseShape != None: if self.m_chooseShape.isRect() == True: editor = Editor.RectEditor(self.m_chooseShape) editor.exec_() print 'Double click ', self.m_chooseShape.GetStateDescribe() elif self.m_chooseShape.isLine() == True: editor = Editor.LineEditor(self.m_chooseShape) editor.exec_() print 'Double click ', self.m_chooseShape.GetStateDescribe()
def merge(): if Lokalize.projectOverview(): files=Lokalize.projectOverview().selectedItems() elif Editor.isValid(): files=[Editor.currentFile()] forms = Kross.module("forms") if not files: return if files[0].endswith('.po'): mergeOne=mergeOneGettext if os.system('which msgmerge')!=0: forms.showMessageBox("Error", i18n("Gettext not found"), i18n("Install gettext package for this feature to work")) else: if not tt_present: print 'error' #forms = Kross.module("forms") #forms.showMessageBox("Error", i18n("Translate-tolkit not found"), i18n("Install translate-toolkit package for this feature to work")) mergeOne=mergeOneOdf okCount=0 progress=0 if len(files)>1: progress=forms.showProgressDialog(i18n("Updating from templates..."), "") progress.setRange(0,len(files)) #progress.setMaximum(len(files)) counter=0 for po in files: if progress: progress.addText(po) progress.setValue(counter) counter+=1 ok=mergeOne(po) okCount+=ok if ok: editor=Lokalize.editorForFile(po) if editor: editor.reloadFile() if progress: progress.deleteLater() if mergeOne==mergeOneGettext: if len(files)==1: pot=potForPo(files[0]) if okCount: potModifSeconds=os.path.getmtime(pot) potModifDelta=datetime.timedelta(seconds=time.time()-potModifSeconds) potModifStr=time.strftime('%X %x %Z', time.localtime(potModifSeconds)) forms.showMessageBox("Information", i18n("Merge has been completed"), i18n("Merge has been completed.\nTemplate modification time: %1 (%2 days ago).",[str(potModifStr),potModifDelta.days])) else: if not os.path.exists(pot): forms.showMessageBox("Error", i18n("Merge failed."), i18n("Could not find template file for the merge:\n%1",[pot]))
class Processor(object): def __init__(self): self.filer = FileHandler() self.validator = Validator() self.database = Database() self.editor = Editor() self.plotter = Plotter() def add_data(self, fileloc): self.database.empty_database() self.filer.set_filepath(fileloc) self.filer.load_file() self.filer.strip_tags() self.validator.set_raw_data(self.filer.export()) self.validator.parse_data() self.database.add_people(self.validator.export_good_data()) def process_bad(self): if self.validator.has_bad_data(): self.editor.set_raw(self.validator.export_bad_data()) self.editor.edit() self.database.add_people(self.editor.export_good_data()) def set_file_path(self, new_path): self.database.set_directory(new_path) def get_file_path(self): return self.database.get_directory() def serialize(self, option): self.database.serialize(option) def deserialize(self, option): self.database.empty_database() self.database.deserialize(option) def pie_bmi(self): dist = self.database.get_bmi_distribution() self.plotter.pie_bmi(dist["normal"], dist["overweight"], dist["obese"], dist["underweight"]) def pie_gender(self): dist = self.database.get_gender_distribution() self.plotter.pie_gender(dist["males"], dist["females"]) def scatter_sales(self): sales_list = self.database.get_sales_ordered() self.plotter.scatter_sales(sales_list) def bar_bmi_vs_gender(self): self.plotter.bar_bmi_vs_gender(self.database.get_male_bmi(),self.database.get_female_bmi() )
def main(filenames=[]): """ start the editor, with a new empty document or load all *filenames* as tabs returns the tab object """ Editor.register_stock_icons() editor = Editor.EditorWindow() tabs = map(editor.load_document, filenames) if len(filenames) == 0: editor.welcome() return tabs
def doCompile(): if not Editor.isValid() or Editor.currentFile=='': return lang=Project.targetLangCode() (path, pofilename)=os.path.split(Editor.currentFile()) (package, ext)=os.path.splitext(pofilename) if os.system('touch `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES' % lang)!=0: os.system('mkdir `kde4-config --localprefix`/share') os.system('mkdir `kde4-config --localprefix`/share/locale') os.system('mkdir `kde4-config --localprefix`/share/locale/%s' % lang) os.system('mkdir `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES' % lang) os.system('msgfmt -o `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES/%s.mo %s' % (lang, package, Editor.currentFile()))
def doCompile(): if not Editor.isValid() or Editor.currentFile == '': return lang = Project.targetLangCode() (path, pofilename) = os.path.split(Editor.currentFile()) (package, ext) = os.path.splitext(pofilename) if os.system('touch ~/.local/share/locale/%s/LC_MESSAGES' % lang) != 0: os.system('mkdir ~/.local/share') os.system('mkdir ~/.local/share/locale') os.system('mkdir ~/.local/share/locale/%s' % lang) os.system('mkdir ~/.local/share/locale/%s/LC_MESSAGES' % lang) os.system('msgfmt -o ~/.local/share/locale/%s/LC_MESSAGES/%s.mo %s' % (lang, package, Editor.currentFile()))
def srcFileOpenRequested(filename, line): try: Editor.setSrcFileOpenRequestAccepted(True) except: print 'your lokalize needs update ;)' if not editor.isValid() or editor.currentFile()=='': return import Kross forms = Kross.module("forms") print filename (path, pofilename)=os.path.split(Editor.currentFile()) (package, ext)=os.path.splitext(pofilename) (upperPath, module)=os.path.split(path) if module.startswith('extragear-'): module=module.replace('extragear-','../extragear/') elif module.startswith('playground-'): module=module.replace('playground-','../playground/') elif module=='kdebase': trySubmodules=['workspace','apps','runtime'] for s in trySubmodules: if os.path.exists(ourPath+'/../../../KDE/kdebase/'+s+'/'+package): module=module+'/'+s print module break if package.startswith('desktop_'): while 1: try: package=package[package.index('_')+1:] except: break KdeTrunkPath=os.path.normpath(ourPath+'/../../../') mapSrcSuggest = mapSrc.get(package, '---') srcFilePath = subprocess.check_output(["/bin/bash", "-c", "/bin/find " + os.getenv("HOME")+"/dev/src/calligra/ | grep " + filename + "$"]).split('\n')[0] #srcFilePath = os.getenv("HOME")+"/dev/src/calligra/kexi/" + filename if len(srcFilePath): #os.system('kdialog --msgbox "'+srcFilePath + '%d' % line + '"') subprocess.call(['/usr/bin/kate', '-u', srcFilePath, '--line', '%d' % line]) print 'kate -u '+srcFilePath+(' --line %d &' % line) else: print "couldn't find. searched in:", print tryList answer=forms.showMessageBox("QuestionYesNo", "Could not find source file", "Searched in:\n"+'\n'.join(tryList)+""" Also searched using 'locate' command. Would you like to initiate websearch (using lxr.kde.org)? """) if answer=='Yes': os.system("kfmclient openURL 'http://lxr.kde.org/search?filestring=%s&string='" % filename)
def draw(screen, background): """Draws to the screen the game state. """ screen.blit(background, (0, 0)) for entity in Entity.collection: entity.enqueue_shadow(screen) Ground.draw(screen) for entity in Entity.collection: entity.draw(screen) Editor.draw(screen) pygame.display.flip()
def mergeOneOdf(xliffpathname): xliffpathname = Editor.currentFile() (path, filename) = os.path.split(xliffpathname) if not filename.endswith('.xlf'): return xlifftemplatepathname = path + '/t_' + filename print xlifftemplatepathname store = factory.getobject(xliffpathname) odfpathname = store.getfilenames()[0] if odfpathname.startswith('NoName'): print 'translate-toolkit is too old' odfpathname = os.path.splitext(xliffpathname)[0] + '.odt' if not os.path.exists(odfpathname): return print 'odf2xliff via subprocess.call', unicode(odfpathname), unicode( xlifftemplatepathname) try: retcode = subprocess.call([ 'odf2xliff', unicode(odfpathname), unicode(xlifftemplatepathname) ]) print >> sys.stderr except OSError, e: print >> sys.stderr, "Execution failed:", e
def CreateInteriorWindowComponents(self): ''' Create "interior" window components. In this case it is just a simple multiline text control. ''' ## Make zoom buttons #sizer = wx.BoxSizer(wx.VERTICAL) #buttons = wx.BoxSizer(wx.HORIZONTAL) #bt = wx.Button(self,ID_VERIFY) #buttons.Add(bt,0) #self.Bind(wx.EVT_BUTTON, self.OnVerify, bt) #bt = wx.Button(self,ID_CHARACTERIZE) #buttons.Add(bt,0) #self.Bind(wx.EVT_BUTTON, self.OnCharacterize, bt) #sizer.Add(buttons, 0, wx.ALIGN_LEFT) # Top: input self.top = wx.Notebook(self, -1) # Editor there self.editor = Editor.selectEditor(self.top) if self.load: textfile = open(os.path.join(self.dirname, self.filename), 'r') self.editor.SetText(textfile.read()) if self.dirname != "": os.chdir(self.dirname) textfile.close() self.editor.SetOpened() self.top.AddPage(self.editor.control, "Protocol description") self.settings = Settingswindow.SettingsWindow(self.top, self) self.top.AddPage(self.settings, "Settings")
def setupUi( self ): self.loadUi('SegmentationStep.ui') placeHolderWidget = self.get('SegmentEditorPlaceHolderWidget') self.EditorWidget = Editor.EditorWidget(parent=placeHolderWidget) self.EditorWidget.setup() placeHolderWidget.hide() for i in range(2): newSegmentWidget = SegmentationWidget.SegmentationWidget(self, self.EditorWidget) self.get('SegmentPlaceHolderWidget').layout().addWidget(newSegmentWidget) newSegmentWidget.setMRMLScene(slicer.mrmlScene) newSegmentWidget.setSegmentValidCallBack(getattr(self, 'onSegment%iValid' %(i+1))) self.SegmentWidgets.append(newSegmentWidget) if i > 0: self.SegmentWidgets[i].collapse(True) self.SegmentWidgets[i].visible = False self.SegmentWidgets[i].MergeNodeSuffix = 'tumor' self.get('SegmentRemoveSegmentWidgetToolButton').connect('clicked()', self.removeSegmentWidget) self.get('SegmentAddSegmentWidgetToolButton').connect('clicked()', self.addSegmentWidget) saveIcon = self.style().standardIcon(qt.QStyle.SP_DialogSaveButton) self.get('MergeAllSavePushButton').setVisible(False) self.get('MergeAllSavePushButton').icon = saveIcon self.get('MergeAllSavePushButton').connect('clicked()', self.saveMergedImage) self.get('MergeAllGoToButton').connect('clicked()', self.openImageLabelCombineModule) self.get('MergeAllApplyButton').connect('clicked(bool)', self.runMergeAll) self.get('MergeAllOutputNodeComboBox').addAttribute('vtkMRMLScalarVolumeNode','LabelMap','1') self.get('MergeAllCollapsibleGroupBox').visible = False self.get('MergeAllCollapsibleGroupBox').setChecked(False)
def main(stdscr): (y, x) = stdscr.getmaxyx() ed = Editor.Editor(y - 1, x) if len(sys.argv) > 1: filename = sys.argv[1] ed.buffer.load_from_file(filename) else: filename = "" curses.curs_set(0) update(stdscr, ed) event = -2 while True: if ed.exit: break elif event == curses.KEY_RESIZE: (y, x) = stdscr.getmaxyx() ed.set_win(0, y - 1, x) update(stdscr, ed) else: try: ed.handle_key(event2key(event)) except KeyChainError, e: curses.flash() update(stdscr, ed) if not ed.exit: stdscr.addstr(y - 2, x - 15, "%d: %s" % (event, event2key(event))) stdscr.chgat(ed.cursor.y - ed.win.top, ed.cursor.x, 1, curses.A_STANDOUT) stdscr.refresh() event = stdscr.getch()
def CreateInteriorWindowComponents(self): ''' Create "interior" window components. In this case it is just a simple multiline text control. ''' ## Make zoom buttons #sizer = wx.BoxSizer(wx.VERTICAL) #buttons = wx.BoxSizer(wx.HORIZONTAL) #bt = wx.Button(self,ID_VERIFY) #buttons.Add(bt,0) #self.Bind(wx.EVT_BUTTON, self.OnVerify, bt) #bt = wx.Button(self,ID_CHARACTERIZE) #buttons.Add(bt,0) #self.Bind(wx.EVT_BUTTON, self.OnCharacterize, bt) #sizer.Add(buttons, 0, wx.ALIGN_LEFT) # Top: input self.top = wx.Notebook(self,-1) # Editor there self.editor = Editor.selectEditor(self.top) if self.load: textfile = open(os.path.join(self.dirname, self.filename), 'r') self.editor.SetText(textfile.read()) if self.dirname != "": os.chdir(self.dirname) textfile.close() self.editor.SetOpened() self.top.AddPage(self.editor.control,"Protocol description") self.settings = Settingswindow.SettingsWindow(self.top,self) self.top.AddPage(self.settings,"Settings")
def GetPassword(user): """Get a user's password.""" if user == "admin": return GetAdminPassword() if user in GetModule.GetEditors(): m = Editor.Editor(user) return hashlib.new('sha1', m.password).hexdigest() return None
def CheckPassword(user, password): """Check a user's password.""" if user == "admin": return CheckAdminPassword(password) if user in GetModule.GetEditors(): m = Editor.Editor(user) return password == m.password return 0
def translate(to_translate, to_langage="tr", langage="en"): '''Return the translation using google translate you must shortcut the langage you define (French = fr, English = en, Spanish = es, etc...) if you don't define anything it will detect it or use english by default Example: print(translate("salut tu vas bien?", "en")) hello you alright?''' agents = { 'User-Agent': "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)" } before_trans = 'result-container">' link = "http://translate.google.com/m?hl=%s&sl=%s&q=%s" % ( to_langage, langage, to_translate.replace(" ", "+").replace("&", "")) request = urllib2.Request(link, headers=agents) page = urllib2.urlopen(request).read() result = page[page.find(before_trans) + len(before_trans):] result = result.split("<")[0] #return result if not result: return # if __name__ == '__main__': # to_translate = 'Hello, how are you?' # print("%s >> %s" % (to_translate, translate(to_translate))) # print("%s >> %s" % (to_translate, translate(to_translate, 'fr'))) # #should print Hola como estas >> Hello how are you # #and Hola como estas? >> Bonjour comment allez-vous? Editor.setEntryTarget( Editor.currentEntry(), 0, result.replace('\ n', "\\n\n").replace('% ', "%").replace( '\ N', "\\n\n").replace('"', "\"").replace('<', "<").replace( '>', ">").replace(''', "'").replace( ' <Nl /> ', '<nl/>').replace('</para> ', '</para>').replace( ' </para>', '</para>').replace('+', ' ').replace( '<para> ', '<para>').replace( '<para> ', '<para>').replace( '<emphasis> ', '<emphasis>').replace( ' </emphasis>', '</emphasis>').replace( '<interface> ', '<interface>').replace( ' </interface>', '</interface>'))
def initMainUi(self): self.tab_widget = QTabWidget() self.tab_widget.setTabsClosable(True) self.tab_widget.tabCloseRequested.connect(self.closeTab) self.resize(400, 400) #self.showMaximized() self.new_tab1 = Editor(self) self.tab_widget.addTab(self.new_tab1, 'test') self.toolbar = self.addToolBar('New') newAction = QAction('新增', self) newAction.triggered.connect(self.setValue) self.toolbar.addAction(newAction) self.setCentralWidget(self.tab_widget)
def main(): """ Our main function is going to do lots of setup from the setup module, it will setup the level size and name, then pygame display information, then it will draw everything to the screen and start the "game" loop. """ level_width, level_height = setup_level_size() level_name = setup_level_name() editor_screen = setup_pygame_display() background = setup_background(editor_screen.get_size()) level = Level.Level(width=level_width, height=level_height) level_editor = Editor.Editor(level) # Editor draw position will be the center of the screen level_editor.set_draw_pos( background.get_width() / 2 - level_editor.editor_surface.get_width() / 2, background.get_height() / 2 - level_editor.editor_surface.get_height() / 2) background.blit(level_editor.editor_surface, level_editor.get_draw_pos()) editor_screen.blit(background, (0, 0)) # Main "game" loop, it handles input and renders the editor(as well as any changes that occur) while level_editor.running: for event in pygame.event.get(): if event.type == pygame.VIDEORESIZE: editor_screen = setup_pygame_display(event.dict['size']) background = setup_background(editor_screen.get_size()) level_editor.set_draw_pos( background.get_width() / 2 - level_editor.editor_surface.get_width() / 2, background.get_height() / 2 - level_editor.editor_surface.get_height() / 2) elif event.type == pygame.QUIT: level_editor.save_level(level_name) level_editor.close() else: level_editor.handle_event(event) level_editor.render() background.blit(level_editor.editor_surface, level_editor.get_draw_pos()) editor_screen.blit(background, (0, 0)) pygame.display.flip() # Exit when we leave the main loop sys.exit()
def create_central_area(self): self.editor = Editor.Editor(self.master, set_status_text=self.set_status_text, font=self.create_font(), maxundo=0, undo=True, wrap=tk.WORD) self.editor.grid(row=1, column=1, sticky=(tk.N, tk.S, tk.W, tk.E), padx=PAD, pady=PAD) self.editor.text.bind("<<Selection>>", self.on_selection) self.editor.text.bind("<<Modified>>", self.on_modified) self.editor.text.bind("<KeyRelease>", self.on_moved, "+") self.editor.text.bind("<ButtonRelease>", self.on_moved, "+") self.editor.text.focus()
def __init__(self, name, text, parent=None): super(ActivityTab, self).__init__(parent) self.name = name self.text = text self.mainLayout = QtGui.QVBoxLayout() self.editor = Editor.Editor() self.mainLayout.addWidget(self.editor) self.highlight = Highlighter.Highlighter(self.editor.document()) self.editor.setPlainText(self.text[0]) #self.setFixedSize(500,500) self.setLayout(self.mainLayout) self.editor.textCursor().setPosition(0, QtGui.QTextCursor.MoveAnchor)
def GetEditor(parent, model, filename=None): """ """ path = os.path.join(model.model_path, ZipManager.Zip.GetPluginFile(model.model_path)) if not filename else filename name = os.path.basename(path) ### editor frame for the text of plug-ins editorFrame = Editor.GetEditor(None, \ wx.ID_ANY, \ _("%s - Plug-ins Editor")%os.path.basename(model.model_path), \ model, \ file_type = 'block') editorFrame.AddEditPage(name, path) return editorFrame
def __init__(self): QMainWindow.__init__(self, windowTitle=u"配置表编辑器") self.m_PaintWidget = PaintWidget.PaintWidget() #申请一个新的QWidget修改来添加grid布局器 mainQWidget = QWidget() self.setCentralWidget(mainQWidget) #布局器 grid = QGridLayout() grid.setSpacing(2) mainQWidget.setLayout(grid) #菜单栏 FileMemu = self.menuBar().addMenu(u"菜单") saveAction = QAction(u"保存", FileMemu) saveAction.triggered.connect(self.save) readAction = QAction(u"读取", FileMemu) readAction.triggered.connect(self.read) FileMemu.addAction(saveAction) FileMemu.addAction(readAction) #画布 #TODO 画布大小自动调整 self.m_PaintWidget.setMinimumSize(2000, 2000) Scroll = QScrollArea() Scroll.setWidget(self.m_PaintWidget) Scroll.setAutoFillBackground(True) Scroll.setWidgetResizable(True) grid.addWidget(Scroll, 0, 1) #layer的属性编辑 editor = Editor.LayerConfigEditor() grid.addWidget(editor, 0, 0) self.setCentralWidget(mainQWidget) #向画板传递editor的句柄,方便回调编辑 self.m_PaintWidget.m_editor = editor #设置布局器比例 grid.setColumnStretch(0, 3) grid.setColumnStretch(1, 10) #添加工具栏,提供属性编辑 editorTooBar = QToolBar() self.addToolBar(Qt.TopToolBarArea, editorTooBar) self.read()
def __init__(self, fileName, parent=None): self.fileName = fileName super(Tab, self).__init__(parent) self.setObjectName("tab2") self.textEdit = Editor(self) self.textEdit.setObjectName("textEdit2") horizontalLayout = QHBoxLayout(self) horizontalLayout.setMargin(0) horizontalLayout.setObjectName("horizontalLayout2") horizontalLayout.addWidget(self.textEdit) self.actionCloseTab = QAction(parent)
def selector(cal, a): "Select enter value in mode" print "\nEnter year, month, day: |example: 1995 april 20|" y, m, d = day() if In_out.check_date(y, m, d): if int(a) == 2: In_out.Out_day(cal, y, m, d) if int(a) == 3: w, t, wind = weath() Editor.add_el(cal, y, m, d, w, t, wind) if int(a) == 4: Editor.del_el(cal, y, m, d) if int(a) == 5: Editor.del_el(cal, y, m, d) Editor.add_el(cal, y, m, d) else: print "Incorrect input date!" return cal
def readSelectedArea(self, file_name, x1, y1, x2, y2): print() print("Please mark your forest.", file_name) e = Editor.Editor(file_name) im = Image.open("files/" + file_name + "bitmask" + '.png') imarray = np.array(im) height = imarray.shape[0] width = imarray.shape[1] #print(height) #print(width) bitmask = np.zeros((height // cell_size, width // cell_size), np.int) print("Reading bitmask:") pb = ProgressBar.ProgressBar() for i in range(5, bitmask.shape[0] * cell_size, cell_size): for j in range(5, bitmask.shape[1] * cell_size, cell_size): y = i // cell_size x = j // cell_size if (imarray[i][j] == [255, 0, 0]).all(): bitmask[y][x] = 1 elif (imarray[i][j] == [255, 255, 0]).all(): bitmask[y][x] = 2 elif (imarray[i][j] == [0, 128, 0]).all(): bitmask[y][x] = 3 else: bitmask[y][x] = 0 pb.printProgress(i, height // cell_size) pb.printProgress(100, 100) print() for i in range(0, bitmask.shape[0]): for j in range(0, bitmask.shape[1]): if bitmask[i][j] == 1: print("R", end=" ") elif bitmask[i][j] == 2: print("Y", end=" ") elif bitmask[i][j] == 3: print("G", end=" ") else: print(".", end=" ") print() total_carbon = self.calculateCarbon(file_name, bitmask, x1, y1, x2, y2, width, height) return (bitmask, total_carbon, x1, y1, datetime.datetime.now())
def OnEdit(self, event): """ """ index = self.currentItem path = self.GetPath(index) if self.IsSelected(index) and path and path.endswith('.py'): name = os.path.basename(path) module = self.GetPyData(index)[0] ### editor frame for the text of plug-ins editorFrame = Editor.GetEditor(None, \ wx.NewIdRef(), \ _("%s - Plug-ins Editor")%name, \ module, \ file_type = 'block') editorFrame.AddEditPage(name, path) editorFrame.Show() ### for .pyc file else: pass
def OnEdit(self, event): """ """ for i in range(self.GetItemCount()): module = self.GetPyData(i)[0] if self.IsSelected(i) and module: path = module.__file__ if path.endswith('.py'): name = os.path.basename(path) ### editor frame for the text of plug-ins editorFrame = Editor.GetEditor(None, \ wx.NewIdRef(), \ _("%s - Plug-ins Editor")%name, \ module, \ file_type = 'block') editorFrame.AddEditPage(name, path) editorFrame.Show() ### for .pyc file else: pass
def mergeOneOdf(xliffpathname): xliffpathname=Editor.currentFile() (path, filename)=os.path.split(xliffpathname) if not filename.endswith('.xlf'): return xlifftemplatepathname=path+'/t_'+filename print xlifftemplatepathname store = factory.getobject(xliffpathname) odfpathname=store.getfilenames()[0] if odfpathname.startswith('NoName'): print 'translate-toolkit is too old' odfpathname=os.path.splitext(xliffpathname)[0]+'.odt' if not os.path.exists(odfpathname): return print 'odf2xliff via subprocess.call', unicode(odfpathname), unicode(xlifftemplatepathname) try: retcode = subprocess.call(['odf2xliff', unicode(odfpathname), unicode(xlifftemplatepathname)]) print >>sys.stderr except OSError, e: print >>sys.stderr, "Execution failed:", e
def OnStrategies(event): ''' Event Handler for the strategies definition ''' global shape #obj = event.GetEventObject() #canvas = obj.GetParent() ### .amd file amd = zipfile.ZipFile(shape.model_path, 'a') ### test if strategies file is zipped if 'strategies.py' not in amd.namelist(): try: amd.writestr(zipfile.ZipInfo('strategies.py'), '') finally: amd.close() else: amd.close() editorFrame = Editor.GetEditor(None, wx.ID_ANY, _('Strategies definition')) editorFrame.AddEditPage("Strategies",os.path.join(shape.model_path, 'strategies.py')) editorFrame.Show()
def main(stdscr): (y, x) = stdscr.getmaxyx() ed = Editor.Editor(y - 1, x) ed.buffer.load_from_file("test.txt") curses.curs_set(0) update(stdscr, ed) event = -1 while True: if event == 4: break elif event == curses.KEY_RESIZE: (y, x) = stdscr.getmaxyx() ed.set_win(0, y, x) update(stdscr, ed) elif event == curses.KEY_UP: ed.move_cursor(row=ed.cursor.y - 1, col=ed.cursor.x) update(stdscr, ed) elif event == curses.KEY_DOWN: ed.move_cursor(row=ed.cursor.y + 1, col=ed.cursor.x) update(stdscr, ed) elif event == curses.KEY_LEFT: ed.move_cursor(row=ed.cursor.y, col=ed.cursor.x - 1) update(stdscr, ed) elif event == curses.KEY_RIGHT: ed.move_cursor(row=ed.cursor.y, col=ed.cursor.x + 1) update(stdscr, ed) elif event == 5: ed.move_window(ed.win.top + 1) update(stdscr, ed) elif event == 25: ed.move_window(ed.win.top - 1) update(stdscr, ed) stdscr.addstr(y - 1, min(20, x - 15), str(event) + " ") stdscr.chgat(ed.cursor.y - ed.win.top, ed.cursor.x, 1, curses.A_STANDOUT) stdscr.refresh() event = stdscr.getch()
def mouseDoubleClickEvent(self, event): """ @鼠标双击事件回调 @坐标落在空白处,触发生成一个新的层的逻辑 @坐标落在矩形内部,触发生成一个新的连接的逻辑 """ #走单击的逻辑 self.PressChooseShape(event) #触发新建连接的逻辑 if self.m_sChooseShapeName != None and self.m_sChooseShapeName != "": History.push(self.m_dLayers) shapeObj = self.m_dShape[self.m_sChooseShapeName] lineObj = BaseShape.Line() lineObj.setStart(event.pos()) lineObj.setEnd(event.pos()) lineObj.m_left = self.m_sChooseShapeName lineObj.m_curConner = 1 sName = lineObj.m_left + lineObj.m_left self.m_dShape[sName] = lineObj self.m_sChooseShapeName = sName #触发新建层的逻辑 else: editor = Editor.CreateLayerEditor(self.createLayerCallback) editor.exec_()
def main(): current_entry = Editor.currentEntry() source = Editor.entrySource(current_entry, 0).decode("utf-8") target = Editor.entryTarget(current_entry, 0).decode("utf-8") source_tags = get_tags(source) target_tags = get_tags(target) if len(source_tags) - len(target_tags) <= 0: return tag_to_insert = source_tags[len(target_tags)] selection = Editor.selectionInTarget() if selection: selection = selection.decode("utf-8") tmp = replace_inner_text(tag_to_insert, selection) partition = target.rfind(selection) target = target[:partition] + target[partition:].replace(selection, tmp) else: target += tag_to_insert Editor.setEntryTarget(current_entry, 0, target.encode("utf-8"))
def open_filters(self): Editor.native_open(Config.settings.filters_path)
def edit_filters(self): Editor.TextEditor(Config.settings.filters_path)
def editeur(): """Open the editor to create your own painting""" Editor.editor()
def setUp(self): self.e = Editor()
def __init__(self): self.filer = FileHandler() self.validator = Validator() self.database = Database() self.editor = Editor() self.plotter = Plotter()
import sys sys.path.append('./scripts') sys.path.append('./scripts/libs') import string import Interface import Event import App import Editor from Interface import * from Event import * from App import * from Editor import * from World import * ########################################################## #####Global variables I = Editor.getInterface() #Interface manager A = App.get() #Application E = Event.get() #Event manager ########################################################## #####Counter, returns new value every time def counter(): static_counter = 0 while True: static_counter += 1 yield static_counter count = counter().next ######################################################################### #####Function creates simple message box with specified title and name #####Message box has one button - ok and is destroyed by interface manager #####after pressing this button. #####Every new popup window has unique id.
def makeFullCFG(input,output): GUI.runGUI(input,'test.xml') Editor.runEditor('test.xml','test2.xml') CreateCFG.writeCFGs('test2.xml',output)
def initUI(self): #Set up menubar ##Set Up menu actions newAction = QtGui.QAction('&New',self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('New file') fileAction = QtGui.QAction('&Open',self) fileAction.setShortcut('Ctrl+O') fileAction.setStatusTip('Open File') self.connect(fileAction, QtCore.SIGNAL('triggered()'), self.showOpenDialog) NameFileAction = QtGui.QAction('&名前を付けて保存',self) NameFileAction.setShortcut('Ctrl+A') NameFileAction.setStatusTip('名前を付けて保存') self.connect(NameFileAction, QtCore.SIGNAL('triggered()'), self.showSaveDialog) xmlAction = QtGui.QAction('&XMLの書き出し',self) xmlAction.setShortcut('Ctrl+L') xmlAction.setStatusTip('XMLの書き出し') self.connect(xmlAction,QtCore.SIGNAL('triggered()'), self.showxmlDialog) wavAction = QtGui.QAction('&wavの書き出し', self) wavAction.setShortcut('Ctrl+L') wavAction.setStatusTip('wavの書き出し') self.connect(wavAction, QtCore.SIGNAL('triggered()'), self.showwavDialog) exitAction = QtGui.QAction('&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) flgviewAction = QtGui.QAction('&Toggle flag editor', self) flgviewAction.setStatusTip('Show/Hide the flag editor view') flgviewAction.triggered.connect(self.flgviewToggle) tselectAction = QtGui.QAction('&Select', self) tselectAction.setStatusTip("Note select and edit tool") tselectAction.triggered.connect(self.toolSelect) tpenAction = QtGui.QAction('&Pen', self) tpenAction.setStatusTip("Note draw tool") tpenAction.triggered.connect(self.toolPen) teraseAction = QtGui.QAction('&Erase', self) teraseAction.setStatusTip("Note erase tool") teraseAction.triggered.connect(self.toolErase) tpquant4Action = QtGui.QAction('&L4 Quarter Note', self) tpquant4Action.setStatusTip('Set Quantization to Quarter notes') tpquant4Action.triggered.connect(self.quant4) tpquant8Action = QtGui.QAction('&L8 Eighth Note', self) tpquant8Action.setStatusTip('Set Quantization to Eighth notes') tpquant8Action.triggered.connect(self.quant8) tpquant16Action = QtGui.QAction('&L16 Sixteenth Note', self) tpquant16Action.setStatusTip('Set Quantization to Sixteenth notes') tpquant16Action.triggered.connect(self.quant16) playAction=QtGui.QAction('&Play',self) playAction.setStatusTip('Synthesize') playAction.triggered.connect(self.playAction) MonoAction=QtGui.QAction('&monoラベルの書き出し',self) MonoAction.setStatusTip('monoラベル書き出し') self.connect(MonoAction, QtCore.SIGNAL('triggered()'), self.MonoDialog) ##Menubar Menus setup menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(newAction) fileMenu.addAction(fileAction) fileMenu.addAction(NameFileAction) fileMenu.addAction(xmlAction) fileMenu.addAction(wavAction) fileMenu.addAction(MonoAction) fileMenu.addAction(exitAction) editMenu = menubar.addMenu('&Edit') trackMenu = menubar.addMenu('&Track') viewMenu = menubar.addMenu('&View') viewMenu.addAction(flgviewAction) searchMenu = menubar.addMenu('&Search') projMenu = menubar.addMenu('&Project') projMenu.addAction(playAction) toolMenu = menubar.addMenu('&Tools') toolMenu.addAction(tselectAction) toolMenu.addAction(tpenAction) toolMenu.addAction(teraseAction) quantMenu = toolMenu.addMenu('&Quantization') quantMenu.addAction(tpquant4Action) quantMenu.addAction(tpquant8Action) quantMenu.addAction(tpquant16Action) ModeMenu = menubar.addMenu('&Mode') self.quantize = 4 helpMenu = menubar.addMenu('&Help') savemeMenu = helpMenu.addMenu('&Save me from this hell') nopeLabel = savemeMenu.addMenu('&There is no salvation') #Set Up Tool Bar? yeah self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(exitAction) #Status bar message self.statusBar().showMessage('This is the status bar message :D') self.track = Editor.noteEditor(self) self.track.show() #hide scroll bars and hide their bg bars self.piano = Editor.pianoRoll(self) self.piano.show() self.piano.verticalScrollBar().hide() self.piano.verticalScrollBar().setStyleSheet("QScrollBar {width:0px;}") self.piano.horizontalScrollBar().hide() self.piano.horizontalScrollBar().setStyleSheet("QScrollBar {height:0px;}") self.measure = Editor.measureDraw(self) self.measure.show() #newmeasureCnt self.measure.verticalScrollBar().hide() self.measure.verticalScrollBar().setStyleSheet("QScrollBar {width:0px;}") self.measure.horizontalScrollBar().hide() self.measure.horizontalScrollBar().setStyleSheet("QScrollBar {height:0px;}") #Show Window self.setGeometry(300, 300, 800, 600) self.setWindowTitle('SiVo') self.show()
# -*- coding: utf-8 -*- import os,sys import Editor import Lokalize import subprocess from opensrc_list import mapSrc print Editor.currentFile() editor=Editor globals()['test']='sssss' lll=['sss'] ourPath=([p for p in sys.path if p.endswith('/scripts/lokalize')]+[''])[0] def srcFileOpenRequested(filename, line): try: Editor.setSrcFileOpenRequestAccepted(True) except: print 'your lokalize needs update ;)' if not editor.isValid() or editor.currentFile()=='': return import Kross forms = Kross.module("forms") print filename (path, pofilename)=os.path.split(Editor.currentFile()) (package, ext)=os.path.splitext(pofilename) (upperPath, module)=os.path.split(path) if module.startswith('extragear-'): module=module.replace('extragear-','../extragear/') elif module.startswith('playground-'): module=module.replace('playground-','../playground/')