Merge pull request #7994 from nnadeau:master

Fixed exceptions, print statements, and long types for gen_pattern.py to be Python 3 compatible (#7994)

* fixed exceptions and print statements to be python 3 compatible; removed long type checks (py3 uses int); whitespace reformatting

* Pulled latest svgfig from upstream

f3179a8926
This commit is contained in:
Nicholas Nadeau 2017-01-16 05:03:49 -05:00 committed by Alexander Alekhin
parent 5b363df2ae
commit 256aa53326
2 changed files with 60 additions and 52 deletions

View File

@ -70,9 +70,9 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], "Ho:c:r:T:u:s:R:w:h:a:", ["help","output=","columns=","rows=",
"type=","units=","square_size=","radius_rate=",
"page_width=","page_height=", "page_size="])
except getopt.error, msg:
print msg
print "for help use --help"
except getopt.error as msg:
print(msg)
print("for help use --help")
sys.exit(2)
output = "out.svg"
columns = 8
@ -89,7 +89,7 @@ def main():
# process options
for o, a in opts:
if o in ("-H", "--help"):
print __doc__
print(__doc__)
sys.exit(0)
elif o in ("-r", "--rows"):
rows = int(a)

View File

@ -1,5 +1,3 @@
#!/usr/bin/env python
# svgfig.py copyright (C) 2008 Jim Pivarski <jpivarski@gmail.com>
#
# This program is free software; you can redistribute it and/or
@ -21,6 +19,15 @@
import re, codecs, os, platform, copy, itertools, math, cmath, random, sys, copy
_epsilon = 1e-5
if sys.version_info >= (3,0):
long = int
basestring = (str,bytes)
# Fix Python 2.x.
try:
UNICODE_EXISTS = bool(type(unicode))
except NameError:
unicode = lambda s: str(s)
if re.search("windows", platform.system(), re.I):
try:
@ -49,20 +56,21 @@ def rgb(r, g, b, maximum=1.):
max(0, min(b*255./maximum, 255)))
def attr_preprocess(attr):
attrCopy = attr.copy()
for name in attr.keys():
name_colon = re.sub("__", ":", name)
if name_colon != name:
attr[name_colon] = attr[name]
del attr[name]
attrCopy[name_colon] = attrCopy[name]
del attrCopy[name]
name = name_colon
name_dash = re.sub("_", "-", name)
if name_dash != name:
attr[name_dash] = attr[name]
del attr[name]
attrCopy[name_dash] = attrCopy[name]
del attrCopy[name]
name = name_dash
return attr
return attrCopy
class SVG:
@ -128,7 +136,7 @@ class SVG:
"""
def __init__(self, *t_sub, **attr):
if len(t_sub) == 0:
raise TypeError, "SVG element must have a t (SVG type)"
raise TypeError( "SVG element must have a t (SVG type)")
# first argument is t (SVG type)
self.t = t_sub[0]
@ -262,7 +270,7 @@ class SVG:
Returns a breadth-first generator over the SVG. If depth_limit
is a number, stop recursion at that depth."""
raise NotImplementedError, "Got an algorithm for breadth-first searching a tree without effectively copying the tree?"
raise NotImplementedError( "Got an algorithm for breadth-first searching a tree without effectively copying the tree?")
def __iter__(self):
return self.depth_first()
@ -558,7 +566,7 @@ def canvas_outline(*sub, **attr):
svg = canvas(*sub, **attr)
match = re.match(r"[, \t]*([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]*", svg["viewBox"])
if match is None:
raise ValueError, "canvas viewBox is incorrectly formatted"
raise ValueError( "canvas viewBox is incorrectly formatted")
x, y, width, height = [float(x) for x in match.groups()]
svg.prepend(SVG("rect", x=x, y=y, width=width, height=height, stroke="none", fill="cornsilk"))
svg.append(SVG("rect", x=x, y=y, width=width, height=height, stroke="black", fill="none"))
@ -675,7 +683,7 @@ def totrans(expr, vars=("x", "y"), globals=None, locals=None):
return output
else:
raise TypeError, "must be a function of 2 or 1 variables"
raise TypeError( "must be a function of 2 or 1 variables")
if len(vars) == 2:
g = math.__dict__
@ -696,7 +704,7 @@ def totrans(expr, vars=("x", "y"), globals=None, locals=None):
return output2
else:
raise TypeError, "vars must have 2 or 1 elements"
raise TypeError( "vars must have 2 or 1 elements")
def window(xmin, xmax, ymin, ymax, x=0, y=0, width=100, height=100,
@ -735,10 +743,10 @@ def window(xmin, xmax, ymin, ymax, x=0, y=0, width=100, height=100,
iy2 = ymax
if xlogbase is not None and (ix1 <= 0. or ix2 <= 0.):
raise ValueError, "x range incompatible with log scaling: (%g, %g)" % (ix1, ix2)
raise ValueError ("x range incompatible with log scaling: (%g, %g)" % (ix1, ix2))
if ylogbase is not None and (iy1 <= 0. or iy2 <= 0.):
raise ValueError, "y range incompatible with log scaling: (%g, %g)" % (iy1, iy2)
raise ValueError ("y range incompatible with log scaling: (%g, %g)" % (iy1, iy2))
def maybelog(t, it1, it2, ot1, ot2, logbase):
if t <= 0.:
@ -813,7 +821,7 @@ class Fig:
self.trans = kwds["trans"]; del kwds["trans"]
if len(kwds) != 0:
raise TypeError, "Fig() got unexpected keyword arguments %s" % kwds.keys()
raise TypeError ("Fig() got unexpected keyword arguments %s" % kwds.keys())
def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object.
@ -931,7 +939,7 @@ class Plot:
self.text_attr = kwds["text_attr"]; del kwds["text_attr"]
self.axis_attr = kwds["axis_attr"]; del kwds["axis_attr"]
if len(kwds) != 0:
raise TypeError, "Plot() got unexpected keyword arguments %s" % kwds.keys()
raise TypeError ("Plot() got unexpected keyword arguments %s" % kwds.keys())
def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object."""
@ -1039,7 +1047,7 @@ class Frame:
self.axis_attr.update(kwds["axis_attr"]); del kwds["axis_attr"]
if len(kwds) != 0:
raise TypeError, "Frame() got unexpected keyword arguments %s" % kwds.keys()
raise TypeError( "Frame() got unexpected keyword arguments %s" % kwds.keys())
def SVG(self):
"""Apply the window transformation and return an SVG object."""
@ -1101,7 +1109,7 @@ class Frame:
def pathtoPath(svg):
"""Converts SVG("path", d="...") into Path(d=[...])."""
if not isinstance(svg, SVG) or svg.t != "path":
raise TypeError, "Only SVG <path /> objects can be converted into Paths"
raise TypeError ("Only SVG <path /> objects can be converted into Paths")
attr = dict(svg.attr)
d = attr["d"]
del attr["d"]
@ -1235,7 +1243,7 @@ class Path:
errstring = "Path command \"%s\" requires a number at index %d" % (command, index)
num1, index, pathdata = self.parse_number(index, pathdata)
if num1 is None:
raise ValueError, errstring
raise ValueError ( errstring)
while num1 is not None:
output.append((command, num1))
@ -1248,11 +1256,11 @@ class Path:
num2, index, pathdata = self.parse_number(index, pathdata)
if num1 is None:
raise ValueError, errstring
raise ValueError ( errstring)
while num1 is not None:
if num2 is None:
raise ValueError, errstring
raise ValueError ( errstring)
output.append((command, num1, num2, False))
num1, index, pathdata = self.parse_number(index, pathdata)
@ -1267,11 +1275,11 @@ class Path:
num4, index, pathdata = self.parse_number(index, pathdata)
if num1 is None:
raise ValueError, errstring
raise ValueError ( errstring )
while num1 is not None:
if num2 is None or num3 is None or num4 is None:
raise ValueError, errstring
raise ValueError (errstring)
output.append((command, num1, num2, False, num3, num4, False))
num1, index, pathdata = self.parse_number(index, pathdata)
@ -1290,11 +1298,11 @@ class Path:
num6, index, pathdata = self.parse_number(index, pathdata)
if num1 is None:
raise ValueError, errstring
raise ValueError(errstring)
while num1 is not None:
if num2 is None or num3 is None or num4 is None or num5 is None or num6 is None:
raise ValueError, errstring
raise ValueError(errstring)
output.append((command, num1, num2, False, num3, num4, False, num5, num6, False))
@ -1317,11 +1325,11 @@ class Path:
num7, index, pathdata = self.parse_number(index, pathdata)
if num1 is None:
raise ValueError, errstring
raise ValueError(errstring)
while num1 is not None:
if num2 is None or num3 is None or num4 is None or num5 is None or num6 is None or num7 is None:
raise ValueError, errstring
raise ValueError(errstring)
output.append((command, num1, num2, False, num3, num4, num5, num6, num7, False))
@ -1344,7 +1352,7 @@ class Path:
output = []
for datum in self.d:
if not isinstance(datum, (tuple, list)):
raise TypeError, "pathdata elements must be tuples/lists"
raise TypeError("pathdata elements must be tuples/lists")
command = datum[0]
@ -1722,7 +1730,7 @@ class Curve:
try:
# the best way to keep all the information while sampling is to make a linked list
if not (self.low < self.high):
raise ValueError, "low must be less than high"
raise ValueError("low must be less than high")
low, high = self.Sample(float(self.low)), self.Sample(float(self.high))
low.link(None, high)
high.link(low, None)
@ -1913,10 +1921,10 @@ class Poly:
vx[i], vy[i] = 0., 0.
else:
raise ValueError, "mode must be \"lines\", \"bezier\", \"velocity\", \"foreback\", \"smooth\", or an abbreviation"
raise ValueError("mode must be \"lines\", \"bezier\", \"velocity\", \"foreback\", \"smooth\", or an abbreviation")
d = []
indexes = range(len(self.d))
indexes = list(range(len(self.d)))
if self.loop and len(self.d) > 0:
indexes.append(0)
@ -2220,7 +2228,7 @@ class Line(Curve):
defs.append(make_marker(self.arrow_start, "arrow_start"))
line.attr["marker-start"] = "url(#%s)" % self.arrow_start
else:
raise TypeError, "arrow_start must be False/None or an id string for the new marker"
raise TypeError("arrow_start must be False/None or an id string for the new marker")
if self.arrow_end != False and self.arrow_end is not None:
if isinstance(self.arrow_end, SVG):
@ -2230,7 +2238,7 @@ class Line(Curve):
defs.append(make_marker(self.arrow_end, "arrow_end"))
line.attr["marker-end"] = "url(#%s)" % self.arrow_end
else:
raise TypeError, "arrow_end must be False/None or an id string for the new marker"
raise TypeError("arrow_end must be False/None or an id string for the new marker")
return SVG("g", defs, line)
@ -2316,7 +2324,7 @@ class LineGlobal:
defs.append(make_marker(self.arrow_start, "arrow_start"))
line.attr["marker-start"] = "url(#%s)" % self.arrow_start
else:
raise TypeError, "arrow_start must be False/None or an id string for the new marker"
raise TypeError("arrow_start must be False/None or an id string for the new marker")
if self.arrow_end != False and self.arrow_end is not None:
if isinstance(self.arrow_end, SVG):
@ -2326,7 +2334,7 @@ class LineGlobal:
defs.append(make_marker(self.arrow_end, "arrow_end"))
line.attr["marker-end"] = "url(#%s)" % self.arrow_end
else:
raise TypeError, "arrow_end must be False/None or an id string for the new marker"
raise TypeError("arrow_end must be False/None or an id string for the new marker")
return SVG("g", defs, line)
@ -2681,7 +2689,7 @@ class Ticks:
elif isinstance(self.arrow_start, basestring):
defs.append(make_marker(self.arrow_start, "arrow_start"))
else:
raise TypeError, "arrow_start must be False/None or an id string for the new marker"
raise TypeError("arrow_start must be False/None or an id string for the new marker")
if self.arrow_end != False and self.arrow_end is not None:
if isinstance(self.arrow_end, SVG):
@ -2689,7 +2697,7 @@ class Ticks:
elif isinstance(self.arrow_end, basestring):
defs.append(make_marker(self.arrow_end, "arrow_end"))
else:
raise TypeError, "arrow_end must be False/None or an id string for the new marker"
raise TypeError("arrow_end must be False/None or an id string for the new marker")
output.append(defs)
@ -2757,7 +2765,7 @@ class Ticks:
format = self.labels
else:
raise TypeError, "labels must be None/False, True, a format string, or a number->string function"
raise TypeError("labels must be None/False, True, a format string, or a number->string function")
# Now for the ticks
ticks = self.ticks
@ -2793,7 +2801,7 @@ class Ticks:
return ticks, []
else:
raise TypeError, "miniticks must be None/False, True, a number of desired miniticks, or a list of numbers"
raise TypeError("miniticks must be None/False, True, a number of desired miniticks, or a list of numbers")
# Cases 3 & 4: ticks is iterable
elif getattr(ticks, "__iter__", False):
@ -2830,10 +2838,10 @@ class Ticks:
return ticks, []
else:
raise TypeError, "miniticks must be None/False, True, a number of desired miniticks, or a list of numbers"
raise TypeError("miniticks must be None/False, True, a number of desired miniticks, or a list of numbers")
else:
raise TypeError, "ticks must be None/False, a number of desired ticks, a list of numbers, or a dictionary of explicit markers"
raise TypeError("ticks must be None/False, a number of desired ticks, a list of numbers, or a dictionary of explicit markers")
def compute_ticks(self, N, format):
"""Return less than -N or exactly N optimal linear ticks.
@ -2841,9 +2849,9 @@ class Ticks:
Normally only used internally.
"""
if self.low >= self.high:
raise ValueError, "low must be less than high"
raise ValueError("low must be less than high")
if N == 1:
raise ValueError, "N can be 0 or >1 to specify the exact number of ticks or negative to specify a maximum"
raise ValueError("N can be 0 or >1 to specify the exact number of ticks or negative to specify a maximum")
eps = _epsilon * (self.high - self.low)
@ -2948,7 +2956,7 @@ class Ticks:
original_ticks.sort()
if self.low > original_ticks[0] + _epsilon or self.high < original_ticks[-1] - _epsilon:
raise ValueError, "original_ticks {%g...%g} extend beyond [%g, %g]" % (original_ticks[0], original_ticks[-1], self.low, self.high)
raise ValueError("original_ticks {%g...%g} extend beyond [%g, %g]" % (original_ticks[0], original_ticks[-1], self.low, self.high))
granularities = []
for i in range(len(original_ticks)-1):
@ -2975,9 +2983,9 @@ class Ticks:
Normally only used internally.
"""
if self.low >= self.high:
raise ValueError, "low must be less than high"
raise ValueError("low must be less than high")
if N == 1:
raise ValueError, "N can be 0 or >1 to specify the exact number of ticks or negative to specify a maximum"
raise ValueError("N can be 0 or >1 to specify the exact number of ticks or negative to specify a maximum")
eps = _epsilon * (self.high - self.low)
@ -3032,7 +3040,7 @@ class Ticks:
Normally only used internally.
"""
if self.low >= self.high:
raise ValueError, "low must be less than high"
raise ValueError("low must be less than high")
lowN = math.floor(math.log(self.low, base))
highN = math.ceil(math.log(self.high, base))
@ -3166,7 +3174,7 @@ class LineAxis(Line, Ticks):
def interpret(self):
if self.exclude is not None and not (isinstance(self.exclude, (tuple, list)) and len(self.exclude) == 2 and
isinstance(self.exclude[0], (int, long, float)) and isinstance(self.exclude[1], (int, long, float))):
raise TypeError, "exclude must either be None or (low, high)"
raise TypeError("exclude must either be None or (low, high)")
ticks, miniticks = Ticks.interpret(self)
if self.exclude is None: