import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
-import StringIO
+import io
from pylons.i18n.translation import _
self.name = None # name as string or None
self.type = None # type as string or None
def __repr__(self):
- return u"Waypoint %s" % unicode(self.name)
+ return "Waypoint %s" % str(self.name)
class Track:
self.type = None # type as string or None
self.points = [] # one point is a tuple (lat, lon, ele) or (lat, lon, None)
def __repr__(self):
- return u"Track %s" % unicode(self.name)
+ return "Track %s" % str(self.name)
class WrGpx:
elif element.tag == ns+'wpt':
waypoint = parse_wpt(element)
wrgpx.waypoints.append(waypoint)
- if waypoint.ele is None: hints.append(Hint(_(u"Elevation of waypoint '%s' should be given.") % unicode(waypoint), 1))
- if waypoint.name is None: hints.append(Hint(_(u"Name of waypoint '%s' must be given.") % unicode(waypoint), 2))
- if waypoint.type is None: hints.append(Hint(_(u"Type of waypoint '%s' must be given (Gasthaus, Bushaltestelle, ...)") % unicode(waypoint), 2))
- if not waypoint.type in ['Gasthaus', 'Parkplatz', 'Bushaltestelle']: hints.append(Hint(_(u"Type of the waypoint '%s' has to be one of (Gasthaus, Bushaltestelle, ...)") % unicode(waypoint), 2))
+ if waypoint.ele is None: hints.append(Hint(_("Elevation of waypoint '%s' should be given.") % str(waypoint), 1))
+ if waypoint.name is None: hints.append(Hint(_("Name of waypoint '%s' must be given.") % str(waypoint), 2))
+ if waypoint.type is None: hints.append(Hint(_("Type of waypoint '%s' must be given (Gasthaus, Bushaltestelle, ...)") % str(waypoint), 2))
+ if not waypoint.type in ['Gasthaus', 'Parkplatz', 'Bushaltestelle']: hints.append(Hint(_("Type of the waypoint '%s' has to be one of (Gasthaus, Bushaltestelle, ...)") % str(waypoint), 2))
# Routes
elif element.tag == ns+'rte':
track.points.append((trkpt.lat, trkpt.lon, trkpt.ele))
if trkpt.ele is None: no_ele += 1
elif e.tag == ns+'extensions': hints.append(Hint(_("XML element extensions within XML element trkpt is not used by WRGPX."), 2))
- if no_ele > 0: hints.append(Hint(_(u"%d of %d track points have no elevation (%s).") % (no_ele, len(track.points), unicode(track)), 1))
- if len(track.points) == 0: hints.append(Hint(_(u"track '%s' is empty.") % unicode(track), 2))
+ if no_ele > 0: hints.append(Hint(_("%d of %d track points have no elevation (%s).") % (no_ele, len(track.points), str(track)), 1))
+ if len(track.points) == 0: hints.append(Hint(_("track '%s' is empty.") % str(track), 2))
wrgpx.tracks.append(track)
# Extensions
"Create a elevation profile for the wrgpx class. Raises a RuntimError in case of an error, otherwise returns the PNG file as string."
proj_utm32 = mapnik.Projection("+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
bahntracks = [t for t in wrgpx.tracks if t.type=='Rodelbahn' and len(t.points) > 0]
- if len(bahntracks) == 0: raise RuntimeError(_(u"There is no 'Rodelbahn' type track in the GPX file."))
+ if len(bahntracks) == 0: raise RuntimeError(_("There is no 'Rodelbahn' type track in the GPX file."))
# Descending order and check
for track in bahntracks:
- if track.points[0][2] is None or track.points[-1][2] is None: raise RuntimeError(_(u'Track has no elevation data'))
+ if track.points[0][2] is None or track.points[-1][2] is None: raise RuntimeError(_('Track has no elevation data'))
if track.points[0][2] < track.points[-1][2]: track.points[:] = track.points[::-1]
bahntracks.sort(lambda x, y: -1 if x.points[0][2] > y.points[0][2] else 1)
points = []
for track in bahntracks: points.extend(track.points)
points = np.array(points)
- for i in xrange(len(points)):
+ for i in range(len(points)):
c = mapnik.Coord(points[i][1], points[i][0])
c = c.forward(proj_utm32)
points[i][0] = c.y
plt.plot(x, h, color='black')
plt.axis([axxmin, axxmax, axymin, axymax])
plt.grid()
- plt.xlabel(u'Strecke in m [%d m Gesamtstrecke]' % round(x[-1], -1))
- plt.ylabel(u'Höhe in m [%d m Differenz]' % round(h[0]-h[-1]))
- plt.title(u'%s - Höhenprofil' % wrgpx.metadata.name)
+ plt.xlabel('Strecke in m [%d m Gesamtstrecke]' % round(x[-1], -1))
+ plt.ylabel('Höhe in m [%d m Differenz]' % round(h[0]-h[-1]))
+ plt.title('%s - Höhenprofil' % wrgpx.metadata.name)
width_px = 500
- imgdata = StringIO.StringIO()
+ imgdata = io.StringIO()
f.savefig(imgdata, dpi=width_px/plt.gcf().get_figwidth())
s = imgdata.getvalue()
imgdata.close()
def to_python(self, value):
self.assert_string(value, None)
- if value == u'': return self.python_none
+ if value == '': return self.python_none
return self.validator.to_python(value)
def from_python(self, value):
- if value == self.python_none: return u''
+ if value == self.python_none: return ''
return self.validator.from_python(value)
>>> v.to_python(u'Nein')
u'Nein'
"""
- def __init__(self, validator, python_no=u'Nein'):
+ def __init__(self, validator, python_no='Nein'):
self.validator = validator
self.python_no = python_no
def to_python(self, value):
self.assert_string(value, None)
- if value == u'Nein': return self.python_no
+ if value == 'Nein': return self.python_no
return self.validator.to_python(value)
def from_python(self, value):
- if value == self.python_no: return u'Nein'
+ if value == self.python_no: return 'Nein'
return self.validator.from_python(value)
u'any string' <=> u'any string'"""
def to_python(self, value):
self.assert_string(value, None)
- return unicode(value)
+ return str(value)
def from_python(self, value):
- return unicode(value)
+ return str(value)
class UnicodeNone(NoneValidator):
return self.iv.to_python(value)
def from_python(self, value):
- return unicode(value)
+ return str(value)
class UnsignedNone(NoneValidator):
def to_python(self, value):
self.assert_string(value, None)
- if not self.dict.has_key(value): raise formencode.Invalid("Key not found in dict.", value, None)
+ if value not in self.dict: raise formencode.Invalid("Key not found in dict.", value, None)
return self.dict[value]
def from_python(self, value):
- for k, v in self.dict.iteritems():
+ for k, v in self.dict.items():
if type(v) == type(value) and v == value: return k
raise formencode.Invalid('Invalid value', value, None)
u'Nein' <=> False
"""
def __init__(self):
- DictValidator.__init__(self, {u'': None, u'Ja': True, u'Nein': False})
+ DictValidator.__init__(self, {'': None, 'Ja': True, 'Nein': False})
class GermanTristateTuple(DictValidator):
u'Teilweise' <=> (True, True)
u'Nein' <=> (False, True)"""
def __init__(self, yes_python = (True, False), no_python = (False, True), partly_python = (True, True), none_python = (None, None)):
- DictValidator.__init__(self, {u'': none_python, u'Ja': yes_python, u'Nein': no_python, u'Teilweise': partly_python})
+ DictValidator.__init__(self, {'': none_python, 'Ja': yes_python, 'Nein': no_python, 'Teilweise': partly_python})
class GermanTristateFloat(GermanTristateTuple):
def to_python(self, value):
self.assert_string(value, None)
- if value == u'':
+ if value == '':
v = value
c = value
else:
left = value.find('(')
right = value.rfind(')')
if left < 0 and right < 0:
- if not self.comment_is_optional: raise formencode.Invalid(u'Mandatory comment not present', value, None)
+ if not self.comment_is_optional: raise formencode.Invalid('Mandatory comment not present', value, None)
v = value
- c = u''
+ c = ''
elif left >= 0 and right >= 0 and left < right:
v = value[:left].strip()
c = value[left+1:right].strip()
- else: raise formencode.Invalid(u'Invalid format', value, None)
+ else: raise formencode.Invalid('Invalid format', value, None)
return self.value_validator.to_python(v), self.comment_validator.to_python(c)
def from_python(self, value):
v = self.value_validator.from_python(value[0])
c = self.comment_validator.from_python(value[1])
if len(c) > 0:
- if len(v) > 0: return u'%s (%s)' % (v, c)
- else: return u'(%s)' % c
+ if len(v) > 0: return '%s (%s)' % (v, c)
+ else: return '(%s)' % c
return v
def to_python(self, value, state=None):
self.assert_string(value, None)
try: return datetime.datetime.strptime(value, self.date_time_format)
- except ValueError, e: raise formencode.Invalid(str(e), value, None)
+ except ValueError as e: raise formencode.Invalid(str(e), value, None)
def from_python(self, value, state=None):
return value.strftime(self.date_time_format)
"""Formats to coordinates '47.076207 N 11.453553 E' to the (latitude, longitude) tuplet."""
def to_python(self, value):
self.assert_string(value, None)
- r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', value)
- if r is None: raise formencode.Invalid(u"Coordinates '%s' have not a format like '47.076207 N 11.453553 E'" % value, value, None)
+ r = re.match('(\d+\.\d+) N (\d+\.\d+) E', value)
+ if r is None: raise formencode.Invalid("Coordinates '%s' have not a format like '47.076207 N 11.453553 E'" % value, value, None)
return (float(r.groups()[0]), float(r.groups()[1]))
def from_python(self, value):
latitude, longitude = value
- return u'%.6f N %.6f E' % (latitude, longitude)
+ return '%.6f N %.6f E' % (latitude, longitude)
class GeoNone(NoneValidator):
self.assert_string(value, None)
input_format = self.input_format
if not input_format in [self.FORMAT_GUESS, self.FORMAT_GEOCACHING, self.FORMAT_WINTERRODELN, self.FORMAT_GMAPPLUGIN, self.FORMAT_GPX]:
- raise formencode.Invalid(u"input_format %d is not recognized" % input_format, value, None) # Shouldn't it be an other type of runtime error?
+ raise formencode.Invalid("input_format %d is not recognized" % input_format, value, None) # Shouldn't it be an other type of runtime error?
lines = [line.strip() for line in value.split("\n") if len(line.strip()) > 0]
result = []
for line in lines:
if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GEOCACHING:
- r = re.match(u'N ?(\d+)° ?(\d+\.\d+) +E ?(\d+)° ?(\d+\.\d+)', line)
+ r = re.match('N ?(\d+)° ?(\d+\.\d+) +E ?(\d+)° ?(\d+\.\d+)', line)
if not r is None:
g = r.groups()
result.append((float(g[0]) + float(g[1])/60, float(g[2]) + float(g[3])/60, None))
continue
if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_WINTERRODELN:
- r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', line)
+ r = re.match('(\d+\.\d+) N (\d+\.\d+) E', line)
if not r is None:
result.append((float(r.groups()[0]), float(r.groups()[1]), None))
last_input_format = self.FORMAT_WINTERRODELN
continue
if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GMAPPLUGIN:
- r = re.match(u'(\d+\.\d+), ?(\d+\.\d+)', line)
+ r = re.match('(\d+\.\d+), ?(\d+\.\d+)', line)
if not r is None:
result.append((float(r.groups()[0]), float(r.groups()[1]), None))
last_input_format = self.FORMAT_GMAPPLUGIN
continue
except (ExpatError, IndexError, ValueError): pass
- raise formencode.Invalid(u"Coordinates '%s' have no known format" % line, value, None)
+ raise formencode.Invalid("Coordinates '%s' have no known format" % line, value, None)
return result
for latitude, longitude, height in value:
if output_format == self.FORMAT_GEOCACHING:
degree = latitude
- result.append(u'N %02d° %02.3f E %03d° %02.3f' % (latitude, latitude % 1 * 60, longitude, longitude % 1 * 60))
+ result.append('N %02d° %02.3f E %03d° %02.3f' % (latitude, latitude % 1 * 60, longitude, longitude % 1 * 60))
elif output_format == self.FORMAT_WINTERRODELN:
- result.append(u'%.6f N %.6f E' % (latitude, longitude))
+ result.append('%.6f N %.6f E' % (latitude, longitude))
elif output_format == self.FORMAT_GMAPPLUGIN:
- result.append(u'%.6f, %.6f' % (latitude, longitude))
+ result.append('%.6f, %.6f' % (latitude, longitude))
elif output_format == self.FORMAT_GPX:
- if not height is None: result.append(u'<trkpt lat="%.6f" lon="%.6f"><ele>%.2f</ele></trkpt>' % (latitude, longitude, height))
- else: result.append(u'<trkpt lat="%.6f" lon="%.6f"/>' % (latitude, longitude))
+ if not height is None: result.append('<trkpt lat="%.6f" lon="%.6f"><ele>%.2f</ele></trkpt>' % (latitude, longitude, height))
+ else: result.append('<trkpt lat="%.6f" lon="%.6f"/>' % (latitude, longitude))
else:
- raise formencode.Invalid(u"output_format %d is not recognized" % output_format, value, None) # Shouldn't it be an other type of runtime error?
+ raise formencode.Invalid("output_format %d is not recognized" % output_format, value, None) # Shouldn't it be an other type of runtime error?
return "\n".join(result)
def to_python(self, value):
self.assert_string(value, None)
- m = re.match(u'^(?:\+(\d+)/)?([\d/]+)(?:-(\d+))?$', value)
+ m = re.match('^(?:\+(\d+)/)?([\d/]+)(?:-(\d+))?$', value)
# This will separate
# u'+43/512/1234567-89' => (u'43', u'512/1234567', u'89')
# u'+43/512/1234/567-89' => (u'43', u'512/1234/567', u'89')
(country, phone, extension) = m.groups()
# Phone
- if phone.find(u'//') > -1 or phone.count('/') == 0: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
+ if phone.find('//') > -1 or phone.count('/') == 0: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
# Country
if country is None:
if phone[0] != '0': raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
phone = phone[1:]
- country = unicode(self.default_cc)
+ country = str(self.default_cc)
if extension is None: return '+%s/%s' % (country, phone)
return '+%s/%s-%s' % (country, phone, extension)
u'mittel' <=> 2
u'schwer' <=> 3"""
def __init__(self):
- DictValidator.__init__(self, {u'': None, u'leicht': 1, u'mittel': 2, u'schwer': 3})
+ DictValidator.__init__(self, {'': None, 'leicht': 1, 'mittel': 2, 'schwer': 3})
class GermanAvalanches(DictValidator):
u'gelegentlich' <=> 3
u'häufig' <=> 4"""
def __init__(self):
- DictValidator.__init__(self, {u'': None, u'kaum': 1, u'selten': 2, u'gelegentlich': 3, u'häufig': 4})
+ DictValidator.__init__(self, {'': None, 'kaum': 1, 'selten': 2, 'gelegentlich': 3, 'häufig': 4})
class GermanPublicTransport(DictValidator):
u'Nein' <=> 5
u'Ja' <=> 6"""
def __init__(self):
- DictValidator.__init__(self, {u'': None, u'Sehr gut': 1, u'Gut': 2, u'Mittelmäßig': 3, u'Schlecht': 4, u'Nein': 5, u'Ja': 6})
+ DictValidator.__init__(self, {'': None, 'Sehr gut': 1, 'Gut': 2, 'Mittelmäßig': 3, 'Schlecht': 4, 'Nein': 5, 'Ja': 6})
class GermanTristateFloatComment(ValueComment):
u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel' <=> u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel'"""
def to_python(self, value):
self.assert_string(value, None)
- if value == u'': return None
- elif value == u'Nein': return value
- elif value.startswith(u'Tiroler Naturrodelbahn-Gütesiegel '):
+ if value == '': return None
+ elif value == 'Nein': return value
+ elif value.startswith('Tiroler Naturrodelbahn-Gütesiegel '):
p = value.split(" ")
Unsigned().to_python(p[2]) # check if year can be parsed
if not p[3] in ['leicht', 'mittel', 'schwer']: raise formencode.Invalid("Unbekannter Schwierigkeitsgrad", value, None)
return value
- else: raise formencode.Invalid(u"Unbekanntes Gütesiegel", value, None)
+ else: raise formencode.Invalid("Unbekanntes Gütesiegel", value, None)
def from_python(self, value):
- if value == None: return u''
- assert value != u''
+ if value == None: return ''
+ assert value != ''
return self.to_python(self, value)
def to_python(self, value):
self.assert_string(value, None)
v = value
- v = v.replace(u'ä', u'a')
- v = v.replace(u'ö', u'o')
- v = v.replace(u'ü', u'u')
- v = v.replace(u'ß', u'ss')
+ v = v.replace('ä', 'a')
+ v = v.replace('ö', 'o')
+ v = v.replace('ü', 'u')
+ v = v.replace('ß', 'ss')
v = self.urlv.to_python(v)
return value
self.validator = formencode.national.InternationalPhoneNumber(default_cc=lambda: default_cc)
def to_python(self, value):
- return unicode(self.validator.to_python(value))
+ return str(self.validator.to_python(value))
def from_python(self, value):
return self.validator.from_python(value)
u'Sessellift (Wochenende); Taxi (6 Euro)' <=> (True, u'Sessellift (Wochenende); Taxi (6 Euro)')
"""
def __init__(self):
- BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList(DictValidator({u'Sessellift': u'Sessellift', u'Gondel': u'Gondel', u'Linienbus': u'Linienbus', u'Taxi': u'Taxi', u'Sonstige': u'Sonstige'}))))
+ BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList(DictValidator({'Sessellift': 'Sessellift', 'Gondel': 'Gondel', 'Linienbus': 'Linienbus', 'Taxi': 'Taxi', 'Sonstige': 'Sonstige'}))))
class SledRental(BoolUnicodeTupleValidator):