rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
raise VersionError("wxversion.select() must be called before wxPython is imported")
raise VersionError("wxversion.selectNewest() must be called before wxPython is imported")
def selectNewest(minVersion): """ Selects a version of wxPython that has a version number greater than or equal to the version given. If a matching version is not found then instead of raising an exception like select() does this function will inform the user of that fact with a message dialog, open the system's default web browser to the wxPython download page, and then will exit the application. """ assert type(minVersion) == str # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise VersionError("wxversion.select() must be called before wxPython is imported") bestMatch = None installed = _find_installed(True) minv = _wxPackageInfo(minVersion) if installed: # The list is in reverse sorted order, so if the first one is # big enough then choose it if installed[0] >= minv: bestMatch = installed[0] if bestMatch is None: import wx, webbrowser versions = "\n".join([" "+ver for ver in getInstalled()]) app = wx.PySimpleApp() wx.MessageBox("This application requires a version of wxPython " "greater than or equal to %s but a matching version " "was not found.\n\n" "You currently have these version(s) installed:\n%s" % (minVersion, versions), "wxPython Upgrade Needed", style=wx.OK) app.MainLoop() webbrowser.open("http://sourceforge.net/project/showfiles.php?group_id=10718") sys.exit() sys.path.insert(0, bestMatch.pathname) _selected = bestMatch
0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL |wx.LEFT, 10)
0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL |wx.LEFT|wx.RIGHT, 10)
def __init__(self): wx.Frame.__init__(self, None, -1, "Widget Layout Tester")
idx = self.testHistory.GetSelection()
idx = evt.GetInt()
def OnHistorySelect(self, evt): idx = self.testHistory.GetSelection() if idx != wx.NOT_FOUND: item = self.history[idx] self.moduleName.SetValue(item[0]) self.className.SetValue(item[1]) self.parameters.SetValue(item[2]) self.postCreate.SetValue(item[3])
app = wx.PySimpleApp(redirect=True)
app = wx.PySimpleApp(redirect=False)
def Clear(self): self._fgtxt.SetValue("") self._bgtxt.SetValue("") self._fgclr.SetBackgroundColour(self.GetBackgroundColour()) self._bgclr.SetBackgroundColour(self.GetBackgroundColour()) self._fgclr.Refresh() self._bgclr.Refresh()
if WXPREFIX.startswith(root):
if root is None or WXPREFIX.startswith(root):
def run(self): if os.name == 'nt': return headers = self.distribution.headers if not headers: return
"wx.Choice and then move the mouse into the dineo below \n"
"wx.Choice and then move the mouse into the window below \n"
def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1)
self._controlPoints.Append(control)
self._controlPoints.append(control)
def MakeControlPoints(self): """Make handle control points.""" if self._canvas and self._lineControlPoints: first = self._lineControlPoints[0] last = self._lineControlPoints[-1]
repr_ = reduce(lambda a,b: '%s|%s' % (a,b), value)
if value: repr_ = reduce(lambda a,b: '%s|%s' % (a,b), value) else: repr_ = ''
def SetValue(self, value): self.freeze = True if not value: value = [] self.value = value repr_ = reduce(lambda a,b: '%s|%s' % (a,b), value) self.text.SetValue(repr_) # update text ctrl self.freeze = False
self.InsertWindow(sys.maxint, window, sashPos)
self.InsertWindow(len(self._windows), window, sashPos)
def AppendWindow(self, window, sashPos=-1): """ Add a new window to the splitter at the right side or bottom of the window stack. If sashPos is given then it is used to size the new window. """ self.InsertWindow(sys.maxint, window, sashPos)
idx = idx * 5 + ends[1] / 12 idx = idx - 1 if idx < 0 or idx > 59:
idx = idx * 5 + ends[1] / 12 - 1 elif idx <= 0 or idx > 60:
def _draw(self, dc, shadow=False): ends = [int(x) for x in strftime("%I %M %S", localtime()).split()]
print icon.__class__.__name__
def AddIcon(self, icon, mask = wxNullBitmap): '''Add an icon to the image list, or get the index if already there''' index = self.__magicImageListMapping.get (id (icon)) if index is None: if isinstance( icon, wxIconPtr ): index = self.__magicImageList.AddIcon( icon ) elif isinstance( icon, wxBitmapPtr ): if isinstance( mask, wxColour ): index = self.__magicImageList.AddWithColourMask( icon, mask ) else: index = self.__magicImageList.Add( icon, mask ) else: print icon.__class__.__name__ raise ValueError("Unexpected icon object %s, " "expected wxIcon or wxBitmap" % (icon)) self.__magicImageListMapping [id (icon)] = index return index
self._lastColMinWidth = None
self._resizeColMinWidth = None self._resizeColStyle = "LAST" self._resizeCol = 0
def __init__(self): """ Standard initialiser. """ self._lastColMinWidth = None
self._lastColMinWidth = minWidth
self.resizeCloumn(self, minWidth) def resizeColumn(self, minWidth): self._resizeColMinWidth = minWidth
def resizeLastColumn(self, minWidth): """ Resize the last column appropriately.
if self._lastColMinWidth == None: self._lastColMinWidth = self.GetColumnWidth(numCols - 1)
if(self._resizeColStyle == "LAST"): resizeCol = self.GetColumnCount() else: resizeCol = self._resizeCol if self._resizeColMinWidth == None: self._resizeColMinWidth = self.GetColumnWidth(resizeCol - 1)
def _doResize(self): """ Resize the last column as appropriate.
for col in range(numCols-1): totColWidth = totColWidth + self.GetColumnWidth(col) lastColWidth = self.GetColumnWidth(numCols - 1) if totColWidth + self._lastColMinWidth > listWidth:
for col in range(numCols): if col != (resizeCol-1): totColWidth = totColWidth + self.GetColumnWidth(col) resizeColWidth = self.GetColumnWidth(resizeCol - 1) if totColWidth + self._resizeColMinWidth > listWidth:
def _doResize(self): """ Resize the last column as appropriate.
self.SetColumnWidth(numCols-1, self._lastColMinWidth)
self.SetColumnWidth(resizeCol-1, self._resizeColMinWidth)
def _doResize(self): """ Resize the last column as appropriate.
self.SetColumnWidth(numCols-1, listWidth - totColWidth)
self.SetColumnWidth(resizeCol-1, listWidth - totColWidth)
def _doResize(self): """ Resize the last column as appropriate.
w = self.text.GetSize().width + self.text.GetPosition().x
w = self.text.GetSize().width + self.text.GetPosition().x + 2
def __init__(self, parent, log): wx.Panel.__init__(self, parent, -1) self.log = log self.count = 0
self.spin = wx.SpinButton(self, -1, (w + 6, 50), (h/2, h), wx.SP_VERTICAL)
self.spin = wx.SpinButton(self, -1, (w, 50), (h*2/3, h), wx.SP_VERTICAL)
def __init__(self, parent, log): wx.Panel.__init__(self, parent, -1) self.log = log self.count = 0
dc.DrawLineXY(*coords)
dc.DrawLine(*coords)
def DrawSavedLines(self, dc): dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLUE, 3)) for line in self.lines: for coords in line: dc.DrawLineXY(*coords) dc.EndDrawing()
coords = ((self.x, self.y), event.GetPosition())
coords = ((self.x, self.y), event.GetPositionTuple())
def OnMotion(self, event): if event.Dragging() and not self.mode == "Drag": dc = wx.ClientDC(self) dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLUE, 3)) coords = ((self.x, self.y), event.GetPosition()) self.curLine.append(coords) dc.DrawLineXY(*coords) self.x, self.y = event.GetPositionTuple() dc.EndDrawing()
dc.DrawLineXY(*coords)
dc.DrawLine(*coords)
def OnMotion(self, event): if event.Dragging() and not self.mode == "Drag": dc = wx.ClientDC(self) dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLUE, 3)) coords = ((self.x, self.y), event.GetPosition()) self.curLine.append(coords) dc.DrawLineXY(*coords) self.x, self.y = event.GetPositionTuple() dc.EndDrawing()
lines = wx.InputStream(cPickle.loads(linesdata))
lines = cPickle.loads(linesdata)
def OnData(self, x, y, d): self.log.WriteText("OnData: %d, %d, %d\n" % (x, y, d))
dc.DrawLineXY(*coords)
dc.DrawLine(*coords)
def DrawSavedLines(self, dc): dc.BeginDrawing() dc.SetPen(wx.Pen(wx.RED, 3))
new_select_to = min(edit_end, len(newvalue.rstrip()))
new_select_to = min(edit_end, len(newtext.rstrip()))
def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False): """ Handles replacement of the character at the current insertion point."""
if self.callCallback:
if self.callCallback and self.changeCallback:
def OnChanged(self, evt): if self.callCallback: self.changeCallback(evt)
This demo shows Drand and Drop using a custom data type and a custom data object. A type called "DoodleLines" is created and a Python Pickle of a list is actually transfered in the drag and drop opperation.
This demo shows Drag and Drop using a custom data type and a custom data object. A type called "DoodleLines" is created and a Python Pickle of a list is actually transfered in the drag and drop opperation.
def runTest(frame, nb, log): win = TestPanel(nb, log) return win
wxART_TOOLBAR = misc2c.wxART_TOOLBAR wxART_MENU = misc2c.wxART_MENU wxART_FRAME_ICON = misc2c.wxART_FRAME_ICON wxART_CMN_DIALOG = misc2c.wxART_CMN_DIALOG wxART_HELP_BROWSER = misc2c.wxART_HELP_BROWSER wxART_MESSAGE_BOX = misc2c.wxART_MESSAGE_BOX wxART_OTHER = misc2c.wxART_OTHER wxART_ADD_BOOKMARK = misc2c.wxART_ADD_BOOKMARK wxART_DEL_BOOKMARK = misc2c.wxART_DEL_BOOKMARK wxART_HELP_SIDE_PANEL = misc2c.wxART_HELP_SIDE_PANEL wxART_HELP_SETTINGS = misc2c.wxART_HELP_SETTINGS wxART_HELP_BOOK = misc2c.wxART_HELP_BOOK wxART_HELP_FOLDER = misc2c.wxART_HELP_FOLDER wxART_HELP_PAGE = misc2c.wxART_HELP_PAGE wxART_GO_BACK = misc2c.wxART_GO_BACK wxART_GO_FORWARD = misc2c.wxART_GO_FORWARD wxART_GO_UP = misc2c.wxART_GO_UP wxART_GO_DOWN = misc2c.wxART_GO_DOWN wxART_GO_TO_PARENT = misc2c.wxART_GO_TO_PARENT wxART_GO_HOME = misc2c.wxART_GO_HOME wxART_FILE_OPEN = misc2c.wxART_FILE_OPEN wxART_PRINT = misc2c.wxART_PRINT wxART_HELP = misc2c.wxART_HELP wxART_TIP = misc2c.wxART_TIP wxART_REPORT_VIEW = misc2c.wxART_REPORT_VIEW wxART_LIST_VIEW = misc2c.wxART_LIST_VIEW wxART_NEW_DIR = misc2c.wxART_NEW_DIR wxART_FOLDER = misc2c.wxART_FOLDER wxART_GO_DIR_UP = misc2c.wxART_GO_DIR_UP wxART_EXECUTABLE_FILE = misc2c.wxART_EXECUTABLE_FILE wxART_NORMAL_FILE = misc2c.wxART_NORMAL_FILE wxART_TICK_MARK = misc2c.wxART_TICK_MARK wxART_CROSS_MARK = misc2c.wxART_CROSS_MARK wxART_ERROR = misc2c.wxART_ERROR wxART_QUESTION = misc2c.wxART_QUESTION wxART_WARNING = misc2c.wxART_WARNING wxART_INFORMATION = misc2c.wxART_INFORMATION
def wxArtProvider_GetIcon(*_args, **_kwargs): val = apply(misc2c.wxArtProvider_GetIcon,_args,_kwargs) if val: val = wxIconPtr(val); val.thisown = 1 return val
self, parent, id=-1,
self, parent, id=-1, value = 0,
def __init__ ( self, parent, id=-1, pos = wxDefaultPosition, size = wxDefaultSize, style = 0, validator = wxDefaultValidator, name = "integer", value = 0, min=None, max=None, limited = 0, allow_none = 0, allow_long = 0, default_color = wxBLACK, oob_color = wxRED, ):
value = 0, min=None, max=None,
min=None, max=None,
def __init__ ( self, parent, id=-1, pos = wxDefaultPosition, size = wxDefaultSize, style = 0, validator = wxDefaultValidator, name = "integer", value = 0, min=None, max=None, limited = 0, allow_none = 0, allow_long = 0, default_color = wxBLACK, oob_color = wxRED, ):
if dy == 0 or dx == 0: return False
if dy == 0 and dx == 0: continue
def HitTest(self, x, y): if not self._lineControlPoints: return False
if len(self._lineControlPoints) > 2: self.Initialise()
def OnMoveLink(self, dc, moveControlPoints = True): """Called when a connected object has moved, to move the link to correct position """ if not self._from or not self._to: return
if len(self._lineControlPoints) > 2:
if len(self._lineControlPoints) > 2 and self._initialised:
def FindLineEndPoints(self): """Finds the x, y points at the two ends of the line.
if self._canvas and self._lineControlPoints:
if self._canvas and self._lineControlPoints and self._controlPoints:
def ResetControlPoints(self): if self._canvas and self._lineControlPoints: for i in range(min(len(self._controlPoints), len(self._lineControlPoints))): point = self._lineControlPoints[i] control = self._controlPoints[i] control.SetX(point[0]) control.SetY(point[1])
pt._point = x, y
pt._point[0] = x pt._point[1] = y
def OnSizingDragLeft(self, pt, draw, x, y, keys = 0, attachment = 0): dc = wx.ClientDC(self.GetCanvas()) self.GetCanvas().PrepareDC(dc)
pt._point = x, y
pt._point[0] = x pt._point[1] = y
def OnSizingBeginDragLeft(self, pt, x, y, keys = 0, attachment = 0): dc = wx.ClientDC(self.GetCanvas()) self.GetCanvas().PrepareDC(dc)
pt._point = pt._originalPos[0], pt._originalPos[1]
pt._point[0] = pt._originalPos[0] pt._point[1] = pt._originalPos[1]
def OnSizingEndDragLeft(self, pt, x, y, keys = 0, attachment = 0): dc = wx.ClientDC(self.GetCanvas()) self.GetCanvas().PrepareDC(dc)
lpt._point = pt[0], pt[1]
lpt._point[0] = pt[0] lpt._point[1] = pt[1]
def OnMoveMiddleControlPoint(self, dc, lpt, pt): lpt._xpos = pt[0] lpt._ypos = pt[1]
"""
'''
def debug(msg): if DEBUG: print msg
class DemoCodeViewer(PythonSTC): def __init__(self, parent, ID): PythonSTC.__init__(self, parent, ID, wx.BORDER_NONE)
class DemoCodeEditor(PythonSTC): def __init__(self, parent): PythonSTC.__init__(self, parent, -1, wx.BORDER_NONE)
def GetTip(self): return "This is my tip"
self.SetReadOnly(False)
def SetValue(self, value): if wx.USE_UNICODE: value = value.decode('iso8859_1') self.SetReadOnly(False) self.SetText(value) self.SetReadOnly(True)
self.SetReadOnly(True)
self.EmptyUndoBuffer() self.SetSavePoint() def IsModified(self): return self.GetModify()
def SetValue(self, value): if wx.USE_UNICODE: value = value.decode('iso8859_1') self.SetReadOnly(False) self.SetText(value) self.SetReadOnly(True)
self.GotoPos(pos)
line = self.LineFromPosition(pos) self.EnsureVisible(line)
def ShowPosition(self, pos): self.GotoPos(pos)
class DemoCodeViewer(wx.TextCtrl): def __init__(self, parent, ID): wx.TextCtrl.__init__(self, parent, ID, style = wx.TE_MULTILINE | wx.TE_READONLY |
class DemoCodeEditor(wx.TextCtrl): def __init__(self, parent): wx.TextCtrl.__init__(self, parent, -1, style = wx.TE_MULTILINE |
def SetUpEditor(self): """ This method carries out the work of setting up the demo editor. It's seperate so as not to clutter up the init code. """ import keyword self.SetLexer(stc.STC_LEX_PYTHON) self.SetKeyWords(0, " ".join(keyword.kwlist))
return apply(os.path.join, tuple(path.split('/')))
str = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): str = '/' + str return str def GetModifiedDirectory(): """ Returns the directory where modified versions of the demo files are stored """ return opj(wx.GetHomeDir() + "/.wxPyDemo/modified/") def GetModifiedFilename(name): """ Returns the filename of the modified version of the specified demo """ if not name.endswith(".py"): name = name + ".py" return GetModifiedDirectory() + name def GetOriginalFilename(name): """ Returns the filename of the original version of the specified demo """ if not name.endswith(".py"): name = name + ".py" return name def DoesModifiedExist(name): """Returns whether the specified demo has a modified copy""" if os.path.exists(GetModifiedFilename(name)): return True else: return False class ModuleDictWrapper: """Emulates a module with a dynamically compiled __dict__""" def __init__(self, dict): self.dict = dict def __getattr__(self, name): if name in self.dict: return self.dict[name] else: raise AttributeError class DemoModules: """ Dynamically manages the original/modified versions of a demo module """ def __init__(self, name): self.modActive = -1 self.name = name self.modules = [[None, "" , "" , "<original>" , None], [None, "" , "" , "<modified>" , None]] self.LoadFromFile(modOriginal, GetOriginalFilename(name)) if DoesModifiedExist(name): self.LoadFromFile(modModified, GetModifiedFilename(name)) def LoadFromFile(self, modID, filename): self.modules[modID][2] = filename file = open(filename, "r") self.LoadFromSource(modID, file.read()) file.close() def LoadFromSource(self, modID, source): self.modules[modID][1] = source self.LoadDict(modID) def LoadDict(self, modID): if self.name != __name__: source = self.modules[modID][1] description = self.modules[modID][3] try: self.modules[modID][0] = {} code = compile(source, description, "exec") exec code in self.modules[modID][0] except: self.modules[modID][4] = DemoError(sys.exc_info()) self.modules[modID][0] = None else: self.modules[modID][4] = None def SetActive(self, modID): if modID != modOriginal and modID != modModified: raise LookupError else: self.modActive = modID def GetActive(self): dict = self.modules[self.modActive][0] if dict is None: return None else: return ModuleDictWrapper(dict) def GetActiveID(self): return self.modActive def GetSource(self, modID = None): if modID is None: modID = self.modActive return self.modules[modID][1] def GetFilename(self, modID = None): if modID is None: modID = self.modActive return self.modules[self.modActive][2] def GetErrorInfo(self, modID = None): if modID is None: modID = self.modActive return self.modules[self.modActive][4] def Exists(self, modID): return self.modules[modID][1] != "" def UpdateFile(self, modID = None): """Updates the file from which a module was loaded with (possibly updated) source""" if modID is None: modID = self.modActive source = self.modules[modID][1] filename = self.modules[modID][2] try: file = open(filename, "w") file.write(source) finally: file.close() def Delete(self, modID): if self.modActive == modID: self.SetActive(0) self.modules[modID][0] = None self.modules[modID][1] = "" self.modules[modID][2] = "" class ReloadDemoPanel(wx.Panel): """ Panel put into the demo tab when the demo just shows some top-level window. Enables the demo to be reloaded after being closed. """ infoText = "This demo runs outside the main window" def __init__(self, parent, codePanel, log): wx.Panel.__init__(self, parent, -1) self.codePanel = codePanel self.log = log self.label = wx.StaticText(self, -1, self.infoText) self.btnReload = wx.Button(self, -1, "Reload Demo") self.btnReload.Bind(wx.EVT_BUTTON, self.OnReload) self.box = wx.BoxSizer(wx.VERTICAL) self.box.Add(self.label, 0, wx.ALIGN_CENTER | wx.ALL, 10) self.box.Add(self.btnReload, 0, wx.ALIGN_CENTER | wx.ALL, 10) self.box.Fit(self) self.SetSizer(self.box) def OnReload(self, event): self.codePanel.ReloadDemo() class DemoError: """Wraps and stores information about the current exception""" def __init__(self, exc_info): import copy excType, excValue = exc_info[:2] self.traceback = traceback.extract_tb(exc_info[2]) if type(excType) == types.ClassType: self.exception_type = excType.__name__ else: self.exception_type = excType if excType is SyntaxError: try: msg, (filename, lineno, self.offset, line) = excValue except: pass else: if not filename: filename = "<string>" line = line.strip() self.traceback.append( (filename, lineno, "", line) ) excValue = msg try: self.exception_details = str(excValue) except: self.exception_details = "<unprintable %s object>" & type(excValue).__name__ del exc_info def __str__(self): ret = "Type %s \n \ Traceback: %s \n \ Details : %s" % ( str(self.exception_type), str(self.traceback), self.exception_details ) return ret class DemoErrorPanel(wx.Panel): """Panel put into the demo tab when the demo fails to run due to errors""" def __init__(self, parent, codePanel, demoError, log): wx.Panel.__init__(self, parent, -1) self.codePanel = codePanel self.nb = parent self.log = log self.box = wx.BoxSizer(wx.VERTICAL) self.box.Add(wx.StaticText(self, -1, "An error has occured while trying to run the demo") , 0, wx.ALIGN_CENTER | wx.TOP, 10) boxInfo = wx.StaticBox(self, -1, "Exception Info" ) boxInfoSizer = wx.StaticBoxSizer(boxInfo, wx.VERTICAL ) boxInfoGrid = wx.FlexGridSizer(0, 2, 0, 0) textFlags = wx.ALIGN_RIGHT | wx.LEFT | wx.RIGHT | wx.TOP boxInfoGrid.Add(wx.StaticText(self, -1, "Type: "), 0, textFlags, 5 ) boxInfoGrid.Add(wx.StaticText(self, -1, demoError.exception_type) , 0, textFlags, 5 ) boxInfoGrid.Add(wx.StaticText(self, -1, "Details: ") , 0, textFlags, 5 ) boxInfoGrid.Add(wx.StaticText(self, -1, demoError.exception_details) , 0, textFlags, 5 ) boxInfoSizer.Add(boxInfoGrid, 0, wx.ALIGN_CENTRE | wx.ALL, 5 ) self.box.Add(boxInfoSizer, 0, wx.ALIGN_CENTER | wx.ALL, 5) from ListCtrl import TestListCtrl self.list = TestListCtrl(self, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER) self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick) self.list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected) self.list.InsertColumn(0, "Filename") self.list.InsertColumn(1, "Line", wx.LIST_FORMAT_RIGHT) self.list.InsertColumn(2, "Function") self.list.InsertColumn(3, "Code") self.InsertTraceback(self.list, demoError.traceback) self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE) self.box.Add(wx.StaticText(self, -1, "Traceback:") , 0, wx.ALIGN_CENTER | wx.TOP, 5) self.box.Add(self.list, 1, wx.GROW | wx.ALIGN_CENTER | wx.ALL, 5) self.box.Add(wx.StaticText(self, -1, "Entries from the demo module are shown in blue\n" + "Double-click on them to go to the offending line") , 0, wx.ALIGN_CENTER | wx.BOTTOM, 5) self.box.Fit(self) self.SetSizer(self.box) def InsertTraceback(self, list, traceback): for x in range(len(traceback)): data = traceback[x] list.InsertStringItem(x, os.path.basename(data[0])) list.SetStringItem(x, 1, str(data[1])) list.SetStringItem(x, 2, str(data[2])) list.SetStringItem(x, 3, str(data[3])) if data[0] == "<original>" or data[0] == "<modified>": self.list.SetItemData(x, int(data[1])) item = self.list.GetItem(x) item.SetTextColour(wx.BLUE) self.list.SetItem(item) else: self.list.SetItemData(x, -1) def OnItemSelected(self, event): self.currentItem = event.m_itemIndex event.Skip() def OnDoubleClick(self, event): line = self.list.GetItemData(self.currentItem) if line != -1: self.nb.SetSelection(1) wx.CallAfter(self.codePanel.JumpToLine, line-1, True) event.Skip()
def opj(path): """Convert paths to the platform-specific separator""" return apply(os.path.join, tuple(path.split('/')))
def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (800, 600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size = (950, 750), style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) self.loaded = False
def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (800, 600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.window = None
self.demoPage = None self.codePage = None self.useModified = False
def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (800, 600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.log = wx.TextCtrl(splitter2, -1, style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) wx.Log_SetActiveTarget(MyLog(self.log))
def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (800, 600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.nb = wx.Notebook(splitter2, -1, style=wx.CLIP_CHILDREN)
def EmptyHandler(evt): pass
self.SetOverview(self.overviewText, overview) self.txt = DemoCodeViewer(self.nb, -1) self.nb.AddPage(self.txt, "Demo Code") self.LoadDemoSource('Main.py')
if "gtk2" in wx.PlatformInfo: self.ovr.NormalizeFontSizes() self.SetOverview(self.overviewText, mainOverview) self.log = wx.TextCtrl(splitter2, -1, style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) wx.Log_SetActiveTarget(MyLog(self.log))
def OnOvrSize(evt, ovr=self.ovr): ovr.SetSize(evt.GetSize())
splitter2.SplitHorizontally(self.nb, self.log, -120) splitter.SplitVertically(self.tree, splitter2, 180)
splitter2.SplitHorizontally(self.nb, self.log, -160) splitter.SplitVertically(self.tree, splitter2, 200)
def OnOvrSize(evt, ovr=self.ovr): ovr.SetSize(evt.GetSize())
splitter.SetSashPosition(sz.height - 120, False)
splitter.SetSashPosition(sz.height - 160, False)
def SplitterOnSize(evt): splitter = evt.GetEventObject() sz = splitter.GetSize() splitter.SetSashPosition(sz.height - 120, False) evt.Skip()
if len(sys.argv) == 2: try: selectedDemo = self.treeMap[sys.argv[1]] except: selectedDemo = None
self.LoadDemo(self.overviewText) self.loaded = True if len(sys.argv) > 1: arg = sys.argv[1] if arg.endswith('.py'): arg = arg[:-3] selectedDemo = self.treeMap.get(arg, None)
def SplitterOnSize(evt): splitter = evt.GetEventObject() sz = splitter.GetSize() splitter.SetSashPosition(sz.height - 120, False) evt.Skip()
if self.dying:
if self.dying or not self.loaded:
def OnSelChanged(self, event): if self.dying: return
self.RunDemo(itemText) def RunDemo(self, itemText): os.chdir(self.cwd) if self.nb.GetPageCount() == 3: if self.nb.GetSelection() == 2: self.nb.SetSelection(0)
self.LoadDemo(itemText) def LoadDemo(self, demoName): try: wx.BeginBusyCursor() os.chdir(self.cwd) self.ShutdownDemoModule() if demoName == self.overviewText: self.demoModules = DemoModules(__name__) self.SetOverview(self.overviewText, mainOverview) self.LoadDemoSource() self.UpdateNotebook(0) else: if os.path.exists(GetOriginalFilename(demoName)): wx.LogMessage("Loading demo %s.py..." % demoName) self.demoModules = DemoModules(demoName) self.LoadDemoSource() self.tree.Refresh() else: self.SetOverview("wxPython", mainOverview) self.codePage = None self.UpdateNotebook(0) finally: wx.EndBusyCursor() def LoadDemoSource(self): self.codePage = None self.codePage = DemoCodePanel(self.nb, self) self.codePage.LoadDemo(self.demoModules) def RunModule(self): """Runs the active module""" module = self.demoModules.GetActive() self.ShutdownDemoModule() overviewText = "" if module is not None: wx.LogMessage("Running demo module...") if hasattr(module, "overview"): overviewText = module.overview wx.YieldIfNeeded() try: self.demoPage = module.runTest(self, self.nb, self) if self.demoPage is None: self.demoPage = ReloadDemoPanel(self.nb, self.codePage, self) except: self.demoPage = DemoErrorPanel(self.nb, self.codePage, DemoError(sys.exc_info()), self) else: self.demoPage = DemoErrorPanel(self.nb, self.codePage, self.demoModules.GetErrorInfo(), self) self.SetOverview(self.demoModules.name + " Overview", overviewText) self.UpdateNotebook() def ShutdownDemoModule(self): if self.demoPage:
def OnSelChanged(self, event): if self.dying: return
if self.window is not None: if hasattr(self.window, "ShutdownDemo"): self.window.ShutdownDemo() wx.SafeYield() self.nb.DeletePage(2) if itemText == self.overviewText: self.LoadDemoSource('Main.py') self.SetOverview(self.overviewText, overview) self.window = None else: if os.path.exists(itemText + '.py'): wx.BeginBusyCursor() wx.LogMessage("Running demo %s.py..." % itemText) try: self.LoadDemoSource(itemText + '.py') if (sys.modules.has_key(itemText)): reload(sys.modules[itemText]) module = __import__(itemText, globals()) self.SetOverview(itemText + " Overview", module.overview) finally: wx.EndBusyCursor() self.tree.Refresh() self.window = module.runTest(self, self.nb, self) if self.window is not None: self.nb.AddPage(self.window, 'Demo') self.nb.SetSelection(2)
if hasattr(self.demoPage, "ShutdownDemo"): self.demoPage.ShutdownDemo() wx.YieldIfNeeded() self.demoPage = None def UpdateNotebook(self, select = -1): nb = self.nb debug = False def UpdatePage(page, pageText): pageExists = False pagePos = -1 for i in range(nb.GetPageCount()): if nb.GetPageText(i) == pageText: pageExists = True pagePos = i break if page: if not pageExists: nb.AddPage(page, pageText) if debug: wx.LogMessage("DBG: ADDED %s" % pageText) else: if nb.GetPage(pagePos) != page: nb.Freeze() nb.DeletePage(pagePos) nb.InsertPage(pagePos, page, pageText) nb.Thaw() if debug: wx.LogMessage("DBG: RELOADED %s" % pageText) else: if debug: wx.LogMessage("DBG: SAVED from reloading %s" % pageText) elif pageExists: nb.DeletePage(pagePos) if debug: wx.LogMessage("DBG: DELETED %s" % pageText)
def RunDemo(self, itemText): os.chdir(self.cwd) if self.nb.GetPageCount() == 3: if self.nb.GetSelection() == 2: self.nb.SetSelection(0) # inform the window that it's time to quit if it cares if self.window is not None: if hasattr(self.window, "ShutdownDemo"): self.window.ShutdownDemo() wx.SafeYield() # in case the page has pending events self.nb.DeletePage(2)
self.ovr.SetPage("") self.txt.Clear() self.window = None self.tree.SetFocus() def LoadDemoSource(self, filename): self.txt.Clear() try: self.txt.SetValue(open(filename).read()) except IOError: self.txt.SetValue("Cannot open %s file." % filename) self.txt.SetInsertionPoint(0) self.txt.ShowPosition(0)
if debug: wx.LogMessage("DBG: STILL GONE - %s" % pageText) if select == -1: select = nb.GetSelection() UpdatePage(self.codePage, "Demo Code") UpdatePage(self.demoPage, "Demo") if select >= 0: nb.SetSelection(select)
def RunDemo(self, itemText): os.chdir(self.cwd) if self.nb.GetPageCount() == 3: if self.nb.GetSelection() == 2: self.nb.SetSelection(0) # inform the window that it's time to quit if it cares if self.window is not None: if hasattr(self.window, "ShutdownDemo"): self.window.ShutdownDemo() wx.SafeYield() # in case the page has pending events self.nb.DeletePage(2)
end = self.txt.GetLastPosition() textstring = self.txt.GetRange(0, end).lower() start = self.txt.GetSelection()[1]
end = editor.GetLastPosition() textstring = editor.GetRange(0, end).lower() start = editor.GetSelection()[1]
def OnFind(self, event): self.nb.SetSelection(1) end = self.txt.GetLastPosition() textstring = self.txt.GetRange(0, end).lower() start = self.txt.GetSelection()[1] findstring = self.finddata.GetFindString().lower() loc = textstring.find(findstring, start) if loc == -1 and start != 0: # string not found, start at beginning start = 0 loc = textstring.find(findstring, start) if loc == -1: dlg = wx.MessageDialog(self, 'Find String Not Found', 'Find String Not Found in Demo File', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() if self.finddlg: if loc == -1: self.finddlg.SetFocus() return else: self.finddlg.Destroy() self.txt.ShowPosition(loc) self.txt.SetSelection(loc, loc + len(findstring))
self.txt.ShowPosition(loc) self.txt.SetSelection(loc, loc + len(findstring))
editor.ShowPosition(loc) editor.SetSelection(loc, loc + len(findstring))
def OnFind(self, event): self.nb.SetSelection(1) end = self.txt.GetLastPosition() textstring = self.txt.GetRange(0, end).lower() start = self.txt.GetSelection()[1] findstring = self.finddata.GetFindString().lower() loc = textstring.find(findstring, start) if loc == -1 and start != 0: # string not found, start at beginning start = 0 loc = textstring.find(findstring, start) if loc == -1: dlg = wx.MessageDialog(self, 'Find String Not Found', 'Find String Not Found in Demo File', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() if self.finddlg: if loc == -1: self.finddlg.SetFocus() return else: self.finddlg.Destroy() self.txt.ShowPosition(loc) self.txt.SetSelection(loc, loc + len(findstring))
self.window = None
self.demoPage = None self.codePage = None
def OnCloseWindow(self, event): self.dying = True self.window = None self.mainmenu = None self.Destroy()
self.window = self.otherWin
self.demoPage = self.otherWin
def OnIdle(self, event): if self.otherWin: self.otherWin.Raise() self.window = self.otherWin self.otherWin = None
wx.LogMessage("OnIconfiy")
wx.LogMessage("OnIconfiy: %d" % evt.Iconized())
def OnIconfiy(self, evt): wx.LogMessage("OnIconfiy") evt.Skip()
frame = wxPythonDemo(None, -1, "wxPython: (A Demonstration)")
frame = wxPythonDemo(None, "wxPython: (A Demonstration)")
def OnClose(self, evt): self.Hide() frame = wxPythonDemo(None, -1, "wxPython: (A Demonstration)") frame.Show() evt.Skip() # Make sure the default handler runs too...
overview = """<html><body>
mainOverview = """<html><body>
def main(): try: demoPath = os.path.dirname(__file__) os.chdir(demoPath) except: pass app = MyApp(0) ##wx.Platform == "__WXMAC__") app.MainLoop()
EVT_CHILD_FOCUS(self, self.OnChildFocus)
wxCallAfter(self.Scroll, 0, 0)
def __init__(self, parent, log): self.log = log wxScrolledWindow.__init__(self, parent, -1, style = wxTAB_TRAVERSAL)
return val def SetVerbose(self, *_args, **_kwargs): val = apply(misc2c.wxLog_SetVerbose,(self,) + _args, _kwargs)
def HasPendingMessages(self, *_args, **_kwargs): val = apply(misc2c.wxLog_HasPendingMessages,(self,) + _args, _kwargs) return val
borderSizer = wx.BoxSizer(wx.HORIZONTAL)
def OnAddDirToProject(self, event): frame = wx.Dialog(None, -1, _("Add All Files from Directory to Project"), size= (320,200)) borderSizer = wx.BoxSizer(wx.HORIZONTAL)
lineSizer.Add(wx.StaticText(frame, -1, _("Directory:")), 0, wx.ALIGN_CENTER | wx.RIGHT, HALF_SPACE) dirCtrl = wx.TextCtrl(frame, -1, os.path.dirname(self.GetDocument().GetFilename()), size=(200,-1))
dirCtrl = wx.TextCtrl(frame, -1, os.path.dirname(self.GetDocument().GetFilename()), size=(250,-1))
def OnAddDirToProject(self, event): frame = wx.Dialog(None, -1, _("Add All Files from Directory to Project"), size= (320,200)) borderSizer = wx.BoxSizer(wx.HORIZONTAL)
lineSizer.Add(dirCtrl, 0, wx.LEFT, HALF_SPACE)
lineSizer.Add(dirCtrl, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
def OnAddDirToProject(self, event): frame = wx.Dialog(None, -1, _("Add All Files from Directory to Project"), size= (320,200)) borderSizer = wx.BoxSizer(wx.HORIZONTAL)
lineSizer.Add(findDirButton, 0, wx.LEFT, HALF_SPACE) contentSizer.Add(lineSizer, 0, wx.BOTTOM, SPACE)
lineSizer.Add(findDirButton, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, HALF_SPACE) flexGridSizer.Add(lineSizer, 1, wx.EXPAND)
def OnAddDirToProject(self, event): frame = wx.Dialog(None, -1, _("Add All Files from Directory to Project"), size= (320,200)) borderSizer = wx.BoxSizer(wx.HORIZONTAL)
filterChoice = wx.Choice(frame, -1, size=(210, -1), choices=choices)
filterChoice = wx.Choice(frame, -1, size=(250, -1), choices=choices)
def OnBrowseButton(event): dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) dir = dirCtrl.GetValue() if len(dir): dlg.SetPath(dir) if dlg.ShowModal() == wx.ID_OK: dirCtrl.SetValue(dlg.GetPath()) dirCtrl.SetToolTipString(dirCtrl.GetValue()) dirCtrl.SetInsertionPointEnd()
lineSizer = wx.BoxSizer(wx.HORIZONTAL) lineSizer.Add(wx.StaticText(frame, -1, _("Files of type:")), 0, wx.ALIGN_CENTER | wx.RIGHT, HALF_SPACE) lineSizer.Add(filterChoice, 1, wx.LEFT, HALF_SPACE) contentSizer.Add(lineSizer, 0, wx.BOTTOM|wx.EXPAND, SPACE)
flexGridSizer.Add(wx.StaticText(frame, -1, _("Files of type:")), 0, wx.ALIGN_CENTER_VERTICAL) flexGridSizer.Add(filterChoice, 1, wx.EXPAND) contentSizer.Add(flexGridSizer, 0, wx.ALL|wx.EXPAND, SPACE)
def OnBrowseButton(event): dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) dir = dirCtrl.GetValue() if len(dir): dlg.SetPath(dir) if dlg.ShowModal() == wx.ID_OK: dirCtrl.SetValue(dlg.GetPath()) dirCtrl.SetToolTipString(dirCtrl.GetValue()) dirCtrl.SetInsertionPointEnd()
contentSizer.Add(subfolderCtrl, 0, wx.BOTTOM, SPACE) borderSizer.Add(contentSizer, 0, wx.TOP|wx.BOTTOM|wx.LEFT, SPACE) buttonSizer = wx.BoxSizer(wx.VERTICAL)
contentSizer.Add(subfolderCtrl, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, SPACE) buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
def OnBrowseButton(event): dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) dir = dirCtrl.GetValue() if len(dir): dlg.SetPath(dir) if dlg.ShowModal() == wx.ID_OK: dirCtrl.SetValue(dlg.GetPath()) dirCtrl.SetToolTipString(dirCtrl.GetValue()) dirCtrl.SetInsertionPointEnd()
buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE)
buttonSizer.Add(findBtn, 0, wx.RIGHT, HALF_SPACE)
def OnBrowseButton(event): dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) dir = dirCtrl.GetValue() if len(dir): dlg.SetPath(dir) if dlg.ShowModal() == wx.ID_OK: dirCtrl.SetValue(dlg.GetPath()) dirCtrl.SetToolTipString(dirCtrl.GetValue()) dirCtrl.SetInsertionPointEnd()
borderSizer.Add(buttonSizer, 0, wx.ALL, SPACE) frame.SetSizer(borderSizer)
contentSizer.Add(buttonSizer, 0, wx.ALL|wx.ALIGN_RIGHT, SPACE) frame.SetSizer(contentSizer)
def OnBrowseButton(event): dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) dir = dirCtrl.GetValue() if len(dir): dlg.SetPath(dir) if dlg.ShowModal() == wx.ID_OK: dirCtrl.SetValue(dlg.GetPath()) dirCtrl.SetToolTipString(dirCtrl.GetValue()) dirCtrl.SetInsertionPointEnd()
(child, cookie2) = self._treeCtrl.GetNextChild(project, cookie)
(child, cookie2) = self._treeCtrl.GetNextChild(project, cookie2)
def _GetFileItem(self, shortFileName = None, longFileName = None): """ Returns the tree item for a file given the short (display) or long (fullpath) file name. """ rootItem = self._treeCtrl.GetRootItem() (project, cookie) = self._treeCtrl.GetFirstChild(rootItem) while project.IsOk(): (child, cookie2) = self._treeCtrl.GetFirstChild(project) while child.IsOk(): if shortFileName: if self._treeCtrl.GetItemText(child) == shortFileName: return child else: if self._treeCtrl.GetLongFilename(child) == longFileName: return child (child, cookie2) = self._treeCtrl.GetNextChild(project, cookie) (project, cookie) = self._treeCtrl.GetNextChild(rootItem, cookie) return None
self.SetHandSize(h, SECOND)
self.SetHandSize(s, SECOND)
def SetHandWeights(self, h=None, m=None, s=None): if h: self.SetHandSize(h, HOUR) if m: self.SetHandSize(m, MINUTE) if s: self.SetHandSize(h, SECOND)
self.SetHandBorderColour(h, SECOND) self.SetHandFillColour(h, SECOND)
self.SetHandBorderColour(s, SECOND) self.SetHandFillColour(s, SECOND)
def SetHandColours(self, h=None, m=None, s=None): if h and not m and not s: m=h s=h if h: self.SetHandBorderColour(h, HOUR) self.SetHandFillColour(h, HOUR) if m: self.SetHandBorderColour(m, MINUTE) self.SetHandFillColour(m, MINUTE) if s: self.SetHandBorderColour(h, SECOND) self.SetHandFillColour(h, SECOND)
self.SetTickSize(h, MINUTE)
self.SetTickSize(m, MINUTE)
def SetTickSizes(self, h=None, m=None): if h: self.SetTickSize(h, HOUR) if m: self.SetTickSize(h, MINUTE)
self.SetTickFont(h, MINUTE)
self.SetTickFont(m, MINUTE)
def SetTickFontss(self, h=None, m=None): if h: self.SetTickFont(h, HOUR) if m: self.SetTickFont(h, MINUTE)
lrsizer.Add(self.mimelist, 1, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER, 4)
lrsizer.Add(self.mimelist, 1, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER | wx.FIXED_SIZE, 4)
def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1)
import PyCrust
from wx import py
def setUp(self): GetAttributeTestCase.setUp(self) import PyCrust spam = Spam() self.f = open('test_introspect.py') self.items = ( None, int(123), long(123), float(123), complex(123), "", unicode(""), [], (), xrange(0), {}, # Builtin function. len, # Builtin method. [].append, # User function. ham, # Byte-compiled code. ham.func_code, # Lambda. lambda: None, # Class with no init. Bar, # Instance with no init. Bar(), # Class with init and del. Foo, # Instance with init and del. Foo(), # Bound method. spam.foo, # Unbound method. Spam.eggs, # Callable instance. spam, # Module. introspect, # Package. PyCrust, # Buffer. buffer(''), # File. self.f, # Slice. slice(0), # Ellipsis. Ellipsis, # BrokenStr class. BrokenStr, # BrokenStr instance. brokenStr, )
PyCrust,
py,
def setUp(self): GetAttributeTestCase.setUp(self) import PyCrust spam = Spam() self.f = open('test_introspect.py') self.items = ( None, int(123), long(123), float(123), complex(123), "", unicode(""), [], (), xrange(0), {}, # Builtin function. len, # Builtin method. [].append, # User function. ham, # Byte-compiled code. ham.func_code, # Lambda. lambda: None, # Class with no init. Bar, # Instance with no init. Bar(), # Class with init and del. Foo, # Instance with init and del. Foo(), # Bound method. spam.foo, # Unbound method. Spam.eggs, # Callable instance. spam, # Module. introspect, # Package. PyCrust, # Buffer. buffer(''), # File. self.f, # Slice. slice(0), # Ellipsis. Ellipsis, # BrokenStr class. BrokenStr, # BrokenStr instance. brokenStr, )
def InsertLineControlPoint(self, dc = None): """Insert a control point at an arbitrary position."""
def InsertLineControlPoint(self, dc = None, point = None): """Insert a control point at an optional given position."""
def InsertLineControlPoint(self, dc = None): """Insert a control point at an arbitrary position.""" if dc: self.Erase(dc)
last_point = self._lineControlPoints[-1] second_last_point = self._lineControlPoints[-2] line_x = (last_point[0] + second_last_point[0]) / 2.0 line_y = (last_point[1] + second_last_point[1]) / 2.0
if point: line_x, line_y = point else: last_point = self._lineControlPoints[-1] second_last_point = self._lineControlPoints[-2] line_x = (last_point[0] + second_last_point[0]) / 2.0 line_y = (last_point[1] + second_last_point[1]) / 2.0
def InsertLineControlPoint(self, dc = None): """Insert a control point at an arbitrary position.""" if dc: self.Erase(dc)
print flags, col, self.tree.GetItemText(item, col)
self.log.write('Flags: %s, Col:%s, Text: %s' % (flags, col, self.tree.GetItemText(item, col)))
def OnRightUp(self, evt): pos = evt.GetPosition() item, flags, col = self.tree.HitTest(pos) if item: print flags, col, self.tree.GetItemText(item, col)
g.currentEncoding = dom.encoding
if dom.encoding: g.currentEncoding = dom.encoding
def Open(self, path): if not os.path.exists(path): wxLogError('File does not exists: %s' % path) return False # Try to read the file try: f = open(path) self.Clear() dom = minidom.parse(f) f.close() # Set encoding global variable g.currentEncoding = dom.encoding # Change dir dir = os.path.dirname(path) if dir: os.chdir(dir) tree.SetData(dom) self.dataFile = path self.SetTitle(progname + ': ' + os.path.basename(path)) except: # Nice exception printing inf = sys.exc_info() wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1]) wxLogError('Error reading file: %s' % path) return False return True
frame.res.Load(os.path.join(basePath, 'xrced.xrc'))
try: frame.res.Load(os.path.join(basePath, 'xrced.xrc')) except wx._core.PyAssertionError: pass
def OnInit(self): global debug # Process comand-line try: opts = args = None opts, args = getopt.getopt(sys.argv[1:], 'dhiv') for o,a in opts: if o == '-h': usage() sys.exit(0) elif o == '-d': debug = True elif o == '-v': print 'XRCed version', version sys.exit(0) except getopt.GetoptError: if wxPlatform != '__WXMAC__': # macs have some extra parameters print >> sys.stderr, 'Unknown option' usage() sys.exit(1)
cleanup = ogl.OGLCleanUp def __del__(self): self.cleanup()
def __del__(self, cleanup=ogl.OGLCleanUp): cleanup()
def runTest(frame, nb, log): # This creates some pens and brushes that the OGL library uses. # It should be called after the app object has been created, but # before OGL is used. ogl.OGLInitialize() win = TestWindow(nb, log, frame) return win
def __init__(self, name, expr, engine):
def __call__(self, econtext): expr = super(TALESProviderExpression, self).__call__(econtext)
def __init__(self, name, expr, engine): if not '/' in expr: raise KeyError('Use `iface/key` for defining the provider.')
raise KeyError("Do not use more then one / for defining iface/key.")
msg = "Do not use more then one '/' for defining iface/key." raise KeyError(msg)
def __init__(self, name, expr, engine): if not '/' in expr: raise KeyError('Use `iface/key` for defining the provider.')
def __call__(self, econtext):
def __call__(self, econtext): context = econtext.vars['context'] request = econtext.vars['request'] view = econtext.vars['view']
'Viewlet region interface not found.', str)
'Provider region interface not found.', str)
def getRegion(str): """Get a region from the string. This function will create the dummy region implementation as well. """ region = zope.component.queryUtility(interfaces.IRegion, name=str) if region is None: raise interfaces.ViewletRegionLookupError( 'Viewlet region interface not found.', str) return region
raise KeyError('Use `iface/viewletname` for defining the viewlet.')
raise KeyError('Use `iface/key` for defining the provider.')
def __init__(self, name, expr, engine): if not '/' in expr: raise KeyError('Use `iface/viewletname` for defining the viewlet.')
cpManager = zope.component.queryMultiAdapter( (context, request, view), interfaces.IContentProviderManager)
cpManager = None res = [] iface = interfaces.IContentProviderManager objs = (context, request, view) lookup = ISiteManager(context).adapters.lookup cpManagerClass = lookup(map(providedBy, objs)+[region], iface, name='') if cpManagerClass is not None: cpManager = cpManager(context, request, view, region)
def __call__(self, econtext): context = econtext.vars['context'] request = econtext.vars['request'] view = econtext.vars['view']
comp = new_compiler(compiler=compiler, verbose=True, output_dir='build')
print 'Creating library', libName comp = new_compiler(compiler=compiler, verbose=True)
def buildStaticLibrary(sourceFiles, libName, libDir, compiler): '''Build libraries to be linked to simuPOP modules''' # get a c compiler comp = new_compiler(compiler=compiler, verbose=True, output_dir='build') objFiles = comp.compile(sourceFiles, include_dirs=['.']) comp.create_static_lib(objFiles, libName, libDir)
res['libraries'] = boost_lib_names
res['libraries'] = [x for x in boost_lib_names]
def ModuInfo(modu, SIMUPOP_VER='9.9.9', SIMUPOP_REV='9999'): res = {} res['src'] = ['src/simuPOP_' + modu + '_wrap.cpp'] for src in SOURCE_FILES: res['src'].append(src[:-4] + '_' + modu + '.cpp') res['src'].extend(GSL_FILES) res['libraries'] = boost_lib_names # lib if os.name == 'nt': # Windows res['libraries'].append('zdll') else: res['libraries'].extend(['stdc++', 'z']) res['include_dirs'] = ['.', boost_inc_path] if use_vc: # I have a portable stdint.h for msvc res['include_dirs'].append('win32') # res['library_dirs'] = ['build', boost_lib_path] if os.name == 'nt': # msvc does not have O3 option res['extra_compile_args'] = ['/O2'] else: res['extra_compile_args'] = ['-O3', '-Wall'] # define_macros res['define_macros'] = MACROS[modu] res['define_macros'].extend([('SIMUPOP_VER', SIMUPOP_VER), ('SIMUPOP_REV', SIMUPOP_REV)]) if disable_compression: res['define_macros'].extend([('DISABLE_COMPRESSION', None)]) if os.name == 'nt': res['define_macros'].extend([('BOOST_ALL_NO_LIB', None)]) res['undef_macros'] = [] if 'mpi' in modu: res['include_dirs'].extend(MPIFlags['inc_dirs']) res['library_dirs'].extend(MPIFlags['lib_dirs']) res['libraries'].extend(MPIFlags['libs']) res['define_macros'].extend(MPIFlags['def_macros']) res['undef_macros'].extend(MPIFlags['undef_macros']) return res
r.postscript(file=epsFile) r.par(mfrow=[2,1])
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' r.postscript(file=epsFile) r.par(mfrow=[2,1]) # return max LD res = [] # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % pop.dvars().ctrChrom, xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2, pop.dvars().noDSLChrom), xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % pop.dvars().ctrChrom, xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL'])
if hasRPy: r.postscript(file=epsFile) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % pop.dvars().ctrChrom, xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL'])
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' r.postscript(file=epsFile) r.par(mfrow=[2,1]) # return max LD res = [] # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % pop.dvars().ctrChrom, xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2, pop.dvars().noDSLChrom), xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2, pop.dvars().noDSLChrom), xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off()
if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2, pop.dvars().noDSLChrom), xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off()
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' r.postscript(file=epsFile) r.par(mfrow=[2,1]) # return max LD res = [] # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % pop.dvars().ctrChrom, xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) res.append(max(ldprime)) r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2, pop.dvars().noDSLChrom), xlab="marker location", ylab="D'", type='b') r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail