Commits

Chaiwat Suttipongsakul  committed 9c9e5fc

Modernize some codes, rename variable names from preserved words, fix integer and float calculation.

  • Participants
  • Parent commits 9f4cce7

Comments (0)

Files changed (18)

 
 import os, string, time, warnings
 
+if sys.getdefaultencoding() != 'utf-8':
+    from imp import reload
+    reload(sys)
+    set_default_encoding = getattr(sys, 'setdefaultencoding')
+    if set_default_encoding:
+        set_default_encoding('utf-8')
+
 #sys.stdout = sys.__stdout__#open('stdout.txt', 'w')
 #sys.stderr = sys.__stderr__#open('stderr.txt', 'w')
 

File ClassBrowser.py

         moduleName = ''
         for className in self.classes.keys():
             moduleName = os.path.basename(self.classes[className].file)
-            if not modules.has_key(moduleName):
+            if not moduleName in modules:
                 modules[moduleName] = {}
             modules[moduleName][className] = {}
             modules[moduleName][className]['Properties'] = {}
                 if (method[:2] == '__'):
                     modules[moduleName][className]['Built-in'][method] = self.classes[className].lineno
                 elif (method[:3] == 'Get'):
-                    if self.classes[className].methods.has_key('Set'+method[3:]):
+                    if 'Set'+method[3:] in self.classes[className].methods:
                         modules[moduleName][className]['Properties'][method[3:]] = self.classes[className].lineno
                     else:
                         modules[moduleName][className]['Methods'][method] = self.classes[className].lineno
                 elif (method[:3] == 'Set'):
-                    if self.classes[className].methods.has_key('Get'+method[3:]):
+                    if 'Get'+method[3:] in self.classes[className].methods:
                         modules[moduleName][className]['Properties'][method[3:]] = self.classes[className].lineno
                     else:
                         modules[moduleName][className]['Methods'][method] = self.classes[className].lineno
     return tree.AddRoot(name)
 
 def travTilBase(name, classes, root):
-    if not classes.has_key(name):
-        if not root.has_key(name):
+    if not name in classes:
+        if not name in root:
             root[name] = {}
         return root[name]
     elif len(classes[name].super) == 0:
-        if not root.has_key(name):
+        if not name in root:
             root[name] = {}
         return root[name]
     else:
         if type(super1) != type(''):
             super1 = super1.name
         c = travTilBase(super1, classes, root)
-        if not c.has_key(name):
+        if not name in c:
             c[name] = {}
         return c[name]
 

File Companions/BaseCompanions.py

         pass
 
     def getPropEditor(self, prop):
-        if self.editors.has_key(prop): return self.editors[prop]
+        if prop in self.editors: return self.editors[prop]
         else: return None
 
     def getPropOptions(self, prop):
-        if self.options.has_key(prop): return self.options[prop]
+        if prop in self.options: return self.options[prop]
         else: return None
 
     def getPropNames(self, prop):
 
-        if self.names.has_key(prop):
+        if prop in self.names:
             return self.names[prop]
         else:
             return None
 
     def checkTriggers(self, name, oldValue, newValue):
         #trigger specially handled callbacks for property changes with consequences
-        if self.triggers.has_key(name):
+        if name in self.triggers:
             self.triggers[name](oldValue, newValue)
 
     def getCompName(self):
     def persistProp(self, name, setterName, value):
         c = self.constructor()
         #constructor
-        if c.has_key(name):
+        if name in c:
             self.textConstr.params[c[name]] = value
         #property
         elif name not in self.dontPersistProps():
     def persistedPropVal(self, name, setterName):
         c = self.constructor()
         #constructor
-        if c.has_key(name):
+        if name in c:
             return self.textConstr.params[c[name]]
         #property
         elif name not in self.dontPersistProps():
             parameters to default values """
         c = self.constructor()
         #constructor
-        if c.has_key(name):
+        if name in c:
             defVal = self.designTimeSource()[c[name]]
             self.textConstr.params[c[name]] = defVal
         #property
             or constructor parameter """
         c = self.constructor()
         #constructor
-        if c.has_key(name):
+        if name in c:
             try:
                 dts = self.designTimeSource()
             except TypeError:
                 return True
             else:
-                if dts.has_key(c[name]):
+                if c[name] in dts:
                     defVal = self.designTimeSource()[c[name]]
                     return self.textConstr.params[c[name]] == defVal
                 else:
 
     def SetName(self, oldValue, newValue):
         """ Triggered when the 'Name' property is changed """
-        if self.designer.objects.has_key(newValue):
+        if newValue in self.designer.objects:
             wx.LogError(_('There is already an object named %s')%newValue)
         else:
             self.name = newValue
                 model = self.designer.model
                 # Either rename the event or add if a new one
                 # The first streamed occurrence will do the rename or add
-                if evt.prev_trigger_meth and module and module.classes[
-                      model.main].methods.has_key(evt.prev_trigger_meth):
+                if (evt.prev_trigger_meth and module
+                        and (evt.prev_trigger_meth in
+                            module.classes[model.main].methods)):
                     module.renameMethod(model.main, evt.prev_trigger_meth,
                           evt.trigger_meth)
-                elif module and not module.classes[
-                      model.main].methods.has_key(evt.trigger_meth):
+                elif module and not evt.trigger_meth in module.classes[model.main].methods:
                     module.addMethod(model.main, evt.trigger_meth,
                        'self, event', [sourceconst.bodyIndent + 'event.Skip()'])
 
         """ Write out dependent properties if all the ctrls they reference
             have been created.
         """
-        if depLinks.has_key(ctrlName):
+        if ctrlName in depLinks:
             for prop, otherRefs in depLinks[ctrlName]:
                 for oRf in otherRefs:
                     if oRf not in definedCtrls:
         #print 'afterResize'
 
     def updatePosAndSize(self):
-        if self.textConstr and self.textConstr.params.has_key('pos') \
-              and self.textConstr.params.has_key('size'):
+        if self.textConstr and 'pos' in self.textConstr.params \
+              and 'size' in self.textConstr.params:
             pos = self.control.GetPosition()
             size = self.control.GetSize()
             self.textConstr.params['pos'] = 'wx.Point(%d, %d)' % (pos.x, pos.y)
     def getDisplayProp(self):
         tcl = self.textConstrLst[self.index]
         if tcl.method != self.insertionMethod:
-            if self.additionalMethods.has_key(tcl.method):
+            if tcl.method in self.additionalMethods:
                 displayProp = self.additionalMethods[tcl.method][1]
             else:
                 return '-'
         else:
             displayProp = self.displayProp
 
-        if tcl.params.has_key(displayProp):
+        if displayProp in tcl.params:
             propSrc = tcl.params[displayProp]
             if propSrc and (propSrc[0] in ("'", '"') or propSrc[:2] in ('u"', "u'")):
                 return self.eval(propSrc)
 
     def getWinId(self):
         tcl = self.textConstrLst[self.index]
-        if tcl.params.has_key(self.idProp):
+        if self.idProp in tcl.params:
             return tcl.params[self.idProp]
         else:
             return -1
 
     def addIds(self, lst):
         for constr in self.textConstrLst:
-            if constr.params.has_key(self.idProp):
+            if self.idProp in constr.params:
                 wId = constr.params[self.idProp]
                 if wId in EventCollections.reservedWxIds:
                     name, wId = self.newUnusedItemNames(0)
 
     def deleteItemEvents(self, idx):
         constr = self.textConstrLst[idx]
-        if constr.params.has_key(self.idProp):
+        if self.idProp in constr.params:
             wIdStr = constr.params[self.idProp]
             for evt in self.textEventList[:]:
                 if evt.windowid == wIdStr:
 
     def isIdUsed(self, wId):
         for tc in self.textConstrLst:
-            if tc.params.has_key(self.idProp) and tc.params[self.idProp] == wId:
+            if self.idProp in tc.params and tc.params[self.idProp] == wId:
                 return True
         return False
 

File Companions/ContainerCompanions.py

 
     def OnPageChanged(self, event):
         try:
-            if self.collections.has_key('Pages'):
+            if 'Pages' in self.collections:
                 self.collections['Pages'].updateSelection(event.GetSelection())
                 wx.PostEvent(self.control, wx.SizeEvent( self.control.GetSize() ))
         except Exception, err:
             if compn != self:
                 compnSrcRef = Utils.srcRefFromCtrlName(compn.name)
                 for constr in self.textConstrLst:
