Commit c7ea3759 authored by François Kneib's avatar François Kneib Committed by Janek Kozicki

Apply futurize stage1 without unicode_literals

parent 1f29aa22
from __future__ import print_function
#!${pyExecutable}
# encoding: utf-8
# syntax:python
......@@ -16,7 +17,7 @@ except ImportError:
sys.path.insert(1,'${runtimePREFIX}/${LIBRARY_OUTPUT_PATH}/yade${SUFFIX}/py')
# get yade path (allow YADE_PREFIX to override)
prefix,suffix='${runtimePREFIX}' if not os.environ.has_key('YADE_PREFIX') else os.environ['YADE_PREFIX'],'${SUFFIX}'
prefix,suffix='${runtimePREFIX}' if 'YADE_PREFIX' not in os.environ else os.environ['YADE_PREFIX'],'${SUFFIX}'
# duplicate some items from yade.config here, so that we can increase verbosity when the c++ part is booting
features,version,debugbuild='${CONFIGURED_FEATS}'.split(' '),'${realVersion}',' ${debugbuild}'
......@@ -65,15 +66,15 @@ args = opts.args
if opts.impLibraries:
sys.path.append('.')
for lib in opts.impLibraries:
print "\n------------------------ IMPORTING ------------------------"
print("\n------------------------ IMPORTING ------------------------")
# see also https://gitlab.com/yade-dev/trunk/issues/18
print "library:", lib, "\n"
print("library:", lib, "\n")
import importlib
importlib.import_module(str(lib))
#__import__(lib)
if opts.version:
print 'Yade version: %s%s'%(version,debugbuild)
print('Yade version: %s%s'%(version,debugbuild))
sys.exit(0)
if opts.script:
......@@ -95,28 +96,28 @@ if opts.test:
try:
result=yade.tests.testAll()
except:
print 20*'*'+' UNEXPECTED EXCEPTION WHILE RUNNING TESTS '+20*'*'
print 20*'*'+' '+str(sys.exc_info()[0])
print 20*'*'+" Please report bug at https://gitlab.com/yade-dev/trunk/issues providing the following traceback:"
print(20*'*'+' UNEXPECTED EXCEPTION WHILE RUNNING TESTS '+20*'*')
print(20*'*'+' '+str(sys.exc_info()[0]))
print(20*'*'+" Please report bug at https://gitlab.com/yade-dev/trunk/issues providing the following traceback:")
import traceback; traceback.print_exc()
print 20*'*'+' Thank you '+20*'*'
print(20*'*'+' Thank you '+20*'*')
sys.exit(2)
if (os.path.exists('./DirSearchYade')): os.remove('./DirSearchYade')
if (os.path.exists('./MicroMacroAnalysis')): os.remove('./MicroMacroAnalysis')
if result.wasSuccessful():
print "*** ALL TESTS PASSED ***"
print("*** ALL TESTS PASSED ***")
sys.exit(0)
else:
print 20*'*'+' SOME TESTS FAILED '+20*'*'
print(20*'*'+' SOME TESTS FAILED '+20*'*')
sys.exit(1)
if not 'OpenMP' in features and (opts.cores or (opts.threads and opts.threads>1)):
print 'WARNING: compiled without OpenMP, -j/--threads/--cores have no effect.'
print('WARNING: compiled without OpenMP, -j/--threads/--cores have no effect.')
# OpenMP env variables must be set before loading yade libs ("import yade" below)
# changes have no effect after libgomp initializes
if opts.cores:
if opts.threads: print 'WARNING: --threads ignored, since --cores specified.'
if opts.threads: print('WARNING: --threads ignored, since --cores specified.')
try:
cores=[int(i) for i in opts.cores.split(',')]
except ValueError:
......@@ -172,7 +173,7 @@ def userSession(gui='none',qapp=None):
# common ipython configuration
# use standard terminal color codes to make F12, F11 bold, and underline the word "help", see https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
banner='[[ ^L clears screen, ^U kills line. '+', '.join((['\033[1mF12\033[0m controller','\033[1mF11\033[0m 3D view (press \033[4m"h"\033[0m in 3D view for \033[4mhelp\033[0m)','\033[1mF10\033[0m both','\033[1mF9\033[0m generator'] if (gui<>'none') else [])+['\033[1mF8\033[0m plot'])+'. ]]'
banner='[[ ^L clears screen, ^U kills line. '+', '.join((['\033[1mF12\033[0m controller','\033[1mF11\033[0m 3D view (press \033[4m"h"\033[0m in 3D view for \033[4mhelp\033[0m)','\033[1mF10\033[0m both','\033[1mF9\033[0m generator'] if (gui!='none') else [])+['\033[1mF8\033[0m plot'])+'. ]]'
ipconfig=dict( # ipython options, see e.g. http://www.cv.nrao.edu/~rreid/casa/tips/ipy_user_conf.py
prompt_in1='Yade [\#]: ',
prompt_in2=' .\D.: ',
......@@ -183,7 +184,7 @@ def userSession(gui='none',qapp=None):
'tab: complete',
# only with the gui; the escape codes might not work on non-linux terminals.
]
+(['"\e[24~": "\C-Uyade.qt.Controller();\C-M"','"\e[23~": "\C-Uyade.qt.View();\C-M"','"\e[21~": "\C-Uyade.qt.Controller(), yade.qt.View();\C-M"','"\e[20~": "\C-Uyade.qt.Generator();\C-M"'] if (gui<>'none') else []) #F12,F11,F10,F9
+(['"\e[24~": "\C-Uyade.qt.Controller();\C-M"','"\e[23~": "\C-Uyade.qt.View();\C-M"','"\e[21~": "\C-Uyade.qt.Controller(), yade.qt.View();\C-M"','"\e[20~": "\C-Uyade.qt.Generator();\C-M"'] if (gui!='none') else []) #F12,F11,F10,F9
+['"\e[19~": "\C-Uimport yade.plot; yade.plot.plot();\C-M"', #F8
'"\e[A": history-search-backward', '"\e[B": history-search-forward', # incremental history forward/backward
]
......@@ -243,26 +244,26 @@ def userSession(gui='none',qapp=None):
try:
yade.qt.Controller()
except Exception as e:
print e
print(e)
@registry.add_binding(Keys.F11, eager=True)
def invokeView_(event):
try:
yade.qt.View()
except Exception as e:
print e
print(e)
@registry.add_binding(Keys.F10, eager=True)
def invokeBoth_(event):
try:
yade.qt.View()
yade.qt.Controller()
except Exception as e:
print e
print(e)
@registry.add_binding(Keys.F9, eager=True)
def invokeGenerator_(event):
try:
yade.qt.Generator()
except Exception as e:
print e
print(e)
@registry.add_binding(Keys.F8, eager=True)
def invokeGenerator_(event):
try:
......@@ -282,7 +283,7 @@ def userSession(gui='none',qapp=None):
# IPython.appstart_qt4(qapp)
if len(sys.argv)>0:
arg0=sys.argv[0]
if (gui<>'none'): yade.qt.Controller();
if (gui!='none'): yade.qt.Controller();
if sum(bool(arg0.endswith(ext)) for ext in ('.xml','.xml.bz2','.xml.gz','.yade','.yade.gz','.yade.bz2','.bin','.bin.gz','.bin.bz2'))>0:
if len(sys.argv)>1: raise RuntimeError('Extra arguments to saved simulation to run: '+' '.join(sys.argv[1:]))
sys.stderr.write("Running simulation "+arg0+'\n')
......@@ -321,7 +322,7 @@ if gui:
# usually Xlib.error.DisplayError, but there can be Xlib.error.XauthError etc as well
# let's just pretend any exception means the display would not work
gui=None
print 'Warning: no X rendering available (see https://bbs.archlinux.org/viewtopic.php?id=13189)'
print('Warning: no X rendering available (see https://bbs.archlinux.org/viewtopic.php?id=13189)')
# run remote access things, before actually starting the user session (not while imported by other python application)
if __name__ == "__main__":
......
from __future__ import print_function
#!${pyExecutable}
# encoding: utf-8
#
......@@ -16,7 +17,7 @@ sys.path.insert(1,'${runtimePREFIX}/${LIBRARY_OUTPUT_PATH}/yade${SUFFIX}/py')
#socket.setdefaulttimeout(10)
## replaced by scons automatically
prefix,suffix='${runtimePREFIX}' if not os.environ.has_key('YADE_PREFIX') else os.environ['YADE_PREFIX'],'${SUFFIX}'
prefix,suffix='${runtimePREFIX}' if 'YADE_PREFIX' not in os.environ else os.environ['YADE_PREFIX'],'${SUFFIX}'
libPATH='${LIBRARY_OUTPUT_PATH}'
if (libPATH[1:] == '{LIBRARY_OUTPUT_PATH}'): libPATH='lib'
......@@ -259,18 +260,18 @@ def runHttpStatsServer():
try:
server=HTTPServer(('',port),HttpStatsServer)
import thread; thread.start_new_thread(server.serve_forever,())
print "http://localhost:%d shows batch summary"%port
print("http://localhost:%d shows batch summary"%port)
break
except socket.error:
port+=1
if port==maxPort:
print "WARN: No free port in range 9080-11000, not starting HTTP stats server!"
print("WARN: No free port in range 9080-11000, not starting HTTP stats server!")
def runJob(job):
job.status='RUNNING'
job.started=time.time();
print '#%d (%s%s%s) started on %s'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores,(' ['+','.join([str(c) for c in job.cores])+']') if job.cores else '',time.asctime())
print('#%d (%s%s%s) started on %s'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores,(' ['+','.join([str(c) for c in job.cores])+']') if job.cores else '',time.asctime()))
#print '#%d cores',%(job.num,job.cores)
if job.cores:
def coresReplace(s): return s.replace('[threadspec]','--cores=%s'%(','.join(str(c) for c in job.cores)))
......@@ -292,7 +293,7 @@ def runJob(job):
shutil.copy(job.plotsFile,f)
job.plotsFile=f
havePlot=True
print "#%d (%s%s) %s (exit status %d), duration %s, log %s%s"%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores,strStatus,job.exitStatus,job.duration,job.log,(', plot %s'%(job.plotsFile) if havePlot else ''))
print("#%d (%s%s) %s (exit status %d), duration %s, log %s%s"%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores,strStatus,job.exitStatus,job.duration,job.log,(', plot %s'%(job.plotsFile) if havePlot else '')))
job.saveInfo()
def runJobs(jobs,numCores):
......@@ -333,10 +334,10 @@ def getNumCores():
try:
nCpu=len([l for l in open('/proc/cpuinfo','r') if l.find('processor')==0])
except:
print 'WARNING: No cpuinfo available! Setting the maximal number of processors 1'
print('WARNING: No cpuinfo available! Setting the maximal number of processors 1')
pass
if os.environ.has_key("OMP_NUM_THREADS"): return min(int(os.environ['OMP_NUM_THREADS']),nCpu)
if "OMP_NUM_THREADS" in os.environ: return min(int(os.environ['OMP_NUM_THREADS']),nCpu)
return nCpu
numCores=getNumCores()
maxOmpThreads=numCores if 'OpenMP' in yade.config.features else 1
......@@ -374,19 +375,19 @@ args = opts.args
logFormat,lineList,maxJobs,nice,executable,gnuplotOut,dryRun,httpWait,globalLog=opts.logFormat,opts.lineList,opts.maxJobs,opts.nice,opts.executable,opts.gnuplotOut,opts.dryRun,opts.httpWait,opts.globalLog
if opts.impLibraries:
print "\n\n ------------------------ IMPORTING ---------------------------------------\n\n"
print("\n\n ------------------------ IMPORTING ---------------------------------------\n\n")
sys.path.append('.')
for lib in opts.impLibraries:
print "\n\n ------------------------ IMPORTING ---------------------------------------\n\n"
print lib
print("\n\n ------------------------ IMPORTING ---------------------------------------\n\n")
print(lib)
__import__(lib)
if opts.version:
print 'Yade version: %s, features: %s'%(version,','.join(features))
print('Yade version: %s, features: %s'%(version,','.join(features)))
sys.exit(0)
if globalLog:
print 'Redirecting all output to',globalLog
print('Redirecting all output to',globalLog)
sys.stderr=open(globalLog,"w")
sys.stdout=sys.stderr
......@@ -414,14 +415,14 @@ if not opts.disablePynotify:
except Exception:
pynotifyAvailable = False
print "Will run simulation(s) %s using `%s', nice value %d, using max %d cores."%(scripts,executable,nice,maxJobs)
print("Will run simulation(s) %s using `%s', nice value %d, using max %d cores."%(scripts,executable,nice,maxJobs))
if table:
reader=yade.utils.TableParamReader(table)
params=reader.paramDict()
availableLines=params.keys()
print "Will use table `%s', with available lines"%(table),', '.join([str(i) for i in availableLines])+'.'
print("Will use table `%s', with available lines"%(table),', '.join([str(i) for i in availableLines])+'.')
if lineList:
useLines=[]
......@@ -436,9 +437,9 @@ if table:
if l not in availableLines: logging.warn('Skipping unavailable line %d that was requested from the command line.'%l)
else: useLines+=[l]
else: useLines=availableLines
print "Will use lines ",', '.join([str(i)+' (%s)'%params[i]['description'] for i in useLines])+'.'
print("Will use lines ",', '.join([str(i)+' (%s)'%params[i]['description'] for i in useLines])+'.')
else:
print "Running %d stand-alone simulation(s) in batch mode."%(len(scripts))
print("Running %d stand-alone simulation(s) in batch mode."%(len(scripts)))
useLines=[]
params={}
for i,s in enumerate(scripts):
......@@ -507,11 +508,11 @@ for i,l in enumerate(useLines):
if opts.timing>0: desc+='[%d]'%j
jobs.append(JobInfo(jobNum,desc,fullCmd,hrefCmd,logFile2,nCores,script=script,table=table,lineNo=l,affinity=jobAffinity))
print "Master process pid",os.getpid()
print("Master process pid",os.getpid())
print "Job summary:"
print("Job summary:")
for job in jobs:
print ' #%d (%s%s):'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores),job.command
print(' #%d (%s%s):'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores),job.command)
sys.stdout.flush()
......@@ -527,28 +528,28 @@ if opts.plotAlwaysUpdateTime>0:
# OK, go now
if not dryRun: runJobs(jobs,maxJobs)
print 'All jobs finished, total time ',t2hhmmss(totalRunningTime())
print('All jobs finished, total time ',t2hhmmss(totalRunningTime()))
plots=[]
for j in jobs:
if not os.path.exists(j.plotsFile): continue
plots.append(j.plotsFile)
if plots: print 'Plot files:',' '.join(plots)
if plots: print('Plot files:',' '.join(plots))
# for easy grepping in logfiles:
print 'Log files:',' '.join([j.log for j in jobs])
print('Log files:',' '.join([j.log for j in jobs]))
# write timing table
if opts.timing>0:
if opts.timingOut:
print 'Writing gathered timing information to',opts.timingOut
print('Writing gathered timing information to',opts.timingOut)
try:
out=open(opts.timingOut,'w')
except IOError:
logging.warn('Unable to open file %s for timing output, writing to stdout.'%opts.timingOut)
out=sys.stdout
else:
print 'Gathered timing information:'
print('Gathered timing information:')
out=sys.stdout
# write header
out.write('## timing data, written '+time.asctime()+' with arguments\n## '+' '.join(sys.argv)+'\n##\n')
......@@ -564,9 +565,9 @@ if opts.timing>0:
out.write('%d\t%d\t%.2f\t%.2f\t%.3g\t%.2f\t%.2f\t|\t'%(l,len(jobTimes),tAvg,tDev,tRelDev,tMin,tMax)+'\t'.join([params[l][p] for p in paramNames])+'\n')
if not gnuplotOut:
print 'Bye.'
print('Bye.')
else:
print 'Assembling gnuplot files…'
print('Assembling gnuplot files…')
for job in jobs:
for l in file(job.log):
if l.startswith('gnuplot '):
......@@ -575,7 +576,7 @@ else:
preamble,plots='',[]
for job in jobs:
if not 'plot' in job.__dict__:
print "WARN: No plot found for job "+job.id
print("WARN: No plot found for job "+job.id)
continue
for l in file(job.plot):
if l.startswith('plot'):
......@@ -592,10 +593,10 @@ else:
gp=file(gnuplotOut,'w')
gp.write(preamble)
gp.write('plot '+','.join(plots))
print "gnuplot",gnuplotOut
print "Plot written, bye."
print("gnuplot",gnuplotOut)
print("Plot written, bye.")
if httpWait and time.time()-httpLastServe<30:
print "(continue serving http until no longer requested as per --http-wait)"
print("(continue serving http until no longer requested as per --http-wait)")
while time.time()-httpLastServe<30:
time.sleep(1)
......
from __future__ import print_function
#!${pyExecutable}
# encoding: utf-8
#
......@@ -20,7 +21,7 @@ import os, sys, thread, time, logging, pipes, socket, xmlrpclib, re, shutil, ran
# Setup executable
## replaced by scons automatically
prefix,suffix='${runtimePREFIX}' if not os.environ.has_key('YADE_PREFIX') else os.environ['YADE_PREFIX'],'${SUFFIX}'
prefix,suffix='${runtimePREFIX}' if 'YADE_PREFIX' not in os.environ else os.environ['YADE_PREFIX'],'${SUFFIX}'
libPATH='${LIBRARY_OUTPUT_PATH}'
if (libPATH[1:] == '{LIBRARY_OUTPUT_PATH}'): libPATH='lib'
......@@ -88,11 +89,11 @@ args = opts.args
logFormat,lineList,nice,executable,dryRun,globalLog,project, walltime=opts.logFormat,opts.lineList,opts.nice,opts.executable,opts.dryRun,opts.globalLog,opts.oar_p,opts.oar_t
if opts.version:
print 'Yade version: %s, features: %s'%(version,','.join(features))
print('Yade version: %s, features: %s'%(version,','.join(features)))
sys.exit(0)
if globalLog:
print 'Redirecting all output to',globalLog
print('Redirecting all output to',globalLog)
sys.stderr=open(globalLog,"w")
sys.stdout=sys.stderr
......@@ -108,7 +109,7 @@ else:
sys.exit(1)
if opts.oar_script == '' :
print '--oar_script is mandatory';
print('--oar_script is mandatory');
sys.exit(1);
pynotifyAvailable = False
......@@ -121,14 +122,14 @@ if not opts.disablePynotify:
except ImportError:
pynotifyAvailable = False
print "Will run simulation(s) %s using `%s', nice value %d"%(scripts,executable,nice)
print("Will run simulation(s) %s using `%s', nice value %d"%(scripts,executable,nice))
if table:
reader=yade.utils.TableParamReader(table)
params=reader.paramDict()
availableLines=params.keys()
print "Will use table `%s', with available lines"%(table),', '.join([str(i) for i in availableLines])+'.'
print("Will use table `%s', with available lines"%(table),', '.join([str(i) for i in availableLines])+'.')
if lineList:
useLines=[]
......@@ -143,9 +144,9 @@ if table:
if l not in availableLines: logging.warn('Skipping unavailable line %d that was requested from the command line.'%l)
else: useLines+=[l]
else: useLines=availableLines
print "Will use lines ",',\n '.join([str(i)+' (%s)'%params[i]['description'] for i in useLines])+'.'
print("Will use lines ",',\n '.join([str(i)+' (%s)'%params[i]['description'] for i in useLines])+'.')
else:
print "Running %d stand-alone simulation(s) in batch mode."%(len(scripts))
print("Running %d stand-alone simulation(s) in batch mode."%(len(scripts)))
useLines=[]
params={}
for i,s in enumerate(scripts):
......@@ -209,10 +210,10 @@ for i,l in enumerate(useLines):
if not os.path.exists('tmp/'+str(os.getpid())):
os.makedirs('tmp/'+str(os.getpid()));
print "Job summary:"
print("Job summary:")
i = 0
for job in jobs:
print ' #%d (%s%s):'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores),job.command
print(' #%d (%s%s):'%(job.num,job.id,'' if job.nCores==1 else '/%d'%job.nCores),job.command)
if not dryRun:
# Create script file from model
scriptname = 'tmp/'+str(os.getpid())+'/'+opts.oar_script.split('/')[-1]+'.'+str(i)
......@@ -236,7 +237,7 @@ for job in jobs:
prop+=' -t besteffort'
os.chmod(scriptname,0744);
os.chmod(scriptname,0o744);
#os.system('%s'%(scriptname));
os.system('oarsub --project=%s %s -l/cpu=1/core=%i,walltime=%s -O %s -E %s.err %s\n'%(project, prop, job.nCores, walltime, job.log,job.log,scriptname));
......
#!/usr/bin/python
# encoding: utf-8
from __future__ import print_function
try:
import _bibtex as bib
import _recode as bibRecode
......@@ -27,7 +28,7 @@ def readBib(filename):
def dumpBib(db):
for k in db.keys():
print k,db[k]
print(k,db[k])
def formatRest(db):
ret=[]
......@@ -35,52 +36,52 @@ def formatRest(db):
for key in keys:
i=db[key]; type=i['type']
line=r'.. [%s] \ '%key ## ← HACK: explicit space to prevent docutils from using abbreviated first name (e.g. "F.") as enumeration item; it works!!
if i.has_key('author'): author=i['author'].replace(' and ',', ') # the module does not handle this..?
if 'author' in i: author=i['author'].replace(' and ',', ') # the module does not handle this..?
# required fields from http://en.wikipedia.org/wiki/Bibtex
# in some cases, they are not present, anyway
if type=='article':
if i.has_key('author'): line+='%s '%author
if i.has_key('year'): line+='(%s), '%i['year']
if 'author' in i: line+='%s '%author
if 'year' in i: line+='(%s), '%i['year']
line+='**%s**. *%s*'%(i['title'],i['journal'])
if i.has_key('issue'): line+=' %s'%i['issue']
if i.has_key('volume'): line+=' (%s)'%i['volume']
if i.has_key('pages'): line+=', pages %s'%i['pages']
if 'issue' in i: line+=' %s'%i['issue']
if 'volume' in i: line+=' (%s)'%i['volume']
if 'pages' in i: line+=', pages %s'%i['pages']
line+='.'
elif type=='book':
if i.has_key('author'): line+='%s '%author
if i.has_key('year'): line+='(%s), '%i['year']
if 'author' in i: line+='%s '%author
if 'year' in i: line+='(%s), '%i['year']
line+='**%s**.'%i['title']
if i.has_key('publisher'): line+=' %s.'%i['publisher']
if 'publisher' in i: line+=' %s.'%i['publisher']
elif type=='inproceedings':
line+='%s (%s), **%s**. In *%s*.'%(author,i['year'],i['title'],i['booktitle'] if i.has_key('booktitle') else i['journal'])
line+='%s (%s), **%s**. In *%s*.'%(author,i['year'],i['title'],i['booktitle'] if 'booktitle' in i else i['journal'])
elif type=='incollection':
line+='%s (%s), **%s**. In *%s* '%(author,i['year'],i['title'],i['booktitle'] if i.has_key('booktitle') else i['journal'])
if i.has_key('editor'): line+='( %s'%i['editor']+', ed.),'
if i.has_key('publisher'): line+=' %s'%i['publisher']+' ,'
if i.has_key('edition'): line+=' %s ed.'%i['edition']
line+='%s (%s), **%s**. In *%s* '%(author,i['year'],i['title'],i['booktitle'] if 'booktitle' in i else i['journal'])
if 'editor' in i: line+='( %s'%i['editor']+', ed.),'
if 'publisher' in i: line+=' %s'%i['publisher']+' ,'
if 'edition' in i: line+=' %s ed.'%i['edition']
elif type=='phdthesis':
line+='%s (%s), **%s**. PhD thesis at *%s*.'%(author,i['year'],i['title'],i['school'])
elif type=='mastersthesis':
typeThesis = 'Master thesis'
if i.has_key('note'):
if 'note' in i:
typeThesis = i['note']
line+='%s (%s), **%s**. %s at *%s*.'%(author,i['year'],i['title'],typeThesis,i['school'])
elif type=='proceedings':
if i.has_key('editor'): line+='%s (ed.), '%i['editor']
if 'editor' in i: line+='%s (ed.), '%i['editor']
line+='**%s** (%s).'%(i['title'],i['year'])
if i.has_key('organization'): line+=' *%s*.'%i['organization']
if i.has_key('publisher'): line+=' %s'%i['publisher']
if 'organization' in i: line+=' *%s*.'%i['organization']
if 'publisher' in i: line+=' %s'%i['publisher']
elif type=='misc':
if i.has_key('author'): line+=author
if i.has_key('year'): line+=' %s'%i['year']
if i.has_key('title'): line+=' **%s**'%i['title']
if 'author' in i: line+=author
if 'year' in i: line+=' %s'%i['year']
if 'title' in i: line+=' **%s**'%i['title']
# add doi and url to everything, if present
## ReST uses <..> to delimit URL, therefore < and > must be encoded in the URL (http://www.blooberry.com/indexdot/html/topics/urlencoding.htm)
def escapeUrl(url): return url.replace('<','%3c').replace('>','%3e')
if i.has_key('doi'): line+=' DOI `%s <http://dx.doi.org/%s>`_'%(i['doi'],escapeUrl(i['doi']))
if i.has_key('url'): line+=' `(fulltext) <%s>`__'%escapeUrl(i['url'])
if (i.has_key('note') and type<>'mastersthesis'): line+=' (%s)'%i['note']
if 'doi' in i: line+=' DOI `%s <http://dx.doi.org/%s>`_'%(i['doi'],escapeUrl(i['doi']))
if 'url' in i: line+=' `(fulltext) <%s>`__'%escapeUrl(i['url'])
if ('note' in i and type!='mastersthesis'): line+=' (%s)'%i['note']
ret.append(line)
return [l.replace('@tilde@','~') for l in ret]
......@@ -95,4 +96,4 @@ def bib2rst(filename):
return '\n\n'.join(formatRest(db))
if __name__=='__main__':
import sys
print bib2rst(sys.argv[1])
print(bib2rst(sys.argv[1]))
......@@ -21,6 +21,7 @@
##
## http://docutils.sourceforge.net/docs/howto/rst-roles.html
from __future__ import print_function
import sys, os, re
from docutils import nodes
from sphinx import addnodes
......@@ -76,7 +77,7 @@ moduleMap={
class YadeXRefRole(XRefRole):
#def process_link
def process_link(self, env, refnode, has_explicit_title, title, target):
print 'TARGET:','yade.wrapper.'+target
print('TARGET:','yade.wrapper.'+target)
return '[['+title+']]','yade.wrapper.'+target
def mkYrefNode(target,text,rawtext,role,explicitText,lineno,options={}):
......@@ -233,11 +234,11 @@ def boostFuncSignature(name,obj,removeSelf=False):
strippedDoc[i],n=re.subn(r'([a-zA-Z_][a-zA-Z0-9_]*\() \(object\)arg1(, |)',r'\1',strippedDoc[i].replace('->','→'))
# inspect dosctring after mangling
if 'getViscoelasticFromSpheresInteraction' in name and False:
print name
print strippedDoc
print '======================'
for l in strippedDoc: print l
print '======================'
print(name)
print(strippedDoc)
print('======================')
for l in strippedDoc: print(l)
print('======================')
sig=doc1.split('(',1)[1]
if removeSelf:
# remove up to the first comma; if no comma present, then the method takes no arguments
......@@ -307,7 +308,7 @@ from sphinx import addnodes
def parse_ystaticattr(env,attr,attrnode):
m=re.match(r'([a-zA-Z0-9_]+)\.(.*)\(=(.*)\)',attr)
if not m:
print 100*'@'+' Static attribute %s not matched'%attr
print(100*'@'+' Static attribute %s not matched'%attr)
attrnode+=addnodes.desc_name(attr,attr)
klass,name,default=m.groups()
#attrnode+=addnodes.desc_type('static','static')
......
......@@ -21,6 +21,7 @@
##
## http://docutils.sourceforge.net/docs/howto/rst-roles.html
from __future__ import print_function
import sys, os, re
from docutils import nodes
from sphinx import addnodes
......@@ -76,7 +77,7 @@ moduleMap={
class YadeXRefRole(XRefRole):
#def process_link
def process_link(self, env, refnode, has_explicit_title, title, target):
print 'TARGET:','yade.wrapper.'+target
print('TARGET:','yade.wrapper.'+target)
return '[['+title+']]','yade.wrapper.'+target
def mkYrefNode(target,text,rawtext,role,explicitText,lineno,options={}):
......@@ -226,11 +227,11 @@ def boostFuncSignature(name,obj,removeSelf=False):
strippedDoc[i],n=re.subn(r'([a-zA-Z_][a-zA-Z0-9_]*\() \(object\)arg1(, |)',r'\1',strippedDoc[i].replace('->','→'))
# inspect dosctring after mangling
if 'getViscoelasticFromSpheresInteraction' in name and False:
print name
print strippedDoc
print '======================'
for l in strippedDoc: print l
print '======================'
print(name)
print(strippedDoc)
print('======================')
for l in strippedDoc: print(l)
print('======================')
sig=doc1.split('(',1)[1]
if removeSelf:
# remove up to the first comma; if no comma present, then the method takes no arguments
......@@ -300,7 +301,7 @@ from sphinx import addnodes
def parse_ystaticattr(env,attr,attrnode):
m=re.match(r'([a-zA-Z0-9_]+)\.(.*)\(=(.*)\)',attr)
if not m:
print 100*'@'+' Static attribute %s not matched'%attr
print(100*'@'+' Static attribute %s not matched'%attr)
attrnode+=addnodes.desc_name(attr,attr)
klass,name,default=m.groups()
#attrnode+=addnodes.desc_type('static','static')
......
......@@ -21,6 +21,7 @@
##
## http://docutils.sourceforge.net/docs/howto/rst-roles.html
from __future__ import print_function