rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if x0<self.plotaread[0] and x1>self.plotaread[0]: | if x0<self.plotaread[0] and x1>=self.plotaread[0]: | def drawpoint(self, aFullPNString, datapoint): #get datapoint x y values #convert to plot coordinates if self.trace_onoff[aFullPNString]==gtk.FALSE: return 0 x=self.convertx_to_plot(datapoint[0]) y=self.converty_to_plot(datapoint[1]) cur_point_within_frame=self.withinframes([x,y]) #getlastpoint, calculate change to the... |
if x0>self.plotaread[2] and x1<self.plotaread[2]: | if x0>self.plotaread[2] and x1<=self.plotaread[2]: | def drawpoint(self, aFullPNString, datapoint): #get datapoint x y values #convert to plot coordinates if self.trace_onoff[aFullPNString]==gtk.FALSE: return 0 x=self.convertx_to_plot(datapoint[0]) y=self.converty_to_plot(datapoint[1]) cur_point_within_frame=self.withinframes([x,y]) #getlastpoint, calculate change to the... |
if x1<self.plotaread[0] and x0>self.plotaread[0]: | if x1<self.plotaread[0] and x0>=self.plotaread[0]: | def drawpoint(self, aFullPNString, datapoint): #get datapoint x y values #convert to plot coordinates if self.trace_onoff[aFullPNString]==gtk.FALSE: return 0 x=self.convertx_to_plot(datapoint[0]) y=self.converty_to_plot(datapoint[1]) cur_point_within_frame=self.withinframes([x,y]) #getlastpoint, calculate change to the... |
if x1>self.plotaread[2] and x0<self.plotaread[2]: | if x1>self.plotaread[2] and x0<=self.plotaread[2]: | def drawpoint(self, aFullPNString, datapoint): #get datapoint x y values #convert to plot coordinates if self.trace_onoff[aFullPNString]==gtk.FALSE: return 0 x=self.convertx_to_plot(datapoint[0]) y=self.converty_to_plot(datapoint[1]) cur_point_within_frame=self.withinframes([x,y]) #getlastpoint, calculate change to the... |
if string.count( fullid, ':' ) != 2: raise ValueError( "FullID must have 2 ':'s." ) return string.split( fullid, ':' ) | aList = string.split( fullid, ':' ) aLength = len( aList ) if aLength != 3: raise ValueError( "FullID must have 2 ':'s. ( %d given ) " % aLength - 1 ) return aList | def parseFullID( fullid ): if string.count( fullid, ':' ) != 2: raise ValueError( "FullID must have 2 ':'s." ) return string.split( fullid, ':' ) |
if string.count( fullpropertyname, ':' ) != 3: raise ValueError( "FullPropertyName must have 3 ':'s." ) return string.split( fullpropertyname, ':' ) | aList = string.split( fullpropertyname, ':' ) aLength = len( aList ) if aLength != 4: raise ValueError( "FullPropertyName must have 3 ':'s. ( %d given ) " % aLength - 1 ) return aList | def parseFullPropertyName( fullpropertyname ): if string.count( fullpropertyname, ':' ) != 3: raise ValueError( "FullPropertyName must have 3 ':'s." ) return string.split( fullpropertyname, ':' ) |
"FullID has 3 parts. ( %d given )" % aLength ) | "FullID has 3 fields. ( %d given )" % aLength ) | def constructFullID( words ): aLength = len( words ) if aLength != 3: raise ValueError( "FullID has 3 parts. ( %d given )" % aLength ) return string.join( words, ':' ) |
"FullPropertyName has 4 parts. ( %d given )" % aLength ) | "FullPropertyName has 4 fields. ( %d given )" % aLength ) | def constructFullPropertyName( words ): aLength = len( words ) if aLength != 4: raise ValueError( "FullPropertyName has 4 parts. ( %d given )" % aLength ) return string.join( words, ':' ) |
aKineticLaw = aReaction.getKineticLaw() ListOfKineticLaw = [] if aKineticLaw != []: aFormula_KL = aKineticLaw.getFormula() aMath = [] if( aSBMLDocument.getLevel() == 1 ): aMath.append( '' ) else: anASTNode_KL = aKineticLaw.getMath() aMath.append( libsbml.formulaToString( anASTNode_KL ) ) aString_KL = aMath aTimeUn... | if aReaction.isSetKineticLaw(): aKineticLaw = aReaction.getKineticLaw() ListOfKineticLaw = [] if aKineticLaw != []: if aKineticLaw.isSetFormula(): aFormula_KL = aKineticLaw.getFormula() else: aFormula_KL = '' aMath = [] if( aSBMLDocument.getLevel() == 1 ): aMath.append( '' ) else: if aKineticLaw.isSetMath(): anASTN... | def getReaction( aSBMLmodel, aSBMLDocument ): " [[ Id , Name , [ Formula , String , TimeUnit , SubstanceUnit , [[ ParameterId , ParameterName , ParameterValue , ParameterUnit , ParameterConstant ]] ] , Reversible , Fast , [[ ReactantSpecies , ( ReactantStoichiometry , ReactantStoichiometryMath ) , ReactantDenominator ... |
count = 0 | count = 1 | def checkMultiplicity(self): processes = {} my_pid = 1 count = 0 try: f = open('throttle.log','r') except IOError: if not self.pid: pass else: raise else: now = time.time() for line in f.readlines(): line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now -... |
print("Checked for running processes. %s processes currently running, "%len(processes) + | print("Checked for running processes. %s processes currently running, "%count + | def checkMultiplicity(self): processes = {} my_pid = 1 count = 0 try: f = open('throttle.log','r') except IOError: if not self.pid: pass else: raise else: now = time.time() for line in f.readlines(): line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now -... |
ofp.write(oldcontent.encode(config.console_encoding)) | if self.options.new_data == '': ofp.write(oldcontent.encode(config.console_encoding)) else: ofp.write(oldcontent.encode(config.console_encoding)+'\n===========\n'+self.options.new_data) | def edit(self): """Edit the page using the editor. It returns two strings: the old version and the new version.""" ofn = tempfile.mktemp() ofp = open(ofn, 'w') try: oldcontent = self.pagelink.get() except wikipedia.NoPage: oldcontent = "" except wikipedia.IsRedirectPage: if self.options.redirect: oldcontent = self.pag... |
if site == mysite and pl.exists() and not pl.isRedirectPage() and not pl.isEmpty(): | if site == mysite and pl.exists() and not pl.isRedirectPage(): | def assemble(self): # No errors have been seen so far nerr = 0 # Build up a dictionary of all links found, with the site as key. # Each value will be a list. mysite = wikipedia.getSite() new = {} for pl in self.done.keys(): site = pl.site() if site == mysite and pl.exists() and not pl.isRedirectPage() and not pl.isEmp... |
print "WARNING: Could not load %s%s. Maybe the server is down. Retrying in %i minutes..." % (self.site.hostname(), path, retry_idle_time) | print "WARNING: Could not load %s%s. Maybe the server is down. Retrying in %i minutes..." % (self.site().hostname(), path, retry_idle_time) | def getEditPage(self, get_redirect=False, throttle = True, sysop = False): """ Get the contents of the Page via the edit page. Do not use this directly, use get() instead. Arguments: get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text. """ isW... |
'mk': [u'Никулец'], | def __init__(self): family.Family.__init__(self) self.name = 'wikipedia' | |
'eu' : lambda v: dh_dayOfMnth( v, u'Aprilaren %d' ), | 'eu' : lambda v: dh_dayOfMnth( v, u'Apirilaren %d' ), | def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo... |
'cy' : lambda v: dh_dayOfMnth( v, u'%d Gorffenaf' ), | 'cy' : lambda v: dh_dayOfMnth( v, u'%d Gorffennaf' ), | def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo... |
'la' : lambda v: dh_noConv( v, u'%d a.C.n' ), | 'la' : lambda v: dh_noConv( v, u'%d a.C.n.' ), | def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo... |
the optional argument 'into' specifies the encoding of the target wikipedia | the argument 'incode' specifies the encoding of the target wikipedia | def url2link(percentname,incode,code): """Convert a url-name of a page into a proper name for an interwiki link the optional argument 'into' specifies the encoding of the target wikipedia """ result=underline2space(percentname) x=url2unicode(result,language=code) if code2encoding(incode)==code2encoding(code): #print "u... |
edits = editR.findall(txt) | edits = editR.findall(self._versionhistory) | def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() host = site.hostname() url = site.family.version_history_address(site, self.urlname(... |
yield wikipedia.PageLink(wikipedia.mylang, pagenames) | for pagename in pagenames: yield wikipedia.PageLink(wikipedia.mylang, pagename) | def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ... |
pass | continue | def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ... |
newTable, num = re.subn(r'([\r\n]+(\!|\||\{\|)[^\r\n\|]+)[ ]*=[ ]*([^"][^\s]+?[^"])(\s)', r'\1="\3"\4', newTable, 1) | newTable, num = re.subn(r'([\r\n]+(?:!|\||\{\|)[^\r\n\|]+) *= *([^"\s>]+)(\s)', r'\1="\2"\3', newTable, 1) | def convertTable(self, table): ''' Converts an HTML table to wiki syntax. If the table already is a wiki table or contains a nested wiki table, tries to beautify it. Returns the converted table, the number of warnings that occured and a list containing these warnings. |
retry_idle_time = 1 while True: | startFromPage = None thisCatDone = False while not thisCatDone: retry_idle_time = 1 while True: try: if startFromPage: txt = wikipedia.getPage(site, cat.urlname() + '&from=' + startFromPage, get_edit_page = False) else: txt = wikipedia.getPage(site, cat.urlname(), get_edit_page = False) except: raise print "WA... | def _make_catlist(self, recurse = False, site = None): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and subcategories of any subcategories are also retrieved. |
txt = wikipedia.getPage(site, cat.urlname(), get_edit_page = False) except: raise print "WARNING: There was a problem retrieving %s. Maybe the server is down. Retrying in %d minutes..." % (cat.linkname(), retry_idle_time) time.sleep(retry_idle_time * 60) retry_idle_time *= 2 if retry_idle_time > 30: retry_idle_time =... | iend = txt.index('<div id="catlinks">') except ValueError: iend = txt.index('<!-- end content -->') txt = txt[ibegin:iend] for title in Rtitle.findall(txt): if iscattitle(title): ncat = _CatLink(self.site(), title) if recurse and ncat not in catsdone: catstodo.append(ncat) subcats.append(title) else: articles.append(ti... | def _make_catlist(self, recurse = False, site = None): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and subcategories of any subcategories are also retrieved. |
articles.append(title) | thisCatDone = True | def _make_catlist(self, recurse = False, site = None): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and subcategories of any subcategories are also retrieved. |
title = title.encode(site.encoding()) title = urllib.unquote(title) return unicode(title, site.encoding()) | try: t = title.encode(site.encoding()) t = urllib.unquote(t) return unicode(t, site.encoding()) except UnicodeError: for enc in site.encodings(): try: t = title.encode(enc) t = urllib.unquote(t) return unicode(t, enc) except UnicodeError: pass raise | def url2unicode(title, site): title = title.encode(site.encoding()) title = urllib.unquote(title) return unicode(title, site.encoding()) |
def main(): | try: | def fix_double_redirects(source): mysite = wikipedia.getSite() for redir_name in retrieve_double_redirects(source): print '' redir = wikipedia.PageLink(mysite, redir_name) try: target = redir.getRedirectTo() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.linkname()) except wikiped... |
if True: try: main() except: wikipedia.stopme() raise else: wikipedia.stopme() | finally: wikipedia.stopme() | def main(): # read command line parameters # what the bot should do (either resolve double redirs, or delete broken redirs) action = None # where the bot should get his infos from (either None to load the maintenance # special page from the live wiki, the filename of a local sql dump file) source = None # Which namespa... |
self.process_multiplicity = len(processes) | self.process_multiplicity = count | def checkMultiplicity(self): processes = {} my_pid = 1 count = 0 try: f = open('throttle.log','r') except IOError: if not self.pid: pass else: raise else: now = time.time() for line in f.readlines(): line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now -... |
if now - ptime <= self.dropdelay and pid != self.pid: | if now - ptime <= self.releasepid and pid != self.pid: | def drop(self): """Remove me from the list of running bots processes.""" self.checktime = 0 processes = {} try: f = open('throttle.log','r') except IOError: return else: now = time.time() for line in f.readlines(): line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.dropd... |
if self.oldCat.exists() and batchMode == False: | if self.oldCat.exists(): | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat) # TODO: cre... |
if self.oldCat.isEmpty(): reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % newCatTitle self.oldCat.delete(reason) else: wikipedia.output('Couldn\'t copy contents of %s because %s already exists.' % (self.oldCatTitle, self.newCatTitle)) | if batchMode == False: if self.oldCat.isEmpty(): reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % newCatTitle self.oldCat.delete(reason) else: wikipedia.output('Couldn\'t copy contents of %s because %s already exists.' % (self.oldCatTitle, self.newCatTitle)) | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat) # TODO: cre... |
t=self.sectionFreeTitle() p=t.split(':', 1) if len(p) == 1: return p[0] else: return p[1] | if self.namespace() == 0: return self.title() else: return self.sectionFreeTitle().split(':', 1)[1] | def titleWithoutNamespace(self): """The name of the page without the namespace part. Returns the sectionFreeTitle if the page is from the main namespace. Note that this is a raw way of doing things - it simply looks for a : in the name.""" t=self.sectionFreeTitle() p=t.split(':', 1) if len(p) == 1: # page is in the mai... |
print "NOTE: Ignoring %s, using %s"%(new[zh].asasciilink(),pl.asasciilink()) | print "NOTE: Ignoring %s, using %s"%(new['zh'].asasciilink(),pl.asasciilink()) | def treesearch(pl): arr = {pl:None} # First make one step based on the language itself try: n = treestep(arr, pl, abort_on_redirect = 1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n == 0 and not arr[pl]: print "Mother doesn't exist" return if untranslated: if len(arr) > 1: print "Already has tr... |
Rlink=re.compile('\[\[([^\]]*)\]\]') | w=r'([^\]\|]*)' Rlink=re.compile(r'\[\['+w+r'(\|'+w+r')?\]\]') | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
alternatives=Rlink.findall(thistxt) | alternatives=[] for a in Rlink.findall(thistxt): alternatives.append(a[0]) | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
Rthis=re.compile('\[\[%s(\|[^\]]*)?\]\]'%thispl.linkname()) | exps=[] zz='\[\[(%s)(\|[^\]]*)?\]\]' Rthis=re.compile(zz%thispl.linkname()) exps.append(Rthis) | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
Rthis2=re.compile('\[\[%s(\|[^\]]*)?\]\]'%aln) | Rthis=re.compile(zz%aln) exps.append(Rthis) Rthis=re.compile(zz%thispl.linkname().lower()) exps.append(Rthis) Rthis=re.compile(zz%aln.lower()) exps.append(Rthis) | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
m=Rthis.search(reftxt) if not m: m=Rthis2.search(reftxt) if not m: | for Rthis in exps: m=Rthis.search(reftxt) if m: break else: | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
print "== %s =="%(refpl) print reftxt[m.start()-context:m.end()+context] | print "== %s =="%(refpl),m.start(),m.end() print reftxt[max(0,m.start()-context):m.end()+context] | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
if not g1: g1=thispl.linkname() reptxt="%s|%s"%(alternatives[choice],g1) | g2=m.group(2) if g2: g2=g2[1:] else: g2=g1 reptxt="%s|%s"%(alternatives[choice],g2) | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
print newtxt[m.start()-30:m.end()+30] | print newtxt[max(0,m.start()-30):m.end()+30] | def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt) |
print 'match' | def getReferences(pl, follow_redirects = True): host = family.hostname(pl.code()) url = family.references_address(mylang, pl.urlname()) output('Getting references to %s:%s' % (pl.code(), pl.linkname())) txt, charset = getUrl(host,url) # remove brackets which would disturb the regular expression cascadedListR txt = txt.... | |
if pl.isDisambig(): return pl | try: if pl.isDisambig(): return pl except wikipedia.NoPage: pass | def hasdisambig(self,site): # Returns TRUE if a link to a disambiguation page on site site has been found for pl in self.pending + self.done.keys(): if pl.site() == site: if pl.isDisambig(): return pl return False |
if not pl.isDisambig(): return pl | try: if not pl.isDisambig(): return pl except wikipedia.NoPage: pass | def hasnondisambig(self,site): # Returns TRUE if a link to a disambiguation page on site site has been found for pl in self.pending + self.done.keys(): if pl.site() == site: if not pl.isDisambig(): return pl return False |
def getVersionHistory(self, forceReload = False): | def getVersionHistory(self, forceReload = False, reverseOrder = False, getAll = False): | def getRedirectTarget(self): """ If the page is a redirect page, gives the title of the page it redirects to. Otherwise it will raise an IsNotRedirectPage exception. This function can raise a NoPage exception. """ try: self.get() except NoPage: raise NoPage(self) except IsRedirectPage, arg: if '|' in arg: warnings.war... |
summary. | summary. Defaults to getting the first 500 edits. | def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() path = site.family.version_history_address(self.site().language(), self.urlname()) |
path = site.family.version_history_address(self.site().language(), self.urlname()) if not hasattr(self, '_versionhistory') or forceReload: output(u'Getting version history of %s' % self.title()) txt = site.getUrl(path) self._versionhistory = txt | def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() path = site.family.version_history_address(self.site().language(), self.urlname()) | |
edits = editR.findall(self._versionhistory) return edits def getVersionHistoryTable(self, forceReload = False): | startFromPage = None thisHistoryDone = False skip = False RLinkToNextPage = re.compile('&offset=(.*?)&') if reverseOrder: if not hasattr(self, '_versionhistoryearliest') or forceReload: self._versionhistoryearliest = [] elif getAll and len(self._versionhistoryearliest) == 500: thisHistoryDone = False skip ... | def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() path = site.family.version_history_address(self.site().language(), self.urlname()) |
for time, username, summary in self.getVersionHistory(forceReload = forceReload): | for time, username, summary in self.getVersionHistory(forceReload = forceReload, reverseOrder = reverseOrder, getAll = getAll): | def getVersionHistoryTable(self, forceReload = False): """ Returns the version history as a wiki table. """ result = '{| border="1"\n' result += '! date/time || username || edit summary\n' for time, username, summary in self.getVersionHistory(forceReload = forceReload): result += '|----\n' result += '| %s || %s || <now... |
def delete(pl, reason = None, prompt = True): | def delete(self, reason = None, prompt = True): | def delete(pl, reason = None, prompt = True): """Deletes the page from the wiki. Requires administrator status. If reason is None, asks for a reason. If prompt is True, asks the user if he wants to delete the page. """ # TODO: Find out if bot is logged in with an admin account, raise exception # or show error message o... |
def post_multipart(host, selector, fields, cookies): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files. Return the server's response page. """ ... | def delete(pl, reason = None, prompt = True): """Deletes the page from the wiki. Requires administrator status. If reason is None, asks for a reason. If prompt is True, asks the user if he wants to delete the page. """ # TODO: Find out if bot is logged in with an admin account, raise exception # or show error message o... | |
answer = input(u'Do you want to delete %s? [y|N]' % pl.linkname()) | answer = inputChoice(u'Do you want to delete %s?' % self.linkname(), ['Yes', 'No'], ['y', 'N'], 'N') | def encode_multipart_formdata(fields): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF =... |
output(u'Deleting page %s...' % pl.linkname()) token = pl.site().getToken() returned_html = post_multipart(pl.site().hostname(), pl.site().delete_address(pl.urlname()), (('wpReason', reason), ('wpConfirm', '1'), ('wpEditToken', token)), pl.site().cookies()) deleted_msg = mediawiki_messages.get('actioncomplete') dele... | token = self.site().getToken(self) host = self.site().hostname() address = self.site().delete_address(space2underline(self.linkname())) while not self.site().loggedin(check = True): loginMan = login.LoginManager() loginMan.login() predata = [ ('wpReason', reason), ('wpConfirm', '1')] if token: predata.append(('wpEdi... | def encode_multipart_formdata(fields): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF =... |
returned_html = returned_html[ibegin:iend] output(returned_html, myencoding()) | output(u'Deletion failed:.') try: ibegin = data.index('<!-- start content -->') + 22 iend = data.index('<!-- end content -->') except ValueError: output(data) else: data = data[ibegin:iend] output(data) | def encode_multipart_formdata(fields): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF =... |
R = re.compile(r'\[\[(.+?)\]\]') | R = re.compile(ur'\[\[(.+?)\]\]') | def __iter__(self): site = wikipedia.getSite() f = codecs.open(self.filename, 'r', config.textfile_encoding) R = re.compile(r'\[\[(.+?)\]\]') for pageTitle in R.findall(f.read()): parts = pageTitle.split(':') i = 0 try: fam = wikipedia.Family(parts[i], fatal = False) i += 1 except: fam = site.family if parts[i] in fam.... |
fam == default_family | fam = default_family | def getSite(code = None, fam = None, user=None): if code == None: code = default_code if fam == None: fam == default_family key = '%s:%s'%(fam,code) if not _sites.has_key(key): _sites[key] = Site(code=code, fam=fam, user=user) return _sites[key] |
content = talk.get() | content = talk.get() + "\n\n" | def report(self, url, errorReport, containingPage): """ Tries to add an error report to the talk page belonging to the page containing the dead link. """ if config.report_dead_links_on_talk and not containingPage.isTalkPage(): wikipedia.output(u"** Reporting dead link on talk page...") talk = containingPage.switchTalkP... |
for (page, date, length, user, comment) in wikipedia.newpages(1000): | for (page, date, length, loggedIn, user, comment) in wikipedia.newpages(1000): | def declare_alternative(self,alt): if not alt in knownwords[self.word]: knownwords[self.word].append(word) newwords.append(self.word) return self.alternatives |
'da':u'Robot: Fjerner fra kategori %s', 'de':u'Bot: Entferne aus Kategorie %s', 'en':u'Robot: Removing from category %s', 'es':u'Bot: Eliminada de la categoría %s', 'is':u'Vélmenni: Fjarlægi [[Flokkur:%s]]', 'nl':u'Bot: Verwijderd uit Categorie %s', 'pt':u'Bot: Removendo [[Categoria:%s]]', | 'da':u'Robot: Fjerner fra %s', 'de':u'Bot: Entferne aus %s', 'en':u'Robot: Removing from %s', 'es':u'Bot: Eliminada de la %s', 'is':u'Vélmenni: Fjarlægi [[%s]]', 'nl':u'Bot: Verwijderd uit %s', 'pt':u'Bot: Removendo [[%s]]', | def run(self): articles = self.oldCat.articles(recurse = 0) |
cat.delete(reason) | self.cat.delete(reason) | def run(self): articles = self.cat.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in category %s' % self.cat.title()) else: for article in articles: catlib.change_category(article, self.cat, None) # Also removes the category tag from subcategories' pages subcategories = self.cat.s... |
x2=wikipedia.PageLink(wikipedia.getSite(code=newcode, fam=site.family), newname.lower()) | x2=wikipedia.PageLink(wikipedia.getSite(code=newcode, fam=site.family), newname[0].lower() + newname[1:]) | def sametranslate(pl, arr, same): site = pl.site() for newcode in site.family.seriouslangs: # Put as suggestion into array newname = pl.linkname() if newcode in ['eo','cs'] and same == 'name': newname = newname.split(' ') newname[-1] = newname[-1].upper() newname = ' '.join(newname) x=wikipedia.PageLink(wikipedia.getSi... |
arr[x2] = None | if newcode in site.family.nocapitalize: arr[x2] = None | def sametranslate(pl, arr, same): site = pl.site() for newcode in site.family.seriouslangs: # Put as suggestion into array newname = pl.linkname() if newcode in ['eo','cs'] and same == 'name': newname = newname.split(' ') newname[-1] = newname[-1].upper() newname = ' '.join(newname) x=wikipedia.PageLink(wikipedia.getSi... |
if hasattr(self, '_getexception'): | if hasattr(self, '_redirarg') and not get_redirect: raise IsRedirectPage, self._redirarg elif hasattr(self, '_getexception'): | def get(self, read_only = False, force = False, get_redirect=False, throttle = True): """The wiki-text of the page. This will retrieve the page if it has not been retrieved yet. This can raise the following exceptions that should be caught by the calling code: |
elif hasattr(self, '_redirarg') and not get_redirect: raise IsRedirectPage, self._redirarg | def get(self, read_only = False, force = False, get_redirect=False, throttle = True): """The wiki-text of the page. This will retrieve the page if it has not been retrieved yet. This can raise the following exceptions that should be caught by the calling code: | |
if text.startswith('\r\n'): | if text and text.startswith('\r\n'): | def removeLanguageLinks(text): """Given the wiki-text of a page, return that page with all interwiki links removed. If a link to an unknown language is encountered, a warning is printed.""" for code in langs: text=re.sub(r'\[\['+code+':([^\]]*)\]\]', '', text) m=re.search(r'\[\[([a-z][a-z]):([^\]]*)\]\]', text) if m: p... |
elif text.startswith(' '): | elif text and text.startswith(' '): | def removeLanguageLinks(text): """Given the wiki-text of a page, return that page with all interwiki links removed. If a link to an unknown language is encountered, a warning is printed.""" for code in langs: text=re.sub(r'\[\['+code+':([^\]]*)\]\]', '', text) m=re.search(r'\[\[([a-z][a-z]):([^\]]*)\]\]', text) if m: p... |
if text[-1:] in '\r\n \t': | if text and text[-1:] in '\r\n \t': | def removeLanguageLinks(text): """Given the wiki-text of a page, return that page with all interwiki links removed. If a link to an unknown language is encountered, a warning is printed.""" for code in langs: text=re.sub(r'\[\['+code+':([^\]]*)\]\]', '', text) m=re.search(r'\[\[([a-z][a-z]):([^\]]*)\]\]', text) if m: p... |
templateRegex = re.compile(r'\{\{([mM][sS][gG]:)?' + templateName + '(?P<parameters>\|[^}]+|)}}') | templateRegex = re.compile(r'\{\{ *([mM][sS][gG]:)?' + templateName + ' *(?P<parameters>\|[^}]+|) *}}') | def __iter__(self): """ Yield page objects until the entire XML dump has been read. """ import xmlreader mysite = wikipedia.getSite() dump = xmlreader.XmlDump(self.xmlfilename) # regular expression to find the original template. # {{vfd}} does the same thing as {{Vfd}}, so both will be found. # The old syntax, {{msg:vf... |
allTemplates = (', ').join(old) | if isinstance(self.old, list): allTemplates = (', ').join(old) else: allTemplates = old | def __init__(self, generator, old, new = None, remove = False, editSummary = '', acceptAll = False, extras = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want to subs... |
templateRegex = re.compile(r'\{\{([mM][sS][gG]:)?' + old + '(?P<parameters>\|[^}]+|)}}') | templateRegex = re.compile(r'\{\{ *(?:[Tt]emplate:|[mM][sS][gG]:)?' + old + ' *(?P<parameters>\|[^}]+|) *}}') | def run(self): """ Starts the robot's action. """ # regular expression to find the original template. # {{vfd}} does the same thing as {{Vfd}}, so both will be found. # The old syntax, {{msg:vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. |
def __init__(self, oldCatTitle, newCatTitle, batchMode = False, editSummary = '', inPlace = False): | def __init__(self, oldCatTitle, newCatTitle, batchMode = False, editSummary = '', inPlace = False, moveCatPage = True): | def __init__(self, oldCatTitle, newCatTitle, batchMode = False, editSummary = '', inPlace = False): self.editSummary = editSummary self.inPlace = inPlace self.oldCat = catlib.Category(wikipedia.getSite(), 'Category:' + oldCatTitle) self.newCatTitle = newCatTitle # set edit summary message |
catlib.change_category(article, self.oldCat, newCat, inPlace=inPlace) | catlib.change_category(article, self.oldCat, newCat, inPlace=self.inPlace) | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat, inPlace=inPl... |
if self.oldCat.exists(): | if self.oldCat.exists() and self.moveCatPage: | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat, inPlace=inPl... |
if self.oldCat.copyAndKeep(newCatTitle, wikipedia.translate(wikipedia.getSite(), cfd_templates)): | if self.oldCat.copyAndKeep(self.newCatTitle, wikipedia.translate(wikipedia.getSite(), cfd_templates)): | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat, inPlace=inPl... |
reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % newCatTitle | reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % self.newCatTitle | def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat, inPlace=inPl... |
m = re.search("== *%s *==" % section, text) | m = re.search("== *%s *==" % re.escape(section), text) | def oneDone(self, entry): title = entry.title username = entry.username ipedit = entry.ipedit timestamp = entry.timestamp text = entry.text editRestriction = entry.editRestriction moveRestriction = entry.moveRestriction pl = Page(self.site, title) for pl2 in self.pages: if pl2.sectionFreeTitle() == pl.sectionFreeTitle(... |
'et': u'Kasuteju', | 'et': u'Kasutaja', | def __init__(self): |
'es': u'Imagen_Discusión', | 'es': u'Imagen Discusión', | def __init__(self): |
'pt': u'Predefinição_Discussão', | 'pt': u'Predefinição Discussão', | def __init__(self): |
'pt': u'Ajuda_Discussão', | 'pt': u'Ajuda Discussão', | def __init__(self): |
imagelist = [] | def main(): # if -file is not used, this temporary array is used to read the page title. pageTitle = [] page = None gen = None imagelist = [] interwiki = False for arg in sys.argv[1:]: #for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'imagetransfer') if arg: if arg == '-interwiki': interwiki = True elif arg.s... | |
bot = ImageTransferBot(gen, interwiki = interwiki) | if not targetLang and not targetFamily: targetSite = wikipedia.getSite('commons', 'commons') else: if not targetLang: targetLang = wikipedia.getSite().language if not targetFamily: targetFamily = wikipedia.getSite().family targetSite = wikipedia.Site(targetLang, targetFamily) bot = ImageTransferBot(gen, interwiki = in... | def main(): # if -file is not used, this temporary array is used to read the page title. pageTitle = [] page = None gen = None imagelist = [] interwiki = False for arg in sys.argv[1:]: #for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'imagetransfer') if arg: if arg == '-interwiki': interwiki = True elif arg.s... |
description = wikipedia.unicode2html(description, wikipedia.code2encoding(wikipedia.mylang)) | try: description = description.encode(wikipedia.code2encoding(wikipedia.mylang)) except UnicodeEncodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.code2encoding(wikipedia.mylang)) except UnicodeDecodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.code2e... | def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi... |
fixedSites += ' ' + page_title | fixedSites += ' ' + article | def treat(page_title, site = None): ''' Loads a page, converts all HTML tables in its text to wiki syntax, and saves the converted text. Returns True if the converted table was successfully saved, otherwise returns False. ''' if site is None: site = wikipedia.getSite() pl = wikipedia.PageLink(site, page_title) try: tex... |
notFixedSites += ' ' + page_title | notFixedSites += ' ' + article | def treat(page_title, site = None): ''' Loads a page, converts all HTML tables in its text to wiki syntax, and saves the converted text. Returns True if the converted table was successfully saved, otherwise returns False. ''' if site is None: site = wikipedia.getSite() pl = wikipedia.PageLink(site, page_title) try: tex... |
def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): | def __init__(self, generator, old, new = None, remove = False, editSummary = '', acceptAll = False): | def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want ... |
self.customSummary = customSummary | def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want ... | |
if self.customSummary: | if self.editSummary: | def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want ... |
customSummary = False | def main(): template_names = [] resolve = False remove = False namespaces = [] customSummary = False editSummary = '' acceptAll = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in wikipedia.handleArgs(): if arg == '-remo... | |
customSummary = True | def main(): template_names = [] resolve = False remove = False namespaces = [] customSummary = False editSummary = '' acceptAll = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in wikipedia.handleArgs(): if arg == '-remo... | |
if namespaces != []: | if namespaces: | def main(): template_names = [] resolve = False remove = False namespaces = [] customSummary = False editSummary = '' acceptAll = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in wikipedia.handleArgs(): if arg == '-remo... |
bot = TemplateRobot(preloadingGen, old, new, remove, customSummary, editSummary, acceptAll) | bot = TemplateRobot(preloadingGen, old, new, remove, editSummary, acceptAll) | def main(): template_names = [] resolve = False remove = False namespaces = [] customSummary = False editSummary = '' acceptAll = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in wikipedia.handleArgs(): if arg == '-remo... |
self._add(l,i) | l = self._add(l,i) | def _addall(self,l1,l2): l=l1 for i in l2: self._add(l,i) return l |
family.Family.__init__(self) | def __init__(self): | |
family.Family.__init__(self) | def __init__(self): | |
displayedText = text[max(0, m.start() - context):m.end()+context] displayedText = displayedText[:context] + '\x1b[91;1m' + displayedText[context:] | def treat(refpl, thispl): """ Parameters: thispl - The disambiguation page or redirect we don't want anything to link on refpl - A page linking to thispl Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ try: include = False text=refpl.get(throttle=False) include = True ex... | |
displayedText = displayedText[:-context] + '\x1b[0m' + displayedText[-context:] | displayedText = text[max(0, m.start() - context):m.start()] + '\x1b[91;1m' + text[m.start():m.end()] + '\x1b[0m' + text[m.end():m.end()+context] | def treat(refpl, thispl): """ Parameters: thispl - The disambiguation page or redirect we don't want anything to link on refpl - A page linking to thispl Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ try: include = False text=refpl.get(throttle=False) include = True ex... |
whereClause = ' OR '.join(["old_text RLIKE '%s'" % old.pattern for (old, new) in replacements]) query = u"""SELECT page_namespace, page_title FROM page JOIN text ON (page_id = old_id) WHERE %s LIMIT 20""" % whereClause | whereClause = 'WHERE (%s)' % ' OR '.join(["old_text RLIKE '%s'" % prepareRegexForMySQL(old.pattern) for (old, new) in replacements]) if exceptions: exceptClause = 'AND NOT (%s)' % ' OR '.join(["old_text RLIKE '%s'" % prepareRegexForMySQL(exc.pattern) for exc in exceptions]) else: exceptClause = '' query = u""" SELECT p... | def main(): gen = None # How we want to retrieve information on which pages need to be changed. # Can either be 'xmldump', 'textfile' or 'userinput'. source = None # Array which will collect commandline parameters. # First element is original text, second element is replacement text. commandline_replacements = [] # A l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.