-                    if constr.params.has_key('control'):
+                    if 'control' in constr.params:
                         if compnSrcRef == constr.params['control']:
                             constr.params['control'] = 'None'
                             idx = self.textConstrLst.index(constr)
         CollectionIddDTC.writeCollectionItems(self, output, stripFrmId)
         warn = 0
         for constr in self.textConstrLst:
-            if constr.params.has_key('control') and constr.params['control'] == 'None':
+            if 'control' in constr.params and constr.params['control'] == 'None':
                 wx.LogWarning(_("Invalid None control for toolbar %s's AddControl")%(
                       self.parentCompanion.name))
                 warn = 1
 except AttributeError:
     pass
     
-    
+    

File Companions/LibCompanions.py

 
     def properties(self):
         props = MaskedTextCtrlDTC.properties(self)
-        if props.has_key('Autoformat'):
+        if 'Autoformat' in props:
             del props['Autoformat']
         props['SpinButton'] = ('CompnRoute', self.GetSpinButton,
                                              self.BindSpinButton)

File Companions/SizerCompanions.py

     def SetWindow(self, value):
         self.setParamAndUpdate(0, value)
         colEdKey = (self.parentCompanion.name, 'Items')
-        if self.designer.collEditors.has_key(colEdKey):
+        if colEdKey in self.designer.collEditors:
             collEditView = self.designer.collEditors[colEdKey]
             wx.CallAfter(self.setWindowRefresh, collEditView)
 
     def notification(self, compn, action):
         if action == 'delete' and compn != self:
             compnSrcRef = Utils.srcRefFromCtrlName(compn.name)
-            if self.textConstr.params.has_key(self.ctrlParam) and \
+            if self.ctrlParam in self.textConstr.params and \
                   compnSrcRef == self.textConstr.params[self.ctrlParam]:
                 self.designer.deleteCtrl(self.name)
 

File Companions/UtilCompanions.py

     def getDisplayProp(self):
         value = '-'
         tcl = self.textConstrLst[self.index]
-        if tcl.params.has_key(self.displayProp):
+        if self.displayProp in tcl.params:
             value = tcl.params[self.displayProp]
             if value != 'wx.NullBitmap':
                 if value.startswith('wx.Bitmap'):
 
     def applyDesignTimeDefaults(self, params, method=None):
         dtparams = {}; dtparams.update(params)
-        if dtparams.has_key('mask') and dtparams['mask'] == 'wx.NullBitmap':
+        if 'mask' in dtparams and dtparams['mask'] == 'wx.NullBitmap':
             del dtparams['mask']
         CollectionDTC.applyDesignTimeDefaults(self, dtparams, method)
 
             if compn != self:
                 compnSrcRef = Utils.srcRefFromCtrlName(compn.name)
                 for constr in self.textConstrLst:
-                    if constr.params.has_key('submenu'):
+                    if 'submenu' in constr.params:
                         if compnSrcRef == constr.params['submenu']:
                             constr.params['submenu'] = 'wx.Menu()'
 

File EditorUtils.py

 #                                                  (rect.width-2, rect.height-2))
         self.historyBtnBack = wx.BitmapButton(self, -1,
               Preferences.IS.load('Images/Shared/PreviousSmall.png'),
-              (rect.x+1, rect.y+1), (rect.width/2-1, rect.height-2))
+              (rect.x+1, rect.y+1), (int(round(rect.width/2.0))-1, rect.height-2))
         self.historyBtnFwd = wx.BitmapButton(self, -1,
               Preferences.IS.load('Images/Shared/NextSmall.png'),
-              (rect.x+1+rect.width/2, rect.y+1), (rect.width/2-1, rect.height-2))
+              (rect.x+1+int(round(rect.width/2.0)), rect.y+1), (int(round(rect.width/2.0))-1, rect.height-2))
 
         #self.historyBtns.SetToolTipString('Browse the Traceback/Error/Output window history.')
         tip = _('Browse the Traceback/Error/Output window history.')

File Explorers/ExplorerNodes.py

         ExplorerNode.__init__(self, name, resourcepath, clipboard, imgIdx, parent)
         self.config = config
         self.bold = True
-        if not self.sharedEntries.has_key(self.protocol):
+        if not self.protocol in self.sharedEntries:
             self.sharedEntries[self.itemProtocol] = copy.copy(self.entries)
         self.entries = self.sharedEntries[self.itemProtocol]
         self.refresh()
         for ill_substr in self.illegal_substrs:
             if newName.find(ill_substr) != -1:
                 raise Exception, _('Contains invalid string sequence or char: "%s"')%ill_substr
-        if self.entries.has_key(newName):
+        if newName in self.entries:
             raise Exception, _('Name exists')
         self.entries[newName] = self.entries[name]
         del self.entries[name]
             name = os.path.splitext(os.path.basename(respath[:-1]))[0]
         else:
             name = os.path.splitext(os.path.basename(respath))[0]
-        if self.entries.has_key(name):
+        if name in self.entries:
             name = Utils.getValidName(self.entries.keys(), name)
         self.entries[name] = respath
         self.updateConfig()
     def setPropHook(self, name, value, oldProp = None):
         # scramble sensitive properties before saving
         try:
-            if not self.catNode.entries.has_key(self.name):
+            if not self.name in self.catNode.entries:
                 raise Exception(_('%s not found in the config, renaming config '
                           'entries while Inspecting is not allowed.')%self.name)
 
         explorerRootNodesReg.append(Node.protocol)
 
 def isTransportAvailable(conf, section, prot):
-    return conf.has_option(section, prot) and nodeRegByProt.has_key(prot)
+    return conf.has_option(section, prot) and (prot in nodeRegByProt)
 
 
 #-------------------------------------------------------------------------------

File Models/ResourceSupport.py

         wx.ArtProvider.PushProvider(artProv)
         try:
             m = self.model.getModule()
-            self.cataloged = m.globals.has_key('catalog') and m.globals.has_key('index')
+            self.cataloged = ('catalog' in m.globals) and ('index' in m.globals)
             self.eol = m.eol
             for f in m.function_order:
                 if f.startswith('get') and f.endswith('Data'):
                     name = f[3:-4]
-                    iconFunction = m.functions.has_key('get%sIcon'%name)
+                    iconFunction = 'get%sIcon'%name in m.functions
                     if self.onlyIcons and not iconFunction:
                         continue
                     bmpFunctionStart = m.functions['get%sBitmap'%name].start
 Controllers.resourceClasses.append(PyResourceBitmapModel)
 
 EditorHelper.imageExtReg.append('.py')
-if not EditorHelper.imageSubTypeExtReg.has_key('.py'):
+if not '.py' in EditorHelper.imageSubTypeExtReg:
     EditorHelper.imageSubTypeExtReg['.py'] = []
 EditorHelper.imageSubTypeExtReg['.py'].append(PyResourceBitmapModel)
         self.widgets = widgets
         self.buttons = {}
         parent.AddPage(self, name)
-        self.posX = self.buttonSep/2
-        self.posY = (self.GetSize().y -(24+self.buttonBorder))/2
+        self.posX = int(round(self.buttonSep/2.0))
+        self.posY = int(round((self.GetSize().y -(24+self.buttonBorder))/2.0))
         self.eventOwner = eventOwner
         self.menu =wx.Menu()
         self.menusCheckable = False

File PaletteMapping.py

         
         filename = pluginFilename.lower()
         try:
-            execfile(pluginFilename)
+            exec(open(pluginFilename,'r'))
             succeeded.append(filename)
         except Plugins.SkipPluginSilently, msg:
             fails[filename] = ('Skipped', msg)

File Plug-ins/HelpBook.plug-in.py

     def OnGetItemText(self, item, col):
         f = self.model.config.files[item]
         if col == 0:
-            return `item`
+            return repr(item)
         elif col == 1:
             return os.path.basename(f)
         elif col == 2:
         if sel:
             filenames = [self.model.config.files[idx] for idx in sel]
             filelist = wx.CustomDataObject(wx.CustomDataFormat('FileList'))
-            filelist.SetData(`filenames`)
+            filelist.SetData(repr(filenames))
             #tdo =wx.TextDataObject(filename)
             ds = wx.DropSource(self)
             ds.SetData(filelist)
             self.Delete(item)
 
 
