rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
homedir = os.getenv("APPDATA").replace("\\", "/") if not os.path.exists(homedir):
|
if os.getenv("APPDATA") != "": homedir = os.getenv("APPDATA").replace("\\", "/") else:
|
def main(): # Some globals and variables global config global homedir config = {} options = [ "--config", "--configdump", "--daemon", "--debug", "--verbose", "--version" ] shortoptions = { "c":"--config", "d":"--debug", "D":"--daemon", "v":"--verbose", "V":"--version" } overwrite = [ "--daemon", "--debug", "--verbose" ] # Scan for commandline options. This is like the handling # of Gentoo's (http://www.gentoo.org) "emerge". # Thanks vor this inspiration guys! tmpcmd = sys.argv[1:] cmd = [] opts = [] for x in tmpcmd: if x[0:1] == "-" and x[1:2] != "-": for y in x[1:]: if shortoptions.has_key(y): if shortoptions[y] in cmd: print "*** Warning: Redundant use of "+shortoptions[y] else: cmd.append(shortoptions[y]) else: print "!!! Error: -"+y+" is an invalid option." sys.exit(1) else: cmd.append(x) for x in cmd: if len(x) >= 2 and x[0:2] != "--": opts.append(x) elif len(x) >= 2 and x[0:2] == "--": opts.append(x) elif x not in options: print "!!! Error: "+x+" is an invalid option." sys.exit(1) # Some error handling if "--daemon" in opts and "--nodaemon" in opts: print "!!! Error: You can not use --daemon and --nodaemon at the same time" sys.exit(1) # "One option, one output and die" (tm) if "--help" in opts: print "I guess you need help. That's bad at the moment! ;)" sys.exit() elif "--version" in opts: # Some easy release-checkin' headinfo = string.split(__headurl__, "/") if "tags" in headinfo: print "Stable release: "+headinfo[headinfo.index("tags")+1] else: print "This is a development version. Expect bugs!" print __revision__ sys.exit() # Get the users application data directory from environment variables and "~/" # Try windows path first, as windows has a special application data directory # The last fallback is to use the current working directory homedir = os.getenv("APPDATA").replace("\\", "/") if not os.path.exists(homedir): homedir = os.path.expanduser("~") if not os.path.exists(homedir): homedir = os.getenv("HOME") if not os.path.exists(homedir): homedir = os.getcwd() # Get the systems global settings directory # Try both /etc and the windows "all users" diretory if os.path.isdir("/etc/"): etcdir = "/etc" elif os.getenv("ALLUSERSPROFILE") != "": etcdir = os.getenv("ALLUSERSPROFILE").replace("\\", "/") + os.getenv("APPDATA")[len(os.getenv("USERPROFILE")):].replace("\\", "/") else: etcdir = "" if "--config" in opts: if opts[opts.index("--config")+1][0:2] == "--": print "!!! Error: You specified --config but no file was appended!" sys.exit(1) config['config'] = opts[opts.index("--config")+1] else: if os.path.isfile(homedir+"/dirt.xml"): config['config'] = homedir+"/dirt.xml" elif os.path.isfile(etcdir+"/dirt.xml"): config['config'] = etcdir+"/dirt.xml" else: print "!!! Error: No configuration file found!" sys.exit(1) configuration = xml.dom.minidom.parse(config['config']) # Validate XML # TODO general_config = configuration.getElementsByTagName('general') for node in general_config: for general in node.childNodes: if general.nodeType == Node.ELEMENT_NODE: setname = general.nodeName for set in general.childNodes: # TODO: We really have to find a nice way to check for bool's. # This is ugly. if string.lower(set.data) == "true": config[setname] = True elif string.lower(set.data) == "false": config[setname] = False else: config[setname] = set.data for set in opts: if set in overwrite: config[set[2:]] = True if "--configdump" in opts: pprint.pprint(config) sys.exit()
|
self.increase = 0.05
|
self.increase = 0.005
|
def __init__(self):
|
self.percent += self.increase * self.run
|
def getData(self):
|
|
if not Cmp.compare(a,b): log("xxxxxxxxxxxxxxxxxxxxxxxxxxx") log(o.description + " and " + s.description + "differ.") log("o="+str(a)) log("s="+str(b)) log("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
|
def __call__(self):
|
|
Utils.writeXmlToFile(result,"log/"+method[:-2]+".xml")
|
Utils.writeXmlToFile(result,"log/"+method[:-2]+".run"+str(grinder.runNumber)+".thread"+str(grinder.threadID)+".xml")
|
def doIt(self,method):
|
def __init__(self): self.percent = 0.05 self.increase = 0.05 self.run = 0 self.omero = None self.shoola = None def getData(self): self.percent += self.increase * self.run self.run += 1 data = Data(self.percent) data.setDataSource(ds) data.init() log(str(data)) print(str(self.percent)) return data
|
def grok(method): result=eval(method) log(str(result)) sz = Utils.structureSize(result) grinder.statistics.setValue(szIndex, sz) grinder.statistics.setSuccess(1)
|
|
grinder.statistics.delayReports = 1
|
data = self.getData() _omero = Omero(data).init() _omero.setData(data) _shoola = Shoola(data) grinder.statistics.delayReports = 1
|
def __call__(self):
|
proxy = o.wrap(grok) proxy( o.description ) proxy = s.wrap(grok) proxy( p.description )
|
self.omero = o.wrap(_omero) self.doIt ( o.description )
|
def __call__(self):
|
v = cimarron.skin.VBox(parent=self.window) h1 = cimarron.skin.HBox(parent=v) h2 = cimarron.skin.HBox(parent=v)
|
v = cimarron.skin.VBox(parent=self.window, expand=True, fill=True) h1 = cimarron.skin.HBox(parent=v, expand=False, fill=True) h2 = cimarron.skin.HBox(parent=v, expand=False, fill=False)
|
def __init__(self, **kw): super(ReceiptWindow, self).__init__(**kw) self.window.title = "Receipt Generation" self.trans = Transaction() self.target=Receipt(date=today()) self.trans.track(self.target)
|
actionContainer = cimarron.skin.HBox(parent=v)
|
actionContainer = cimarron.skin.HBox(parent=v, expand=False, fill=False)
|
def __init__(self, **kw): super(ReceiptWindow, self).__init__(**kw) self.window.title = "Receipt Generation" self.trans = Transaction() self.target=Receipt(date=today()) self.trans.track(self.target)
|
contents+= ["width=%d" % int (size), "precision=%d" % int(prec)]
|
contents+= ["scale=%d" % int (size), "precision=%d" % int(prec)]
|
def field (self, field): fieldName= self.__fieldName__ (field.name) contents= ["'%s'" % fieldName] try: try: relation= field.get_reference () type= 'RToOne' contents+= ["'%s'" % self.__tableName__ (relation.name)] if field.inverse: # contents+= ["inverse='%s'" % self.__pluralFieldName__ (field.inverse)] contents+= ["inverse='%s'" % self.__fieldName__ (field.inverse)] if field.deleteRule: contents+= ["deleteRule='%s'" % field.deleteRule.upper ()] if field.joinSemantic: if field.joinSemantic=='full': js= 0 elif field.joinSemantic=='outer': js= 1 elif field.joinSemantic=='left': js= 2 elif field.joinSemantic=='right': js= 3 contents+= ["joinSemantic=%d" % js]
|
if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text)
|
if not self.resetInput: if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text) self.display.text = str(self.X) self.resetInput = True
|
def operate(self, sender=None): if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text) self.op = sender.label self.display.text = str(self.X) self.resetInput = True
|
self.display.text = str(self.X) self.resetInput = True
|
def operate(self, sender=None): if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text) self.op = sender.label self.display.text = str(self.X) self.resetInput = True
|
|
f = NamedTemporaryFile()
|
f = NamedTemporaryFile(suffix='.png')
|
def testWindowCanScreenshot(self): from tempfile import NamedTemporaryFile import Image import time f = NamedTemporaryFile() self.win.show() while gtk.events_pending(): gtk.main_iteration() time.sleep(1) while gtk.events_pending(): gtk.main_iteration() self.win.screenshot(f.name) i = Image.open(f.name) self.assertEqual(i.format, 'PNG')
|
self.nameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="name", onAction=self.checkValues) self.surnameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="surname", onAction=self.checkValues)
|
self.widgets = \ (cimarron.skin.Entry(parent=vbox, attribute="name", onAction=self.checkValues), cimarron.skin.Entry(parent=vbox, attribute="surname", onAction=self.checkValues))
|
def __init__(self, target=None, **kw): super(PersonEditor, self).__init__(**kw) self.win.title = 'Person Editor' outer_vbox = cimarron.skin.VBox(parent=self.win) hbox = cimarron.skin.HBox(parent=outer_vbox) vbox = cimarron.skin.VBox(parent=hbox) cimarron.skin.Label(parent=vbox, text='Name:') cimarron.skin.Label(parent=vbox, text='Surname:') vbox = cimarron.skin.VBox(parent=hbox) self.nameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="name", onAction=self.checkValues) self.surnameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="surname", onAction=self.checkValues) cimarron.skin.Button(parent=outer_vbox, label='Check', onAction = self.checkValues) self.label = cimarron.skin.Label(parent=outer_vbox, text="<nothing yet>") if target is not None: self.newTarget(target)
|
self.label = cimarron.skin.Label(parent=outer_vbox, text="<nothing yet>")
|
self.label = cimarron.skin.Label(parent=outer_vbox, text="")
|
def __init__(self, target=None, **kw): super(PersonEditor, self).__init__(**kw) self.win.title = 'Person Editor' outer_vbox = cimarron.skin.VBox(parent=self.win) hbox = cimarron.skin.HBox(parent=outer_vbox) vbox = cimarron.skin.VBox(parent=hbox) cimarron.skin.Label(parent=vbox, text='Name:') cimarron.skin.Label(parent=vbox, text='Surname:') vbox = cimarron.skin.VBox(parent=hbox) self.nameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="name", onAction=self.checkValues) self.surnameWidget = \ cimarron.skin.Entry(parent=vbox, attribute="surname", onAction=self.checkValues) cimarron.skin.Button(parent=outer_vbox, label='Check', onAction = self.checkValues) self.label = cimarron.skin.Label(parent=outer_vbox, text="<nothing yet>") if target is not None: self.newTarget(target)
|
def newTarget(self, *a, **kw): super(PersonEditor, self).newTarget(*a, **kw) self.nameWidget.newTarget(self.target) self.surnameWidget.newTarget(self.target) def refresh(self): self.nameWidget.refresh() self.surnameWidget.refresh()
|
def newTarget(self, target): super(PersonEditor, self).newTarget(target) for w in self.widgets: w.newTarget(self.value)
|
def newTarget(self, *a, **kw): super(PersonEditor, self).newTarget(*a, **kw) self.nameWidget.newTarget(self.target) self.surnameWidget.newTarget(self.target)
|
def __init__(self, columns=None, cls=None, **kwargs):
|
def __init__(self, columns=None, cls=None, onAppend=None, **kwargs):
|
def __init__(self, columns=None, cls=None, **kwargs): """ @param columns: a list of B{Column}s that describe what to show in the grid, how obtain it from the objects, and eventually how to save data back to.
|
value = self.value if value is not None and int(path)<len(value): value = value[int(path)]
|
if self.value is not None and int(path)<len(self.value): value = self.value[int(path)]
|
def _cell_edited(self, cell, path, newVal, colNo, *ignore): """ A cell has been edited: keep the models in sync. """ logger.debug(`cell`+','+`path`+','+`newVal`) attribute = self.columns[colNo].attribute # modify the ListStore model... self._tvdata[path][colNo] = newVal # ... and our model value = self.value if value is not None and int(path)<len(value): value = value[int(path)] else: # we're editing the empty row, so go build an object # to give back up that row. value = self.cls() if self.value is not None: self.value.append(value) else: self.value = [value] value.setattr(attribute, newVal) return False
|
value = self.cls()
|
kwargs = dict([(column.attribute, self._tvdata[path][index]) for index, column in enumerate(self.columns)]) logger.debug(kwargs) value = self.cls(**kwargs)
|
def _cell_edited(self, cell, path, newVal, colNo, *ignore): """ A cell has been edited: keep the models in sync. """ logger.debug(`cell`+','+`path`+','+`newVal`) attribute = self.columns[colNo].attribute # modify the ListStore model... self._tvdata[path][colNo] = newVal # ... and our model value = self.value if value is not None and int(path)<len(value): value = value[int(path)] else: # we're editing the empty row, so go build an object # to give back up that row. value = self.cls() if self.value is not None: self.value.append(value) else: self.value = [value] value.setattr(attribute, newVal) return False
|
self.value = [] valueLen = len(self.value)
|
valueLen = 0 else: valueLen = len(self.value)
|
def _keyreleased(self, widget, key_event, *ignore): """ A key has been released: the user might be wanting to insert a row... """ # bugs will come to haunt you at night if you delete this # and don't fix the socking but that is elsewhere # (I whish at least where does he hide, the little frak) if self.value is None: self.value = [] # conditions that assert we're in the fscking last row of data. valueLen = len(self.value) last = self.value is None \ or valueLen == 0 \ or self.index == valueLen-1 # print self.index, `self.value`, last if key_event.keyval == gtk.keysyms.Down and last and \ self.cls is not None and self._tvdatalen == valueLen: # right conditions; insert a new row in the TreeView # without changing the value yet. self._tvdata.append(['' for j in self.columns]) self._tvdatalen += 1 self.index = valueLen # print 'making new', self.index # print self._tv.get_cursor() return False
|
logger.debug("%r %r %r", self.index, self.value, last)
|
def _keyreleased(self, widget, key_event, *ignore): """ A key has been released: the user might be wanting to insert a row... """ # bugs will come to haunt you at night if you delete this # and don't fix the socking but that is elsewhere # (I whish at least where does he hide, the little frak) if self.value is None: self.value = [] # conditions that assert we're in the fscking last row of data. valueLen = len(self.value) last = self.value is None \ or valueLen == 0 \ or self.index == valueLen-1 # print self.index, `self.value`, last if key_event.keyval == gtk.keysyms.Down and last and \ self.cls is not None and self._tvdatalen == valueLen: # right conditions; insert a new row in the TreeView # without changing the value yet. self._tvdata.append(['' for j in self.columns]) self._tvdatalen += 1 self.index = valueLen # print 'making new', self.index # print self._tv.get_cursor() return False
|
|
logger.debug('making new %r', self.index)
|
def _keyreleased(self, widget, key_event, *ignore): """ A key has been released: the user might be wanting to insert a row... """ # bugs will come to haunt you at night if you delete this # and don't fix the socking but that is elsewhere # (I whish at least where does he hide, the little frak) if self.value is None: self.value = [] # conditions that assert we're in the fscking last row of data. valueLen = len(self.value) last = self.value is None \ or valueLen == 0 \ or self.index == valueLen-1 # print self.index, `self.value`, last if key_event.keyval == gtk.keysyms.Down and last and \ self.cls is not None and self._tvdatalen == valueLen: # right conditions; insert a new row in the TreeView # without changing the value yet. self._tvdata.append(['' for j in self.columns]) self._tvdatalen += 1 self.index = valueLen # print 'making new', self.index # print self._tv.get_cursor() return False
|
|
logger.debug(`self._tv.get_cursor()`)
|
def _keyreleased(self, widget, key_event, *ignore): """ A key has been released: the user might be wanting to insert a row... """ # bugs will come to haunt you at night if you delete this # and don't fix the socking but that is elsewhere # (I whish at least where does he hide, the little frak) if self.value is None: self.value = [] # conditions that assert we're in the fscking last row of data. valueLen = len(self.value) last = self.value is None \ or valueLen == 0 \ or self.index == valueLen-1 # print self.index, `self.value`, last if key_event.keyval == gtk.keysyms.Down and last and \ self.cls is not None and self._tvdatalen == valueLen: # right conditions; insert a new row in the TreeView # without changing the value yet. self._tvdata.append(['' for j in self.columns]) self._tvdatalen += 1 self.index = valueLen # print 'making new', self.index # print self._tv.get_cursor() return False
|
|
theReceipt = Receipt() self.target = theReceipt self.trans.track(theReceipt)
|
self.target=Receipt(date=today()) self.trans.track(self.target)
|
def __init__(self, **kw): super(ReceiptWindow, self).__init__(**kw) self.win.title = "Receipt Generation" self.trans = Transaction() #self.commitValue(Receipt()) theReceipt = Receipt() self.target = theReceipt #self.target = Receipt() #self.trans.track(self.value) self.trans.track(theReceipt)
|
self.target = None self.refresh()
|
self.newTarget(Receipt(date=today())) self.trans.track(self.target)
|
def discard(self, *ignore): self.trans.discard() self.target = None self.refresh()
|
fromXmlObj(xmlObj, parent=obj)
|
if xmlObj.get_type ()!='text': fromXmlObj(xmlObj, parent=obj)
|
def fromXmlObj(xmlObj, parent=None): """ Helper function for loading a Cimarrón app from an xml file. (see L{fromXml}). """ if isinstance(xmlObj, libxml2.xmlDoc): # get at root element xmlObj = xmlObj.children obj = getattr(skin, xmlObj.name)() prop = xmlObj.properties while prop: setattr(obj, prop.name, eval(prop.content)) prop = prop.next if parent is not None: obj.parent = parent xmlObj = xmlObj.children while xmlObj: fromXmlObj(xmlObj, parent=obj) xmlObj = xmlObj.next return obj
|
qual = re.compile('==.*\"([^\"]*)\"').search(qual).group(1)
|
result = re.compile('==.*\"([^\"]*)\"').search(qual) if result: qual = result.group(1)
|
def search(cls, ignoreClass, qualifier): # '' or 'name == "thing"' qual = repr(qualifier) if qual!='': # *HACKY* *WHACKY* qual = re.compile('==.*\"([^\"]*)\"').search(qual).group(1) return [docType for docType in cls.__values__ if qual.upper() in docType['name'].upper()]
|
self.thirdLabel.text = self.docType.value['other'].__name__ self.otherParty.cls = self.docType.value['other'] self.otherParty.enable()
|
if self.docType.value['other']: self.thirdLabel.text = self.docType.value['other'].__name__ self.otherParty.cls = self.docType.value['other'] self.otherParty.enable() else: self.thirdLabel.text = "Documento interno"
|
def setThirdLabel(self, *ignore): if self.docType.value: self.thirdLabel.text = self.docType.value['other'].__name__ self.otherParty.cls = self.docType.value['other'] self.otherParty.enable()
|
def __init__(self, columns=None, transaction=None, searcher=None, **kwargs):
|
def __init__(self, columns=None, cls=None, searcher=None, **kwargs):
|
def __init__(self, columns=None, transaction=None, searcher=None, **kwargs): """ @param columns: A list of Columns. Only the C{read} attribute needs to be set.
|
@param transaction: A transaction that will be used to search the values().
|
@param cls: The class that we'll want to look for with C{searcher}.
|
def __init__(self, columns=None, transaction=None, searcher=None, **kwargs): """ @param columns: A list of Columns. Only the C{read} attribute needs to be set.
|
self.trans = transaction
|
self.cls = cls
|
def __init__(self, columns=None, transaction=None, searcher=None, **kwargs): """ @param columns: A list of Columns. Only the C{read} attribute needs to be set.
|
self.value = self.searcher.values(self.trans, **data)
|
self.value = self.searcher.search(self.cls, **data)
|
def doSearch(self, *ignore): """ Performs the abstract search. The result ends up in aSearch.value as a list and returns the length of the list. """ data = {} for i in xrange(len(self.columns)): e = self.entries[i] c = self.columns[i] if e.value != '': # '' means `don't filter by me' data[c.attribute] = e.value
|
print code
|
code= """def %(methodName)s (self, control, *ignore): print control.value self.value.%(methodName)s(control.value)"""
|
|
print dir(CountryEditor)
|
def __init__(self, *a, **kw): print dir(CountryEditor) return super(CountryEditor, self).__init__(*a, **kw)
|
|
self.widget.newModel (Country)
|
self.widget.newModel (self.widget, Country)
|
def testNew (self): self.widget.newModel (Country) self.assert_ (isinstance (self.widget.value, Country))
|
def values(cls, trans, **qual): ans = trans.search(cls, **qual) return ans values = classmethod(values)
|
def setattr(self, attr, value): """ Find the attribute referred to by 'attr', and set it to 'value'. """ pos = attr.rfind('.') if pos > -1: path = attr[:pos] attr = attr[pos+1:] obj = traverse(self, path) else: obj = self return setattr(obj, attr, value)
|
|
def save(self, ignore):
|
def save(self, *ignore):
|
def save(self, ignore): self.trans.save()
|
def discard(self, ignore):
|
def discard(self, *ignore):
|
def discard(self, ignore): self.trans.discard() self.stockEditor.refresh()
|
print 'total amount ', self.amount super(Invoice, self).addToDetails(detail) print 'here', addToDetails
|
def addToDetails(self, detail): self.amount += detail.amount print 'total amount ', self.amount super(Invoice, self).addToDetails(detail)
|
|
print 'total amount ', self.amount super(Invoice, self).removeFromDetails(detail)
|
def removeFromDetails(self, detail): self.amount -= detail.amount print 'total amount ', self.amount super(Invoice, self).removeFromDetails(detail)
|
|
def _schedule(timeout, callback, repeat=False): def cb(): gobject.timeout_add(timeout, callback) if repeat: cb() cb()
|
def _schedule(timeout, callback, repeat=0): if repeat: def cb(): callback() gobject.timeout_add(timeout, cb) else: cb = callback gobject.timeout_add(timeout, cb)
|
def _schedule(timeout, callback, repeat=False): def cb(): gobject.timeout_add(timeout, callback) if repeat: cb() cb()
|
size, prec= numeric.group (1, 2)
|
prec, size= numeric.group (1, 2)
|
def field (self, field): fieldName= self.__fieldName__ (field.name) contents= ["'%s'" % fieldName] try: try: relation= field.get_reference () type= 'RToOne' contents+= ["'%s'" % self.__tableName__ (relation.name)] if field.inverse: # contents+= ["inverse='%s'" % self.__pluralFieldName__ (field.inverse)] contents+= ["inverse='%s'" % self.__fieldName__ (field.inverse)] if field.deleteRule: contents+= ["deleteRule='%s'" % field.deleteRule.upper ()] if field.joinSemantic: if field.joinSemantic=='full': js= 0 elif field.joinSemantic=='outer': js= 1 elif field.joinSemantic=='left': js= 2 elif field.joinSemantic=='right': js= 3 contents+= ["joinSemantic=%d" % js]
|
onAction= self.updateData,
|
onAction= self.selected,
|
def refresh (self): for i in xrange (len (self.data)): if len (self.labels)<=i: # the row does not exist, so we add it h= cimarron.skin.HBox (parent=self.widget) b= cimarron.skin.Label ( parent= h, text= ' ', row= i )
|
entry.onAction ()
|
self.updateData (entry)
|
def will_focus_out (self, entry, *ignore): entry.onAction ()
|
def concreteParenter (self, child): super (Notebook, self).concreteParenter (child)
|
def _concreteParenter (self, child): super (Notebook, self)._concreteParenter (child)
|
def concreteParenter (self, child): super (Notebook, self).concreteParenter (child) if getattr (child, '_widget', None): label= gtk.Label() label.set_text (child.label) self._widget.set_tab_label (child._widget, label)
|
for aRow in [[['7', self.numberButton], ['4', self.numberButton], ['1', self.numberButton], ['C', self.clear]], [['8', self.numberButton], ['5', self.numberButton], ['2', self.numberButton], ['0', self.numberButton]], [['9', self.numberButton], ['6', self.numberButton], ['3', self.numberButton], ['.', self.numberButton]], [['+', self.operate], ['-', self.operate], ['*', self.operate], ['/', self.operate]]]:
|
for aRow in ((('7', self.numberButton), ('4', self.numberButton), ('1', self.numberButton), ('C', self.clear)), (('8', self.numberButton), ('5', self.numberButton), ('2', self.numberButton), ('0', self.numberButton)), (('9', self.numberButton), ('6', self.numberButton), ('3', self.numberButton), ('.', self.numberButton)), (('+', self.operate), ('-', self.operate), ('*', self.operate), ('/', self.operate))):
|
def __init__(self, **kw): super(CalculatorController, self).__init__(**kw) self.win.title = 'Calculator' vbox = cimarron.skin.VBox(parent=self.win) self.display = cimarron.skin.Label(parent=vbox, text='0') hbox = cimarron.skin.HBox(parent=vbox) for aRow in [[['7', self.numberButton], ['4', self.numberButton], ['1', self.numberButton], ['C', self.clear]], [['8', self.numberButton], ['5', self.numberButton], ['2', self.numberButton], ['0', self.numberButton]], [['9', self.numberButton], ['6', self.numberButton], ['3', self.numberButton], ['.', self.numberButton]], [['+', self.operate], ['-', self.operate], ['*', self.operate], ['/', self.operate]]]: vbox = cimarron.skin.VBox(parent=hbox) for aLabel, anAction in aRow: cimarron.skin.Button(parent=vbox, label=aLabel, onAction=anAction) self.clear()
|
if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text) self.display.text = str(self.X) self.resetInput = True self.op = sender.label
|
val = float(self.display.text) if self.op is not None: val = self.op(self.X, val) self.display.text = str(val) self.resetInput = True self.X = val self.op = self.operations[sender.label]
|
def operate(self, sender=None): if not self.resetInput: if self.op == None: self.X = float(self.display.text) else: if self.op == '+': self.X = self.X + float(self.display.text) elif self.op == '-': self.X = self.X - float(self.display.text) elif self.op == '*': self.X = self.X * float(self.display.text) elif self.op == '/': self.X = self.X / float(self.display.text) self.display.text = str(self.X) self.resetInput = True self.op = sender.label
|
search= crud.newChild (None, 'Search', None)
|
search= crud.newChild (None, 'SearchEntry', None)
|
def export(self, xot, **opts): """return the xml document to create the screen represented by the xot""" self.xot= xot
|
search.setProp ('searcher', KindName)
|
search.setProp ('cls', KindName)
|
def export(self, xot, **opts): """return the xml document to create the screen represented by the xot""" self.xot= xot
|
for aRow in ((('7', self.numberButton), ('4', self.numberButton), ('1', self.numberButton), ('C', self.clear)), (('8', self.numberButton), ('5', self.numberButton), ('2', self.numberButton), ('0', self.numberButton)), (('9', self.numberButton), ('6', self.numberButton), ('3', self.numberButton), ('.', self.numberButton)), (('+', self.operate), ('-', self.operate), ('*', self.operate), ('/', self.operate))):
|
for aRow in (({'label': '7', 'onAction': self.numberButton}, {'label': '4', 'onAction': self.numberButton}, {'label': '1', 'onAction': self.numberButton}, {'label': 'C', 'onAction': self.clear}), ({'label': '8', 'onAction': self.numberButton}, {'label': '5', 'onAction': self.numberButton}, {'label': '2', 'onAction': self.numberButton}, {'label': '0', 'onAction': self.numberButton}), ({'label': '9', 'onAction': self.numberButton}, {'label': '6', 'onAction': self.numberButton}, {'label': '3', 'onAction': self.numberButton}, {'label': '.', 'onAction': self.numberButton}), ({'label': '+', 'onAction': self.operate, 'calcOp': operator.add}, {'label': '-', 'onAction': self.operate, 'calcOp': operator.sub}, {'label': '*', 'onAction': self.operate, 'calcOp': operator.mul}, {'label': '/', 'onAction': self.operate, 'calcOp': operator.div})):
|
def __init__(self, **kw): super(CalculatorController, self).__init__(**kw) self.win.title = 'Calculator' vbox = cimarron.skin.VBox(parent=self.win) self.display = cimarron.skin.Label(parent=vbox, text='0') hbox = cimarron.skin.HBox(parent=vbox) for aRow in ((('7', self.numberButton), ('4', self.numberButton), ('1', self.numberButton), ('C', self.clear)), (('8', self.numberButton), ('5', self.numberButton), ('2', self.numberButton), ('0', self.numberButton)), (('9', self.numberButton), ('6', self.numberButton), ('3', self.numberButton), ('.', self.numberButton)), (('+', self.operate), ('-', self.operate), ('*', self.operate), ('/', self.operate))): vbox = cimarron.skin.VBox(parent=hbox) for aLabel, anAction in aRow: cimarron.skin.Button(parent=vbox, label=aLabel, onAction=anAction) self.clear()
|
for aLabel, anAction in aRow: cimarron.skin.Button(parent=vbox, label=aLabel, onAction=anAction)
|
for parms in aRow: cimarron.skin.Button(parent=vbox, **parms)
|
def __init__(self, **kw): super(CalculatorController, self).__init__(**kw) self.win.title = 'Calculator' vbox = cimarron.skin.VBox(parent=self.win) self.display = cimarron.skin.Label(parent=vbox, text='0') hbox = cimarron.skin.HBox(parent=vbox) for aRow in ((('7', self.numberButton), ('4', self.numberButton), ('1', self.numberButton), ('C', self.clear)), (('8', self.numberButton), ('5', self.numberButton), ('2', self.numberButton), ('0', self.numberButton)), (('9', self.numberButton), ('6', self.numberButton), ('3', self.numberButton), ('.', self.numberButton)), (('+', self.operate), ('-', self.operate), ('*', self.operate), ('/', self.operate))): vbox = cimarron.skin.VBox(parent=hbox) for aLabel, anAction in aRow: cimarron.skin.Button(parent=vbox, label=aLabel, onAction=anAction) self.clear()
|
operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div }
|
def clear(self, sender=None): self.op = None self.display.text = '0' self.X = 0 self.resetInput = True
|
|
if not self.resetInput: val = float(self.display.text) if self.op is not None: val = self.op(self.X, val) self.display.text = str(val) self.resetInput = True self.X = val self.op = self.operations[sender.label]
|
try: if not self.resetInput: val = float(self.display.text) if self.op is not None: val = self.op(self.X, val) self.display.text = str(val) self.X = val self.resetInput = True self.op = sender.calcOp except: self.clear() self.display.text = '-- Error --'
|
def operate(self, sender=None): if not self.resetInput: val = float(self.display.text) if self.op is not None: val = self.op(self.X, val) self.display.text = str(val) self.resetInput = True self.X = val self.op = self.operations[sender.label]
|
Although currently a function, L{config} will probably become a class
|
Although currently a function, L{_config} will probably become a class
|
def _config(skin_name=DEFAULT_SKIN_NAME): """ Although currently a function, L{config} will probably become a class because we strongly suspect people will want to actually do some configuration loading here. In fact, one thing we learned while implementing the first Cimarrón is that a lot of functionality is actually too installation-dependant to I{not} keep it in a configuration file somewhere (an example of this is, of course, the default skin name). This Cimarrón is at this time much leaner than its previous incarnation, and thus the only work done by L{config} is the choosing of the appropriate skin (and loading thereof). Expect this to change as the L{Controller <fvl.cimarron.controllers.Controller>}s and L{Widget <fvl.cimarron.skins.common.Widget>}s are filled out. @param skin_name: the name of the skin to load @type skin_name: str """ global skin logger.debug('importing skin') skin = __import__('fvl.cimarron.skins.' + skin_name, globals(), locals(), skin_name) logger.debug('verifying skin meets ISkin interface:') verifyObject(ISkin, skin) logger.debug(' + %s provides ISkin', skin.__name__) for name, desc in ISkin.namesAndDescriptions(1): if isinstance(desc, Object): verifyClass(desc.schema, getattr(skin, name)) logger.debug(' + %s provides %s', name, desc.schema.__name__) logger.debug('enabling "from fvl.cimarron.skin import Foo"') sys.modules['fvl.cimarron.skin'] = skin
|
and thus the only work done by L{config} is the choosing of the
|
and thus the only work done by L{_config} is the choosing of the
|
def _config(skin_name=DEFAULT_SKIN_NAME): """ Although currently a function, L{config} will probably become a class because we strongly suspect people will want to actually do some configuration loading here. In fact, one thing we learned while implementing the first Cimarrón is that a lot of functionality is actually too installation-dependant to I{not} keep it in a configuration file somewhere (an example of this is, of course, the default skin name). This Cimarrón is at this time much leaner than its previous incarnation, and thus the only work done by L{config} is the choosing of the appropriate skin (and loading thereof). Expect this to change as the L{Controller <fvl.cimarron.controllers.Controller>}s and L{Widget <fvl.cimarron.skins.common.Widget>}s are filled out. @param skin_name: the name of the skin to load @type skin_name: str """ global skin logger.debug('importing skin') skin = __import__('fvl.cimarron.skins.' + skin_name, globals(), locals(), skin_name) logger.debug('verifying skin meets ISkin interface:') verifyObject(ISkin, skin) logger.debug(' + %s provides ISkin', skin.__name__) for name, desc in ISkin.namesAndDescriptions(1): if isinstance(desc, Object): verifyClass(desc.schema, getattr(skin, name)) logger.debug(' + %s provides %s', name, desc.schema.__name__) logger.debug('enabling "from fvl.cimarron.skin import Foo"') sys.modules['fvl.cimarron.skin'] = skin
|
class skin_module(new.module): def __repr__(self): return '<skin lazymodule %r>' % self.__name__ def __init__(self, *a, **kw): super(skin_module, self).__init__(*a, **kw)
|
class _lazy_skin_module(new.module): """ An instance of _lazy_skin_module stands in for the real skin module, and becomes a Borg of the real skin as soon as an unknown attribute is requested (i.e., as soon as __getattr__ is called). """
|
def _config(skin_name=DEFAULT_SKIN_NAME): """ Although currently a function, L{config} will probably become a class because we strongly suspect people will want to actually do some configuration loading here. In fact, one thing we learned while implementing the first Cimarrón is that a lot of functionality is actually too installation-dependant to I{not} keep it in a configuration file somewhere (an example of this is, of course, the default skin name). This Cimarrón is at this time much leaner than its previous incarnation, and thus the only work done by L{config} is the choosing of the appropriate skin (and loading thereof). Expect this to change as the L{Controller <fvl.cimarron.controllers.Controller>}s and L{Widget <fvl.cimarron.skins.common.Widget>}s are filled out. @param skin_name: the name of the skin to load @type skin_name: str """ global skin logger.debug('importing skin') skin = __import__('fvl.cimarron.skins.' + skin_name, globals(), locals(), skin_name) logger.debug('verifying skin meets ISkin interface:') verifyObject(ISkin, skin) logger.debug(' + %s provides ISkin', skin.__name__) for name, desc in ISkin.namesAndDescriptions(1): if isinstance(desc, Object): verifyClass(desc.schema, getattr(skin, name)) logger.debug(' + %s provides %s', name, desc.schema.__name__) logger.debug('enabling "from fvl.cimarron.skin import Foo"') sys.modules['fvl.cimarron.skin'] = skin
|
for k in self.__dict__: if k not in skin.__dict__: del self.__dict__[k] for k, v in skin.__dict__.items(): self.__dict__[k] = v
|
self.__dict__.clear() self.__dict__.update(skin.__dict__)
|
def __getattr__(self, attr): # are we a hack, or what? _config() for k in self.__dict__: if k not in skin.__dict__: del self.__dict__[k] for k, v in skin.__dict__.items(): self.__dict__[k] = v return getattr(skin, attr)
|
skin = skin_module('fvl.cimarron.skin')
|
skin = _lazy_skin_module('<lazy>')
|
def __getattr__(self, attr): # are we a hack, or what? _config() for k in self.__dict__: if k not in skin.__dict__: del self.__dict__[k] for k, v in skin.__dict__.items(): self.__dict__[k] = v return getattr(skin, attr)
|
print skin
|
def __getattr__(self, attr): # are we a hack, or what? _config() for k in self.__dict__: if k not in skin.__dict__: del self.__dict__[k] for k, v in skin.__dict__.items(): self.__dict__[k] = v return getattr(skin, attr)
|
|
logger.debug ('searching %r, %r', self.searcher, qual)
|
logger.debug ('searching %r, %r', self.cls, qual)
|
def doSearch(self, *ignore): """ Performs the abstract search. The result ends up in aSearch.value as a list and returns the length of the list. """ self.window.disable() try: qual = None for i in xrange(len(self.columns)): e = self.entries[i] if e.value != '' and e.value is not None: value = e.value c = self.columns[i] logger.debug ('%s op %r' % (c.attribute, c.operator)) if c.operator == Qualifier.like: value += '*' if qual is None: qual = c.operator(getattr(Qualifier(), c.attribute), value) else: qual = qual & c.operator(getattr(Qualifier(), c.attribute), value)
|
L{Control} is...
|
L{Control} is a Widget that can be interacted with. L{Control}s have an action, that is a callback that is called when a L{Control}-specific event happens. For example, L{Button<gtk2.Button>}s fire the action when you press or click them, whereas L{Entry<gtk2.Entry>}s do so when they have focus and enter is pressed, or they lose focus.
|
def skeleton(self, parent=None): skel = super(Container, self).skeleton(parent) for child in self.children: child.skeleton(skel) return skel
|
self.target = dict(foo=1, bar=2, baz=3)
|
def setUp (self): self.target = dict(foo=1, bar=2, baz=3)
|
|
self.widget= FooController (parent=self.win, target=self.target) self.value= 'quux:5' self.attribute= None
|
self.widget= FooController (parent=self.win) self.setUpControl (dict(foo=1, bar=2, baz=3), None)
|
def setUp (self): self.target = dict(foo=1, bar=2, baz=3)
|
self.widget.target = dict(quux='-13')
|
self.widget.newTarget (dict(quux='-13'))
|
def testSetValue(self): """ This assumes that setting the value re-fires refresh() """ self.widget.entry.value = 'quux' self.widget.target = dict(quux='-13') self.assertEqual(self.widget.label.text, '-13')
|
self.widget.target= self.target= Person ( "Freeman", "Newman",
|
person= Person ("Freeman", "Newman",
|
def setUp (self): super (TestCRUDController, self).setUp () self.widget= CRUDController.fromXmlFile ('test/testCrud.xml') self.widget.parent= self.parent= self.app self.widget.target= self.target= Person ( "Freeman", "Newman", [Address (text="San luis 870"), Address (text="San luis 594 2D")] ) self.attribute= 'name' self.value= 'Freeman'
|
self.attribute= 'name' self.value= 'Freeman'
|
self.setUpControl (target= person)
|
def setUp (self): super (TestCRUDController, self).setUp () self.widget= CRUDController.fromXmlFile ('test/testCrud.xml') self.widget.parent= self.parent= self.app self.widget.target= self.target= Person ( "Freeman", "Newman", [Address (text="San luis 870"), Address (text="San luis 594 2D")] ) self.attribute= 'name' self.value= 'Freeman'
|
self.widget.target= self.target
|
def testRefresh (self): self.widget.target= self.target self.assertEqual (self.widget.editors[0].target, self.target) self.assertEqual (self.widget.editors[1].target, self.target.getAddresses ())
|
|
self._innerWidget = self.note._outerWidget
|
def __init__ (self, cls=None, searchColumns=None, editorClass=None, filename=None, store=None, **kwargs): from fvl.cimarron.skin import Notebook, VBox, Button
|
|
"S simple query interface."
|
"A simple query interface."
|
def search(query, operator='and'): """Execute a search given by 'query' as a list/tuple of filter ids. 'operator' can be 'and' or 'or' to search for matches in all or any filter.
|
import re
|
def _text2list(text): # Helper: splitter input may be a string or a list of strings try: text + u"" except: return text else: return [text]
|
|
docu = re.compile(r' *<h2> (Documentation |Inheritance:)</h2>') public = re.compile(r'<DT><h3>Public')
|
docu = re.compile(r' *<h2> (Documentation|Inheritance) </h2>') public = re.compile(r'<DL>\s*?<DT><B><BR>Public')
|
headingTypedef = re.compile(r'typedef')
|
r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'</th></tr>\n</table>\n'
|
r'<th align=right ><a href="index.html">' + vigraLogo + \ r'</a></th></tr>\n</table>\n'
|
headingTypedef = re.compile(r'typedef')
|
r'<IMG BORDER=0 SRC="documents/pfeilGross.gif"></A>\n' \ r'</th>\n<th width=100%><font size="+2">' docuReplacement = r'<table bgcolor=" r'<th align=left ><font size=+2> \1 </font></th>\n' \ r'<tr>\n</table>' publicReplacement = r'</DL></DL>\n' \ r'<table bgcolor=" r'<th align=left ><font size=+2> Members </font></th>\n' \ r'<tr>\n</table>\n' \ r'<DL><DL>\n<DT><h3>Public'
|
r'<IMG BORDER=0 ALT="details" SRC="documents/pfeilGross.gif"></A>\n' \ r'</th>\n<th width="100%"><font size="+2">' docuReplacement = r'<table bgcolor=" r'<th align=left ><font size="+2"> \1 </font></th>\n' \ r'</tr>\n</table>' publicReplacement = r'<table bgcolor=" r'<th align=left ><font size="+2"> Member Index </font></th>\n' \ r'</tr>\n</table>\n' \ r'<DL>\n<DT><B><BR>Public'
|
headingTypedef = re.compile(r'typedef')
|
text = arrow.sub(r'<IMG BORDER=0 SRC="documents/pfeil.gif"></A>', text) text = bullet.sub(r'<IMG BORDER=0 SRC="documents/bullet.gif">', text)
|
text = arrow.sub(r'<IMG BORDER=0 ALT="+" SRC="documents/pfeil.gif"></A>', text) text = bullet.sub(r'<IMG BORDER=0 ALT="-" SRC="documents/bullet.gif">', text)
|
def convertBody(text): text = body.sub(bodyReplacement, text, 1) text = callOperator.sub(r'operator()', text) text = tag.sub(r'<\1>', text) text = atag.sub(r'<a name="\1">', text) text = umlaut.sub(r'&\1;', text) text = squared.sub(r'²', text) text = cube.sub(r'³', text) text = footer.sub(r'', text, 1) text = stlLink.sub(r'http://www.sgi.com/Technology/STL', text) text = ruler.sub(r'<br>', text) text = docu.sub(docuReplacement, text) text = public.sub(publicReplacement, text, 1) text = arrow.sub(r'<IMG BORDER=0 SRC="documents/pfeil.gif"></A>', text) text = bullet.sub(r'<IMG BORDER=0 SRC="documents/bullet.gif">', text) text = bullet2.sub('', text) text = links.sub(r'<p align=center>\n' + linkReplacement, text) text = fixDocBaselinkBug(text) return text
|
r'<table bgcolor=" r'<th align=left width=100%><font size=+3>Table of Contents</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>',
|
r'<table bgcolor=" r'<th align=left width="100%"><font size="+3">Table of Contents</font></th>\n' \ r'<th align=right ><a href="index.html">' + vigraLogo + \ r'</a><tr>\n</table>',
|
def convertAIndex(text): text = re.sub(r'<H2>Variables</H2>', r'<H2>typedefs</H2>', text) text = re.sub(r'<H1>Table of contents</H1>', r'<table bgcolor="#e0d090" width=100% cellpadding=5>\n<tr>\n' \ r'<th align=left width=100%><font size=+3>Table of Contents</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>', text) text = re.sub(r'<H2>(.*?)</H2>', docuReplacement, text) return text
|
r'<table bgcolor=" r'<th align=left width=100%><font size=+3>\1</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>',
|
r'<table bgcolor=" r'<th align=left width="100%"><font size="+3">\1</font></th>\n' \ r'<th align=right ><a href="index.html">' + vigraLogo + \ r'</a><tr>\n</table>',
|
def convertHIER(text): text = re.sub(r'<H1>(.*?)</H1>', r'<table bgcolor="#e0d090" width=100% cellpadding=5>\n<tr>\n' \ r'<th align=left width=100%><font size=+3>\1</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>', text) return text
|
text = heading.sub( r'<table cellpadding=5 bgcolor=" r'</font></th>\n' + r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra3.gif"></a>' + r'</th></tr>\n</table>\n', text) text = headingArrow.sub( r'<th align=right valign=top>\n' + r'<br><A HREF =" r'<IMG BORDER=0 width=30 height=20 SRC="documents/next_down3.gif"></A>\n' + r'</th>\n<th width=100%><font size="+2">', text)
|
text = heading.sub(headingTableReplacement, text) text = headingArrow.sub(headingArrowReplacement, text)
|
def convertHeading(text): # create a table for the heading (with down arrow at left and VIGRA logo at right) text = heading.sub( r'<table cellpadding=5 bgcolor="#e0d090">\n<tr>\n\1\n' + r'</font></th>\n' + r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra3.gif"></a>' + r'</th></tr>\n</table>\n', text) text = headingArrow.sub( r'<th align=right valign=top>\n' + r'<br><A HREF ="#DOC.DOCU" >' + r'<IMG BORDER=0 width=30 height=20 SRC="documents/next_down3.gif"></A>\n' + r'</th>\n<th width=100%><font size="+2">', text) # simplify heading if headingTypedef.search(text): return text # don't simplify typedef if headingTemplateSpecialization.search(text): return text # don't simplify explicitly specialized templates if headingTemplateClass.search(text): text = headingInheritance.sub(r'\1</font>', text) # remove inheritance return text # don't further simplify classes text = headingTemplateParameters.sub(r'<...>', text) # remove template parameters text = headingFunctionArguments.sub(r'(...)\1</font>', text) # remove function arguments return text
|
text = docu.sub(r'<table bgcolor=" r'<th align=left ><font size=+2> \1 </font></th>\n' + r'<tr>\n</table>', text) text = public.sub(r'</DL></DL>\n' + r'<table bgcolor=" r'<th align=left ><font size=+2> Members </font></th>\n' + r'<tr>\n</table>\n' + r'<DL><DL>\n<DT><h3>Public', text, 1) text = arrow.sub(r'<IMG BORDER=0 SRC="documents/next_down3.gif" width=15 height=15></A>', text)
|
text = docu.sub(docuReplacement, text) text = public.sub(publicReplacement, text, 1) text = arrow.sub(r'<IMG BORDER=0 SRC="documents/pfeil.gif"></A>', text) text = bullet.sub(r'<IMG BORDER=0 SRC="documents/bullet.gif">', text) text = bullet2.sub('', text) text = fixDocBaselinkBug(text)
|
def convertBody(text): text = body.sub(r'<body bgcolor="#f8f0e0" link="#0040b0" vlink="#a00040">', text, 1) text = callOperator.sub(r'operator()', text) text = tag.sub(r'<\1>', text) text = atag.sub(r'<a name="\1">', text) text = umlaut.sub(r'&\1;', text) text = squared.sub(r'²', text) text = cube.sub(r'³', text) text = footer.sub(r'', text, 1) text = stlLink.sub(r'http://www.sgi.com/Technology/STL', text) text = ruler.sub(r'<br>', text) text = docu.sub(r'<table bgcolor="#e0d090" width=100% cellpadding=5>\n<tr>\n' + r'<th align=left ><font size=+2> \1 </font></th>\n' + r'<tr>\n</table>', text) text = public.sub(r'</DL></DL>\n' + r'<table bgcolor="#e0d090" width=100% cellpadding=5>\n<tr>\n' + r'<th align=left ><font size=+2> Members </font></th>\n' + r'<tr>\n</table>\n' + r'<DL><DL>\n<DT><h3>Public', text, 1) text = arrow.sub(r'<IMG BORDER=0 SRC="documents/next_down3.gif" width=15 height=15></A>', text) return text
|
return re.sub(r'<H2>Variables</H2>', r'<H2>typedefs</H2>', text)
|
text = re.sub(r'<H2>Variables</H2>', r'<H2>typedefs</H2>', text) text = re.sub(r'<H1>Table of contents</H1>', r'<table bgcolor=" r'<th align=left width=100%><font size=+3>Table of Contents</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>', text) text = re.sub(r'<H2>(.*?)</H2>', docuReplacement, text) return text def convertHIER(text): text = re.sub(r'<H1>(.*?)</H1>', r'<table bgcolor=" r'<th align=left width=100%><font size=+3>\1</font></th>\n' \ r'<th align=right ><a href="index.html"><IMG border=0 SRC="documents/vigra.gif"></a>' \ r'<tr>\n</table>', text) return text
|
def convertAIndex(text): return re.sub(r'<H2>Variables</H2>', r'<H2>typedefs</H2>', text)
|
headingText = findHeading(text) newHeadingText = convertHeading(headingText) text = heading.sub(newHeadingText, text)
|
def processFile(fileName): print fileName f = open(fileName) text = f.read() f.close() headingText = findHeading(text) newHeadingText = convertHeading(headingText) text = heading.sub(newHeadingText, text) text = convertBody(text) if fileName == str(sys.argv[1]) + '/aindex.html': text = convertAIndex(text) if fileName == str(sys.argv[1]) + '/index.html': text = convertIndex(text, str(sys.argv[2])) f = open(fileName, 'w+') f.write(text) f.close()
|
|
if fileName == str(sys.argv[1]) + '/index.html': text = convertIndex(text, str(sys.argv[2]))
|
elif fileName == str(sys.argv[1]) + '/HIER.html': text = convertHIER(text) else: headingText = findHeading(text) newHeadingText = convertHeading(headingText) text = heading.sub(newHeadingText, text)
|
def processFile(fileName): print fileName f = open(fileName) text = f.read() f.close() headingText = findHeading(text) newHeadingText = convertHeading(headingText) text = heading.sub(newHeadingText, text) text = convertBody(text) if fileName == str(sys.argv[1]) + '/aindex.html': text = convertAIndex(text) if fileName == str(sys.argv[1]) + '/index.html': text = convertIndex(text, str(sys.argv[2])) f = open(fileName, 'w+') f.write(text) f.close()
|
m = re.search(r'Declarations?:[^\(]*?\s*([a-zA-Z_][a-zA-Z_0-9]*) *\(', t)
|
m = re.search(r'Declarations?:[^\(]*?(\s*<a class="code"[^>]*>|\s*)([a-zA-Z_][a-zA-Z_0-9]*)(</a>| *)\(', t)
|
def findExplicitDeclarations(text): decl = {} t = text while len(t): m = re.search(r'Declarations?:[^\(]*?\s*([a-zA-Z_][a-zA-Z_0-9]*) *\(', t) if not m: break decl[m.groups()[0]] = 1 t = t[m.end():] t = "" for i in decl.keys(): t = t + i + "|" if t: return "(" + t[:-1] + ")" else: return None
|
decl[m.groups()[0]] = 1
|
decl[m.groups()[1]] = 1
|
def findExplicitDeclarations(text): decl = {} t = text while len(t): m = re.search(r'Declarations?:[^\(]*?\s*([a-zA-Z_][a-zA-Z_0-9]*) *\(', t) if not m: break decl[m.groups()[0]] = 1 t = t[m.end():] t = "" for i in decl.keys(): t = t + i + "|" if t: return "(" + t[:-1] + ")" else: return None
|
text = re.sub(r'(<td nowrap align=right valign=top>template<).*?(>.*?)'+declPattern+r'(.*?</tr>)', r'\1...\2\3\4', text)
|
text = re.sub(r'(<td nowrap align=right valign=top>template<).*?(>.*?)'+declPattern+\ r'(.*?</tr>)', r'\1...\2\3\4', text)
|
def processFile(fileName): print fileName f = open(fileName) text = f.read() f.close() text = convertHeader(text) if not re.search(r'.*source.html', fileName): text = convertPage(text) else: text = convertSource(text) if re.search(r'.*/group__.*html', fileName): text = typedefField.sub(r'<br><b> \1</b><br> ', text) declPattern = findExplicitDeclarations(text) if declPattern: text = re.sub(r'(<td nowrap align=right valign=top>template<).*?(>.*?)'+declPattern+r'(.*?</tr>)', r'\1...\2\3\4', text) functionSignature = re.compile(r'<table cellpadding="0" cellspacing="0" border="0">\s*'+\ r'<tr>\s*<td class="md".*?>(.*?)'+declPattern+r' *</td>.*?</table>', re.S) text = functionSignature.sub(r'<br><b> \1\2 (...)</b><br> ', text) if re.search(r'.*/index.html', fileName): text = re.sub(r'<h3 align="center">\d+\.\d+\.\d+</h3>', '', text) if re.search(r'.*/namespacevigra.html', fileName): text = re.sub(r"template<.*?>", "template<...>", text) if re.search(r'.*/classes.html', fileName): text = re.sub(r'(<div class="ah">)( . )', r'\1<font color="white"><b>\2</b>', text) text = re.sub(r'\(<a class="el" href="namespace[^\)]*\)', '', text) f = open(fileName, 'w+') f.write(text) f.close()
|
r'<tr>\s*<td class="md".*?>(.*?)'+declPattern+r' *</td>.*?</table>', re.S)
|
r'<tr>\s*<td class="md"[^>]*>([^<]*?)'+declPattern+r' *</td>.*?</table>', re.S)
|
def processFile(fileName): print fileName f = open(fileName) text = f.read() f.close() text = convertHeader(text) if not re.search(r'.*source.html', fileName): text = convertPage(text) else: text = convertSource(text) if re.search(r'.*/group__.*html', fileName): text = typedefField.sub(r'<br><b> \1</b><br> ', text) declPattern = findExplicitDeclarations(text) if declPattern: text = re.sub(r'(<td nowrap align=right valign=top>template<).*?(>.*?)'+declPattern+r'(.*?</tr>)', r'\1...\2\3\4', text) functionSignature = re.compile(r'<table cellpadding="0" cellspacing="0" border="0">\s*'+\ r'<tr>\s*<td class="md".*?>(.*?)'+declPattern+r' *</td>.*?</table>', re.S) text = functionSignature.sub(r'<br><b> \1\2 (...)</b><br> ', text) if re.search(r'.*/index.html', fileName): text = re.sub(r'<h3 align="center">\d+\.\d+\.\d+</h3>', '', text) if re.search(r'.*/namespacevigra.html', fileName): text = re.sub(r"template<.*?>", "template<...>", text) if re.search(r'.*/classes.html', fileName): text = re.sub(r'(<div class="ah">)( . )', r'\1<font color="white"><b>\2</b>', text) text = re.sub(r'\(<a class="el" href="namespace[^\)]*\)', '', text) f = open(fileName, 'w+') f.write(text) f.close()
|
glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE)
|
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE)
|
def go(self): glutInitWindowSize(500,500) glutInitWindowPosition(100,100) glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE) self.win = glutCreateWindow("iSink ROV Simulator") self.init() glutDisplayFunc(self.display) glutIdleFunc(self.doframe) self.thistime = self.lastime = time() glutMainLoop()
|
if ~config.has_section('locations'): raise 'Congfig file must have a \'location\' section'
|
if config.has_section('locations') is False: raise 'Congfig file must have a \'locations\' section'
|
def get_backup_info(config): """ @type configfile: ConfigParser @param configfile: The config file to read from @rtype: dictionary of tuples @return: Maps directory to a tuple of (src, days, weeks) Config file format: # Name directory pair [locations] trac = /var/backup/trac # Specifies a weekly and inremental # With 10 days of incremental and 4 weeks of weekly backups # Days and weeks can be missing and default values will be used [trac] days = 10 weeks = 4 src = /tmp/trac-backup """ if ~config.has_section('locations'): raise 'Congfig file must have a \'location\' section' backup_info = {} locations = config.options('locations') # Read in the days and weeks for each slection (10 and 4 if not given) for location in locations: # Where to do the backup directory = config.get('locations', location) # Change values if options are set def get_option(key, default): if config.has_section(location): if config.has_option(location, key): return config.get(location, key) else: return default weeks = get_option('weeks', 10) days = get_option('days', 4) src = get_option('src', os.path.join('/tmp', location + '-backup')) backup_info[directory] = (src, days, weeks) return backup_info
|
base_dir = os.path.split(path)[0]
|
def date_name(path): """ Takes a file specified by path and returns its name in strftime format %F_%T which is its last modified time """ # Get the modification time from the timestamp of the fill mod_time = datetime.fromtimestamp(os.stat(path).st_mtime) # Grab our parent directory base_dir = os.path.split(path)[0] # Join the two and rename the file dated_path = os.path.join(base_dir, mod_time.strftime('%F_%T')) return dated_path
|
|
dated_path = os.path.join(base_dir, mod_time.strftime('%F_%T'))
|
return mod_time.strftime('%F_%T')
|
def date_name(path): """ Takes a file specified by path and returns its name in strftime format %F_%T which is its last modified time """ # Get the modification time from the timestamp of the fill mod_time = datetime.fromtimestamp(os.stat(path).st_mtime) # Grab our parent directory base_dir = os.path.split(path)[0] # Join the two and rename the file dated_path = os.path.join(base_dir, mod_time.strftime('%F_%T')) return dated_path
|
if ~os.path.exists(path):
|
if os.path.exists(path) is False:
|
def ensure_path(path): """ Makes sure a path exists, and if it doesn't it will create it """ if ~os.path.exists(path): os.makedirs(path);
|
for (path, opts) in backup_tasks:
|
for path in backup_tasks.iterkeys(): raw_opts = backup_tasks[path] opts = (raw_opts[0], int(raw_opts[1]), int(raw_opts[2]))
|
def main(argv=None): # Parse are command line parser = OptionParser() parser.add_option("-c", "--config", dest="configfile", help="The location of config", default='etc/opt/backup.cfg') (options, args) = parser.parse_args() # Read the config file and pull out usefull information config = ConfigParser() config.read(options.configfile) backup_tasks = get_backup_info(config) now = datetime.now() for (path, opts) in backup_tasks: # Make sure src and destination are properly formatted src_path = opts[0] if ~os.path.exists(src_path): raise "Could not find source directory %s" % src_path weekly_path = os.path.join(path, 'weekly') incremental_path = os.path.join(path, 'incremental') ensure_path(weekly_path) ensure_path(incremental_path) # Roll back time the needed number of weeks delta = timedelta(opts[2] * 7) cutoff = now - delta; # Weekly backup shutil.copytree(src_path, weekly_path + os.sep + date_name(src_dir)) remove_old(weekly_path, cutoff) # Incremental Backup try: subprocess.call(['rdiff-backup', src_path, incremental_path]) subprocess.call(['rdiff-backup', '--remove-older-than', opts[1] + 'D', incremental_path]) except OSError: raise "Please install rdiff-backup and put it in on your PATH"
|
if ~os.path.exists(src_path):
|
if os.path.exists(src_path) is False:
|
def main(argv=None): # Parse are command line parser = OptionParser() parser.add_option("-c", "--config", dest="configfile", help="The location of config", default='etc/opt/backup.cfg') (options, args) = parser.parse_args() # Read the config file and pull out usefull information config = ConfigParser() config.read(options.configfile) backup_tasks = get_backup_info(config) now = datetime.now() for (path, opts) in backup_tasks: # Make sure src and destination are properly formatted src_path = opts[0] if ~os.path.exists(src_path): raise "Could not find source directory %s" % src_path weekly_path = os.path.join(path, 'weekly') incremental_path = os.path.join(path, 'incremental') ensure_path(weekly_path) ensure_path(incremental_path) # Roll back time the needed number of weeks delta = timedelta(opts[2] * 7) cutoff = now - delta; # Weekly backup shutil.copytree(src_path, weekly_path + os.sep + date_name(src_dir)) remove_old(weekly_path, cutoff) # Incremental Backup try: subprocess.call(['rdiff-backup', src_path, incremental_path]) subprocess.call(['rdiff-backup', '--remove-older-than', opts[1] + 'D', incremental_path]) except OSError: raise "Please install rdiff-backup and put it in on your PATH"
|
shutil.copytree(src_path, weekly_path + os.sep + date_name(src_dir))
|
shutil.copytree(src_path, weekly_path + os.sep + date_name(src_path))
|
def main(argv=None): # Parse are command line parser = OptionParser() parser.add_option("-c", "--config", dest="configfile", help="The location of config", default='etc/opt/backup.cfg') (options, args) = parser.parse_args() # Read the config file and pull out usefull information config = ConfigParser() config.read(options.configfile) backup_tasks = get_backup_info(config) now = datetime.now() for (path, opts) in backup_tasks: # Make sure src and destination are properly formatted src_path = opts[0] if ~os.path.exists(src_path): raise "Could not find source directory %s" % src_path weekly_path = os.path.join(path, 'weekly') incremental_path = os.path.join(path, 'incremental') ensure_path(weekly_path) ensure_path(incremental_path) # Roll back time the needed number of weeks delta = timedelta(opts[2] * 7) cutoff = now - delta; # Weekly backup shutil.copytree(src_path, weekly_path + os.sep + date_name(src_dir)) remove_old(weekly_path, cutoff) # Incremental Backup try: subprocess.call(['rdiff-backup', src_path, incremental_path]) subprocess.call(['rdiff-backup', '--remove-older-than', opts[1] + 'D', incremental_path]) except OSError: raise "Please install rdiff-backup and put it in on your PATH"
|
opts[1] + 'D', incremental_path])
|
str(opts[1]) + 'D', incremental_path])
|
def main(argv=None): # Parse are command line parser = OptionParser() parser.add_option("-c", "--config", dest="configfile", help="The location of config", default='etc/opt/backup.cfg') (options, args) = parser.parse_args() # Read the config file and pull out usefull information config = ConfigParser() config.read(options.configfile) backup_tasks = get_backup_info(config) now = datetime.now() for (path, opts) in backup_tasks: # Make sure src and destination are properly formatted src_path = opts[0] if ~os.path.exists(src_path): raise "Could not find source directory %s" % src_path weekly_path = os.path.join(path, 'weekly') incremental_path = os.path.join(path, 'incremental') ensure_path(weekly_path) ensure_path(incremental_path) # Roll back time the needed number of weeks delta = timedelta(opts[2] * 7) cutoff = now - delta; # Weekly backup shutil.copytree(src_path, weekly_path + os.sep + date_name(src_dir)) remove_old(weekly_path, cutoff) # Incremental Backup try: subprocess.call(['rdiff-backup', src_path, incremental_path]) subprocess.call(['rdiff-backup', '--remove-older-than', opts[1] + 'D', incremental_path]) except OSError: raise "Please install rdiff-backup and put it in on your PATH"
|
for loc in config.items('locations'): run_location(loc, config)
|
else: for loc in config.items('locations'): run_location(loc, config)
|
def run_config(configfile, location = None): """ Loads the config file and call run_location """ # Parse config file config = ConfigParser() config.optionxform = lambda x: x config.read(configfile) if not config.has_section('locations'): print 'ERROR: Configuration file: %s does not have a \'locations\'' \ ' section' % config_path sys.exit(1) # Run sections if location: loc_path = config.get('locations', location) run_location((location,loc_path), config) for loc in config.items('locations'): run_location(loc, config)
|
run_config(config_path)
|
run_config(config_path, options.location)
|
def main(): # Parse are command line parser = OptionParser(description= \ 'This runs a config file that is basically a mapping of locations to'\ 'commands. Each command name for each location must be unique, see'\ 'test config in the tools/build-deps for an example') parser.add_option("-c", "--config", dest="configfile", help="The location of config", default='<mrbc-root>/deps/build.cfg') parser.add_option("-l", "--location", dest="location", help="If given, run just this location from the configfile") (options, args) = parser.parse_args() config_path = get_config_path(options.configfile) run_config(config_path)
|
def quote(str): return repr(str)
|
def quote(s): s = s.replace('\\', '\\\\') s = s.replace('\0', '\\0') s = s.replace('\b', '\\b') s = s.replace('\n', '\\n') s = s.replace('\r', '\\r') s = s.replace('\t', '\\t') s = s.replace('\z', '\\z') s = s.replace("'", "\\'") s = s.replace('"', '\\"') return "'" + s + "'"
|
def quote(str): return repr(str)
|
parent_id = 0 id = parent_id + 1 for entry in contents: id = dump_contents_entry(entry, id, parent_id) print ";"
|
id = dump_contents_entry(contents, 0, 1)
|
def dump_contents(contents): print "INSERT INTO `toc` (`book_id`, `parent_id`, `number`, `name`, `link`) VALUES" parent_id = 0 id = parent_id + 1 for entry in contents: id = dump_contents_entry(entry, id, parent_id) print ";" print "UPDATE `toc` SET `parent_id` = LAST_INSERT_ID() + `parent_id` - 1 WHERE `book_id` = @book_id AND `parent_id` != 1;"
|
def dump_contents_entry(entry, id, parent_id): print " (@book_id, %d, %d, %s, %s)," % (parent_id, entry.number, quote(entry.name.encode('utf-8')), quote(entry.link.encode('utf-8'))) parent_id = id
|
def dump_contents_entry(entry, parent_id, last):
|
def dump_contents_entry(entry, id, parent_id): print " (@book_id, %d, %d, %s, %s)," % (parent_id, entry.number, quote(entry.name.encode('utf-8')), quote(entry.link.encode('utf-8'))) parent_id = id id = parent_id + 1 for subentry in entry: id = dump_contents_entry(subentry, id, parent_id) return id
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.