-def visitDir((files, excludes), dirname, names):
+def visitDir(files_excludes, dirname, names):
+    files, excludes = files_excludes
     for name in names:
         if name not in excludes:
             filename = os.path.join(dirname, name)

File Plug-ins/PyInterpreterChooser.plug-in.py

         pyIntpPath = dlg.txtPyIntpPath.GetValue()
 
         if pyIntpPath != Preferences.pythonInterpreterPath:
-            Plugins.updateRcFile('prefs.rc.py', 'pythonInterpreterPath', `pyIntpPath`)
+            Plugins.updateRcFile('prefs.rc.py', 'pythonInterpreterPath', repr(pyIntpPath))
 
             for ver, path in dlg.installedPaths:
                 if path == pyIntpPath:
                         break
                 else:
                     Plugins.updateRcFile('prefs.plug-ins.rc.py', 'picExtraPaths',
-                        `Preferences.picExtraPaths+[pyIntpPath]`)
+                        repr(Preferences.picExtraPaths+[pyIntpPath]))
     finally:
         dlg.Destroy()
 

File Preferences.py

             if rcver < version:
                 _backupAndCopyNewestConfig(prefsFile, file, '.py')
 
-    execfile(file)
+    exec(open(file,'r'))
 
 # upgrade/install config files if needed, different config filetypes handled seperately
 # ConfigParser files
     else:
         screenX, screenY = 0, 0
         # handle dual monitors on Linux
-        if screenWidth / screenHeight >= 2:
-            screenWidth = screenWidth / 2
+        if float(screenWidth) / float(screenHeight) >= 2.0:
+            screenWidth = int(round(screenWidth / 2.0))
     
         screenWidth = int(screenWidth - verticalTaskbarWidth)
         screenHeight = int(screenHeight - horizontalTaskbarHeight - topMenuHeight)
         wxDefaultFramePos = wx.DefaultPosition
         wxDefaultFrameSize = wx.DefaultSize
     else:
-        wxDefaultFramePos = (screenWidth / 4, screenHeight / 4)
+        wxDefaultFramePos = (int(round(screenWidth / 4.0)), int(round(screenHeight / 4.0)))
         wxDefaultFrameSize = (int(round(screenWidth / 1.5)), int(round(screenHeight / 1.5)))
     
     edWidth = int(screenWidth * editorScreenWidthPerc - windowManagerSide * 2)

File ShellEditor.py

         self.fillingWin = Filling(self, -1, style=wx.SP_3DSASH,
               rootObject=self.shellWin.interp.locals, rootIsNamespace=True)
         
-        height = Preferences.screenHeight / 2
+        height = int(round(Preferences.screenHeight / 2.0))
         #int(self.GetSize().y * 0.75)
         self.SplitHorizontally(self.shellWin, self.fillingWin, height)
         self.SetMinimumPaneSize(5)
     confFile = os.path.join(Preferences.rcPath, '%s%s.cfg' % (name,
         forPlatform and '.'+Preferences.thisPlatform or ''))
 
-    if not _sharedConfs.has_key(confFile):
+    if not confFile in _sharedConfs:
         conf = ConfigParser()
         conf.read(confFile)
         conf.confFile = confFile

File ZopeLib/DateTime/DateTime.py

     (0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335))
 yr,mo,dy,hr,mn,sc=gmtime(0)[:6]
 i=int(yr-1)
-to_year =int(i*365+i/4-i/100+i/400-693960.0)
+to_year =int(round(i*365+int(round(i/4.0))-int(round(i/100.0))+int(round(i/400.0))-693960.0))
 to_month=tm[yr%4==0 and (yr%100!=0 or yr%400==0)][mo]
 EPOCH  =(to_year+to_month+dy+(hr/24.0+mn/1440.0+sc/86400.0))*86400
 jd1901 =2415385L
                 localzone = altzone
             else:
                 localzone = timezone
-            offset=(-localzone/(60*60))
+            offset=int(round(-localzone/float(60*60)))
             majorOffset=int(offset)
             if majorOffset != 0 :
                 minorOffset=abs(int((offset % majorOffset) * 60.0))