You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jd...@us...> - 2008-06-04 18:21:42
|
Revision: 5386
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5386&view=rev
Author: jdh2358
Date: 2008-06-04 11:21:35 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
Merged revisions 5385 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5385 | jdh2358 | 2008-06-04 13:17:23 -0500 (Wed, 04 Jun 2008) | 1 line
fixed some bugs introduced in the xaxis_date fix
........
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5383
+ /branches/v0_91_maint:1-5385
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-04 18:17:25
|
Revision: 5385
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5385&view=rev
Author: jdh2358
Date: 2008-06-04 11:17:23 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
fixed some bugs introduced in the xaxis_date fix
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/axes.py
Modified: branches/v0_91_maint/lib/matplotlib/axes.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-04 18:15:05 UTC (rev 5384)
+++ branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-04 18:17:23 UTC (rev 5385)
@@ -1174,9 +1174,8 @@
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
+ if iterable(xys) and not len(xys): return
xys = npy.asarray(xys)
-
-
self.dataLim.update_numerix_xy(xys, -1)
@@ -1187,6 +1186,7 @@
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
#print type(x), type(y)
+ if iterable(x) and not len(x): return
self.dataLim.update_numerix(x, y, -1)
def _get_verts_in_data_coords(self, trans, xys):
@@ -1869,15 +1869,16 @@
dmin, dmax = self.convert_xunits([dmin, dmax])
self.viewLim.intervalx().set_bounds(dmin, dmax)
- self.viewLim.intervalx().set_bounds(dmin, dmax)
+ self.dataLim.intervalx().set_bounds(dmin, dmax)
locator = self.xaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.xaxis.set_major_locator(locator)
- locator.refresh()
+ locator.refresh()
+
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
formatter = mdates.AutoDateFormatter(locator)
@@ -1894,19 +1895,20 @@
# have been updated than the ignore setting
dmax = today = datetime.date.today()
dmin = today-datetime.timedelta(days=10)
- self._process_unit_info(xdata=(dmin, dmax))
+ self._process_unit_info(ydata=(dmin, dmax))
- dmin, dmax = self.convert_xunits([dmin, dmax])
+ dmin, dmax = self.convert_yunits([dmin, dmax])
self.viewLim.intervaly().set_bounds(dmin, dmax)
- self.viewLim.intervaly().set_bounds(dmin, dmax)
+ self.dataLim.intervaly().set_bounds(dmin, dmax)
locator = self.yaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.yaxis.set_major_locator(locator)
- locator.refresh()
+ locator.refresh()
+
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
formatter = mdates.AutoDateFormatter(locator)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-04 18:15:20
|
Revision: 5384
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5384&view=rev
Author: jdh2358
Date: 2008-06-04 11:15:05 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
Merged revisions 5383 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5383 | jdh2358 | 2008-06-04 12:49:17 -0500 (Wed, 04 Jun 2008) | 1 line
try to handle xaxis_date more gracefully when no data has been added
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5381
+ /branches/v0_91_maint:1-5383
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-04 17:49:17 UTC (rev 5383)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-04 18:15:05 UTC (rev 5384)
@@ -1,5 +1,5 @@
from __future__ import division, generators
-import math, warnings, new
+import math, sys, warnings, datetime, new
import numpy as np
from numpy import ma
@@ -1309,6 +1309,8 @@
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
+
+ if iterable(xys) and not len(xys): return
if not ma.isMaskedArray(xys):
xys = np.asarray(xys)
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits)
@@ -1320,6 +1322,7 @@
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
+ if iterable(x) and not len(x): return
self.dataLim.update_from_data(x, y, self.ignore_existing_data_limits)
self.ignore_existing_data_limits = False
@@ -1985,11 +1988,24 @@
tz is the time zone to use in labeling dates. Defaults to rc value.
"""
+ if self.ignore_existing_data_limits:
+ # no data has been added - let's set the default datalim.
+ # We should probably use a better proxy for the datalim
+ # have been updated than the ignore setting
+ dmax = today = datetime.date.today()
+ dmin = today-datetime.timedelta(days=10)
+ self._process_unit_info(xdata=(dmin, dmax))
+ dmin, dmax = self.convert_xunits([dmin, dmax])
+ self.viewLim.intervalx = dmin, dmax
+ self.dataLim.intervalx = dmin, dmax
+
locator = self.xaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.xaxis.set_major_locator(locator)
+ locator.refresh()
+
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
formatter = mdates.AutoDateFormatter(locator)
@@ -2000,11 +2016,24 @@
tz is the time zone to use in labeling dates. Defaults to rc value.
"""
+ if self.ignore_existing_data_limits:
+ # no data has been added - let's set the default datalim.
+ # We should probably use a better proxy for the datalim
+ # have been updated than the ignore setting
+ dmax = today = datetime.date.today()
+ dmin = today-datetime.timedelta(days=10)
+ self._process_unit_info(ydata=(dmin, dmax))
+ dmin, dmax = self.convert_yunits([dmin, dmax])
+ self.viewLim.intervaly = dmin, dmax
+ self.dataLim.intervaly = dmin, dmax
+
+
locator = self.yaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.yaxis.set_major_locator(locator)
+ locator.refresh()
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-04 17:49:21
|
Revision: 5383
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5383&view=rev
Author: jdh2358
Date: 2008-06-04 10:49:17 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
try to handle xaxis_date more gracefully when no data has been added
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/axes.py
branches/v0_91_maint/src/_transforms.cpp
branches/v0_91_maint/src/_transforms.h
Modified: branches/v0_91_maint/lib/matplotlib/axes.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-04 16:53:48 UTC (rev 5382)
+++ branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-04 17:49:17 UTC (rev 5383)
@@ -1,5 +1,5 @@
from __future__ import division, generators
-import math, sys, warnings
+import math, sys, warnings, datetime
import numpy as npy
@@ -1858,10 +1858,25 @@
tz is the time zone to use in labeling dates. Defaults to rc value.
"""
+ if self.dataLim.is_ignore():
+ # no data has been added - let's set the default datalim.
+ # We should probably use a better proxy for the datalim
+ # have been updated than the ignore setting
+ dmax = today = datetime.date.today()
+ dmin = today-datetime.timedelta(days=10)
+ self._process_unit_info(xdata=(dmin, dmax))
+
+ dmin, dmax = self.convert_xunits([dmin, dmax])
+
+ self.viewLim.intervalx().set_bounds(dmin, dmax)
+ self.viewLim.intervalx().set_bounds(dmin, dmax)
+
+
locator = self.xaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.xaxis.set_major_locator(locator)
+ locator.refresh()
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
@@ -1873,11 +1888,24 @@
tz is the time zone to use in labeling dates. Defaults to rc value.
"""
+ if self.dataLim.is_ignore():
+ # no data has been added - let's set the default datalim.
+ # We should probably use a better proxy for the datalim
+ # have been updated than the ignore setting
+ dmax = today = datetime.date.today()
+ dmin = today-datetime.timedelta(days=10)
+ self._process_unit_info(xdata=(dmin, dmax))
+ dmin, dmax = self.convert_xunits([dmin, dmax])
+ self.viewLim.intervaly().set_bounds(dmin, dmax)
+ self.viewLim.intervaly().set_bounds(dmin, dmax)
+
+
locator = self.yaxis.get_major_locator()
if not isinstance(locator, mdates.DateLocator):
locator = mdates.AutoDateLocator(tz)
self.yaxis.set_major_locator(locator)
+ locator.refresh()
formatter = self.xaxis.get_major_formatter()
if not isinstance(formatter, mdates.DateFormatter):
Modified: branches/v0_91_maint/src/_transforms.cpp
===================================================================
--- branches/v0_91_maint/src/_transforms.cpp 2008-06-04 16:53:48 UTC (rev 5382)
+++ branches/v0_91_maint/src/_transforms.cpp 2008-06-04 17:49:17 UTC (rev 5383)
@@ -348,6 +348,13 @@
}
Py::Object
+Bbox::is_ignore(const Py::Tuple &args) {
+ _VERBOSE("Bbox::ignore");
+ args.verify_length(0);
+ return Py::Int(_ignore);
+}
+
+Py::Object
Bbox::overlapsx(const Py::Tuple &args, const Py::Dict &kwargs) {
_VERBOSE("Bbox::overlapsx");
args.verify_length(1);
@@ -2349,6 +2356,7 @@
add_varargs_method("ymin", &Bbox::ymin, "ymin()\n");
add_varargs_method("ignore", &Bbox::ignore, "ignore(int)");
+ add_varargs_method("is_ignore", &Bbox::is_ignore, "is_ignore()");
add_varargs_method("scale", &Bbox::scale, "scale(sx,sy)");
add_varargs_method("deepcopy", &Bbox::deepcopy, "deepcopy()\n");
}
Modified: branches/v0_91_maint/src/_transforms.h
===================================================================
--- branches/v0_91_maint/src/_transforms.h 2008-06-04 16:53:48 UTC (rev 5382)
+++ branches/v0_91_maint/src/_transforms.h 2008-06-04 17:49:17 UTC (rev 5383)
@@ -357,8 +357,11 @@
//set the ignore attr
Py::Object ignore(const Py::Tuple &args);
+ //return the ignore setting
+ Py::Object is_ignore(const Py::Tuple &args);
+
Point* ll_api() {return _ll;}
Point* ur_api() {return _ur;}
private:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <sa...@us...> - 2008-06-04 16:54:30
|
Revision: 5382
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5382&view=rev
Author: sameerd
Date: 2008-06-04 09:53:48 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
Merged revisions 5381 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5381 | sameerd | 2008-06-04 11:49:19 -0500 (Wed, 04 Jun 2008) | 3 lines
Docstring changes
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5360
+ /branches/v0_91_maint:1-5381
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-06-04 16:49:19 UTC (rev 5381)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-06-04 16:53:48 UTC (rev 5382)
@@ -48,7 +48,7 @@
* rec2txt : pretty print a record array
* rec2csv : store record array in CSV file
* csv2rec : import record array from CSV file with type inspection
- * rec_append_field : add a field/array to record array
+ * rec_append_fields: adds field(s)/array(s) to record array
* rec_drop_fields : drop fields from record array
* rec_join : join two record arrays on sequence of fields
* rec_groupby : summarize data by groups (similar to SQL GROUP BY)
@@ -1955,7 +1955,10 @@
else: return b
def rec_append_field(rec, name, arr, dtype=None):
- 'return a new record array with field name populated with data from array arr'
+ """
+ return a new record array with field name populated with data from array arr.
+ This function is Depreacted. Please use rec_append_fields.
+ """
warnings.warn("use rec_append_fields", DeprecationWarning)
return rec_append_fields(rec, name, arr, dtype)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <sa...@us...> - 2008-06-04 16:49:21
|
Revision: 5381
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5381&view=rev
Author: sameerd
Date: 2008-06-04 09:49:19 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
Docstring changes
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/mlab.py
Modified: branches/v0_91_maint/lib/matplotlib/mlab.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/mlab.py 2008-06-04 13:09:55 UTC (rev 5380)
+++ branches/v0_91_maint/lib/matplotlib/mlab.py 2008-06-04 16:49:19 UTC (rev 5381)
@@ -48,7 +48,7 @@
* rec2txt : pretty print a record array
* rec2csv : store record array in CSV file
* csv2rec : import record array from CSV file with type inspection
- * rec_append_field : add a field/array to record array
+ * rec_append_fields: adds field(s)/array(s) to record array
* rec_drop_fields : drop fields from record array
* rec_join : join two record arrays on sequence of fields
* rec_groupby : summarize data by groups (similar to SQL GROUP BY)
@@ -1952,7 +1952,10 @@
else: return b
def rec_append_field(rec, name, arr, dtype=None):
- 'return a new record array with field name populated with data from array arr'
+ """
+ return a new record array with field name populated with data from array arr.
+ This function is Depreacted. Please use rec_append_fields.
+ """
warnings.warn("use rec_append_fields", DeprecationWarning)
return rec_append_fields(rec, name, arr, dtype)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-04 13:09:57
|
Revision: 5380
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5380&view=rev
Author: mdboom
Date: 2008-06-04 06:09:55 -0700 (Wed, 04 Jun 2008)
Log Message:
-----------
Update pyparsing to get better error reporting from mathtext. Update
mathtext_examples to include "$$" as a test.
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/mathtext_examples.py
trunk/matplotlib/lib/matplotlib/mathtext.py
trunk/matplotlib/lib/matplotlib/pyparsing.py
Modified: trunk/matplotlib/examples/pylab_examples/mathtext_examples.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-03 20:57:02 UTC (rev 5379)
+++ trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-04 13:09:55 UTC (rev 5380)
@@ -5,7 +5,7 @@
import gc
stests = [
- r'Kerning: AVA $AVA$',
+ r'Kerning: AVA $AVA$ $$',
r'\$100.00 $\alpha \_$',
r'$\frac{\$100.00}{y}$',
r'$x y$',
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-03 20:57:02 UTC (rev 5379)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-04 13:09:55 UTC (rev 5380)
@@ -2024,7 +2024,7 @@
lbrace = Literal('{').suppress()
rbrace = Literal('}').suppress()
- start_group = (Optional(latexfont) + lbrace)
+ start_group = (Optional(latexfont) - lbrace)
start_group.setParseAction(self.start_group)
end_group = rbrace.copy()
end_group.setParseAction(self.end_group)
@@ -2049,9 +2049,9 @@
).setParseAction(self.space).setName('space')
customspace =(Literal(r'\hspace')
- + (( lbrace
- + float
- + rbrace
+ - (( lbrace
+ - float
+ - rbrace
) | Error(r"Expected \hspace{n}"))
).setParseAction(self.customspace).setName('customspace')
@@ -2070,7 +2070,7 @@
accent = Group(
Suppress(bslash)
+ accent
- + placeable
+ - placeable
).setParseAction(self.accent).setName("accent")
function =(Suppress(bslash)
@@ -2082,7 +2082,7 @@
+ ZeroOrMore(
autoDelim
| simple)
- + end_group
+ - end_group
).setParseAction(self.group).setName("group")
font <<(Suppress(bslash)
@@ -2101,20 +2101,30 @@
Suppress(Literal(r"\sqrt"))
+ Optional(
Suppress(Literal("["))
- + Regex("[0-9]+")
- + Suppress(Literal("]")),
+ - Regex("[0-9]+")
+ - Suppress(Literal("]")),
default = None
)
+ (group | Error("Expected \sqrt{value}"))
).setParseAction(self.sqrt).setName("sqrt")
+ print (accent
+ ^ function
+ ^ (c_over_c | symbol)
+ ^ group
+ ^ frac
+ ^ sqrt
+ ) | Error("Expected symbol or group")
+
+ print Error("Expected symbol or group")
+
placeable <<(accent
^ function
^ (c_over_c | symbol)
^ group
^ frac
^ sqrt
- ) | Error("Expected symbol or group")
+ )
simple <<(space
| customspace
@@ -2128,7 +2138,7 @@
( Optional(placeable)
+ OneOrMore(
subsuperop
- + placeable
+ - placeable
)
)
| placeable
@@ -2160,7 +2170,7 @@
non_math
+ ZeroOrMore(
Suppress(math_delim)
- + math
+ + Optional(math)
+ (Suppress(math_delim)
| Error("Expected end of math '$'"))
+ non_math
Modified: trunk/matplotlib/lib/matplotlib/pyparsing.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-03 20:57:02 UTC (rev 5379)
+++ trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-04 13:09:55 UTC (rev 5380)
@@ -1,6 +1,6 @@
# module pyparsing.py
#
-# Copyright (c) 2003-2007 Paul T. McGuire
+# Copyright (c) 2003-2008 Paul T. McGuire
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -58,8 +58,8 @@
- embedded comments
"""
-__version__ = "1.4.8"
-__versionTime__ = "7 October 2007 00:25"
+__version__ = "1.5.0"
+__versionTime__ = "28 May 2008 10:05"
__author__ = "Paul McGuire <pt...@us...>"
import string
@@ -68,50 +68,68 @@
import warnings
import re
import sre_constants
-try:
- from xml.sax.saxutils import escape as xml_escape
-except ImportError:
- def xml_escape(data, entities={}):
- """Escape &, <, and > in a string of data.
+import xml.sax.saxutils
+#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
- You can escape other strings of data by passing a dictionary as
- the optional entities parameter. The keys and values must all be
- strings; each key will be replaced with its corresponding value.
- """
+__all__ = [
+'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
+'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
+'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
+'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
+'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
+'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase',
+'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
+'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
+'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
+'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'getTokensEndLoc', 'hexnums',
+'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno',
+'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
+'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
+'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
+'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
+'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
+'indentedBlock',
+]
- # must do ampersand first
- data = data.replace("&", "&")
- data = data.replace(">", ">")
- data = data.replace("<", "<")
- if entities:
- data = __dict_replace(data, entities)
- return data
-#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
+"""
+Detect if we are running version 3.X and make appropriate changes
+Robert A. Clark
+"""
+if sys.version_info[0] > 2:
+ _PY3K = True
+ _MAX_INT = sys.maxsize
+ basestring = str
+else:
+ _PY3K = False
+ _MAX_INT = sys.maxint
-def _ustr(obj):
- """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
- str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
- then < returns the unicode object | encodes it with the default encoding | ... >.
- """
- try:
- # If this works, then _ustr(obj) has the same behaviour as str(obj), so
- # it won't break any existing code.
- return str(obj)
+if not _PY3K:
+ def _ustr(obj):
+ """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
+ str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
+ then < returns the unicode object | encodes it with the default encoding | ... >.
+ """
+ try:
+ # If this works, then _ustr(obj) has the same behaviour as str(obj), so
+ # it won't break any existing code.
+ return str(obj)
- except UnicodeEncodeError, e:
- # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
- # state that "The return value must be a string object". However, does a
- # unicode object (being a subclass of basestring) count as a "string
- # object"?
- # If so, then return a unicode object:
- return unicode(obj)
- # Else encode it... but how? There are many choices... :)
- # Replace unprintables with escape codes?
- #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
- # Replace unprintables with question marks?
- #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
- # ...
+ except UnicodeEncodeError:
+ # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
+ # state that "The return value must be a string object". However, does a
+ # unicode object (being a subclass of basestring) count as a "string
+ # object"?
+ # If so, then return a unicode object:
+ return unicode(obj)
+ # Else encode it... but how? There are many choices... :)
+ # Replace unprintables with escape codes?
+ #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
+ # Replace unprintables with question marks?
+ #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
+ # ...
+else:
+ _ustr = str
def _str2dict(strg):
return dict( [(c,0) for c in strg] )
@@ -120,10 +138,15 @@
class _Constants(object):
pass
-alphas = string.lowercase + string.uppercase
+if not _PY3K:
+ alphas = string.lowercase + string.uppercase
+else:
+ alphas = string.ascii_lowercase + string.ascii_uppercase
nums = string.digits
hexnums = nums + "ABCDEFabcdef"
alphanums = alphas + nums
+_bslash = "\\"
+printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
class ParseBaseException(Exception):
"""base exception class for all parsing runtime exceptions"""
@@ -153,7 +176,7 @@
elif( aname == "line" ):
return line( self.loc, self.pstr )
else:
- raise AttributeError, aname
+ raise AttributeError(aname)
def __str__( self ):
return "%s (at char %d), (line:%d, col:%d)" % \
@@ -185,6 +208,14 @@
is found; stops all parsing immediately"""
pass
+class ParseSyntaxException(ParseFatalException):
+ """just like ParseFatalException, but thrown internally when an
+ ErrorStop indicates that parsing is to stop immediately because
+ an unbacktrackable syntax error has been found"""
+ def __init__(self, pe):
+ super(ParseSyntaxException, self).__init__(
+ pe.pstr, pe.loc, pe.msg, pe.parserElement)
+
#~ class ReparseException(ParseBaseException):
#~ """Experimental class - parse actions can raise this exception to cause
#~ pyparsing to reparse the input string:
@@ -283,31 +314,72 @@
self.__toklist[k] = v
sub = v
else:
- self.__tokdict[k] = self.__tokdict.get(k,list()) + [(v,0)]
+ self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
sub = v
if isinstance(sub,ParseResults):
sub.__parent = wkref(self)
def __delitem__( self, i ):
if isinstance(i,(int,slice)):
+ mylen = len( self.__toklist )
del self.__toklist[i]
+
+ # convert int to slice
+ if isinstance(i, int):
+ if i < 0:
+ i += mylen
+ i = slice(i, i+1)
+ # get removed indices
+ removed = list(range(*i.indices(mylen)))
+ removed.reverse()
+ # fixup indices in token dictionary
+ for name in self.__tokdict:
+ occurrences = self.__tokdict[name]
+ for j in removed:
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
else:
del self.__tokdict[i]
def __contains__( self, k ):
- return self.__tokdict.has_key(k)
+ return k in self.__tokdict
def __len__( self ): return len( self.__toklist )
def __bool__(self): return len( self.__toklist ) > 0
- def __nonzero__( self ): return self.__bool__()
+ __nonzero__ = __bool__
def __iter__( self ): return iter( self.__toklist )
+ def __reversed__( self ): return iter( reversed(self.__toklist) )
def keys( self ):
"""Returns all named result keys."""
return self.__tokdict.keys()
+ def pop( self, index=-1 ):
+ """Removes and returns item at specified index (default=last).
+ Will work with either numeric indices or dict-key indicies."""
+ ret = self[index]
+ del self[index]
+ return ret
+
+ def get(self, key, defaultValue=None):
+ """Returns named result matching the given key, or if there is no
+ such name, then returns the given defaultValue or None if no
+ defaultValue is specified."""
+ if key in self:
+ return self[key]
+ else:
+ return defaultValue
+
+ def insert( self, index, insStr ):
+ self.__toklist.insert(index, insStr)
+ # fixup indices in token dictionary
+ for name in self.__tokdict:
+ occurrences = self.__tokdict[name]
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(value, position + (position > j))
+
def items( self ):
"""Returns all named result keys and values as a list of tuples."""
- return [(k,self[k]) for k in self.__tokdict.keys()]
+ return [(k,self[k]) for k in self.__tokdict]
def values( self ):
"""Returns all named result values."""
@@ -315,7 +387,7 @@
def __getattr__( self, name ):
if name not in self.__slots__:
- if self.__tokdict.has_key( name ):
+ if name in self.__tokdict:
if name not in self.__accumNames:
return self.__tokdict[name][-1][0]
else:
@@ -446,7 +518,7 @@
continue
else:
resTag = "ITEM"
- xmlBodyText = xml_escape(_ustr(res))
+ xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
@@ -559,13 +631,13 @@
return strg[lastCR+1:]
def _defaultStartDebugAction( instring, loc, expr ):
- print "Match",_ustr(expr),"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
+ print ("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
- print "Matched",_ustr(expr),"->",toks.asList()
+ print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
def _defaultExceptionDebugAction( instring, loc, expr, exc ):
- print "Exception raised:", _ustr(exc)
+ print ("Exception raised:" + _ustr(exc))
def nullDebugAction(*args):
"""'Do-nothing' debug action, to suppress debugging output during parsing."""
@@ -652,7 +724,7 @@
self._parse = self._parse._originalParseMethod
return self
- def normalizeParseActionArgs( f ):
+ def _normalizeParseActionArgs( f ):
"""Internal method used to decorate parse actions that take fewer than 3 arguments,
so that all parse actions can be called as f(s,l,t)."""
STAR_ARGS = 4
@@ -662,34 +734,63 @@
if isinstance(f,type):
restore = f
f = f.__init__
- if f.func_code.co_flags & STAR_ARGS:
+ if not _PY3K:
+ codeObj = f.func_code
+ else:
+ codeObj = f.code
+ if codeObj.co_flags & STAR_ARGS:
return f
- numargs = f.func_code.co_argcount
- if hasattr(f,"im_self"):
- numargs -= 1
+ numargs = codeObj.co_argcount
+ if not _PY3K:
+ if hasattr(f,"im_self"):
+ numargs -= 1
+ else:
+ if hasattr(f,"__self__"):
+ numargs -= 1
if restore:
f = restore
except AttributeError:
try:
+ if not _PY3K:
+ call_im_func_code = f.__call__.im_func.func_code
+ else:
+ call_im_func_code = f.__code__
+
# not a function, must be a callable object, get info from the
# im_func binding of its bound __call__ method
- if f.__call__.im_func.func_code.co_flags & STAR_ARGS:
+ if call_im_func_code.co_flags & STAR_ARGS:
return f
- numargs = f.__call__.im_func.func_code.co_argcount
- if hasattr(f.__call__,"im_self"):
- numargs -= 1
+ numargs = call_im_func_code.co_argcount
+ if not _PY3K:
+ if hasattr(f.__call__,"im_self"):
+ numargs -= 1
+ else:
+ if hasattr(f.__call__,"__self__"):
+ numargs -= 0
except AttributeError:
+ if not _PY3K:
+ call_func_code = f.__call__.func_code
+ else:
+ call_func_code = f.__call__.__code__
# not a bound method, get info directly from __call__ method
- if f.__call__.func_code.co_flags & STAR_ARGS:
+ if call_func_code.co_flags & STAR_ARGS:
return f
- numargs = f.__call__.func_code.co_argcount
- if hasattr(f.__call__,"im_self"):
- numargs -= 1
+ numargs = call_func_code.co_argcount
+ if not _PY3K:
+ if hasattr(f.__call__,"im_self"):
+ numargs -= 1
+ else:
+ if hasattr(f.__call__,"__self__"):
+ numargs -= 1
- #~ print "adding function %s with %d args" % (f.func_name,numargs)
+
+ #~ print ("adding function %s with %d args" % (f.func_name,numargs))
if numargs == 3:
return f
else:
+ if numargs > 3:
+ def tmp(s,l,t):
+ return f(f.__call__.__self__, s,l,t)
if numargs == 2:
def tmp(s,l,t):
return f(l,t)
@@ -701,21 +802,21 @@
return f()
try:
tmp.__name__ = f.__name__
- except AttributeError:
+ except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
try:
tmp.__doc__ = f.__doc__
- except AttributeError:
+ except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
try:
tmp.__dict__.update(f.__dict__)
- except AttributeError:
+ except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
return tmp
- normalizeParseActionArgs = staticmethod(normalizeParseActionArgs)
+ _normalizeParseActionArgs = staticmethod(_normalizeParseActionArgs)
def setParseAction( self, *fns, **kwargs ):
"""Define action to perform when successfully matching parse element definition.
@@ -734,13 +835,13 @@
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
- self.parseAction = map(self.normalizeParseActionArgs, list(fns))
+ self.parseAction = list(map(self._normalizeParseActionArgs, list(fns)))
self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
return self
def addParseAction( self, *fns, **kwargs ):
"""Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
- self.parseAction += map(self.normalizeParseActionArgs, list(fns))
+ self.parseAction += list(map(self._normalizeParseActionArgs, list(fns)))
self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
return self
@@ -757,7 +858,7 @@
self.failAction = fn
return self
- def skipIgnorables( self, instring, loc ):
+ def _skipIgnorables( self, instring, loc ):
exprsFound = True
while exprsFound:
exprsFound = False
@@ -772,7 +873,7 @@
def preParse( self, instring, loc ):
if self.ignoreExprs:
- loc = self.skipIgnorables( instring, loc )
+ loc = self._skipIgnorables( instring, loc )
if self.skipWhitespace:
wt = self.whiteChars
@@ -793,7 +894,7 @@
debugging = ( self.debug ) #and doActions )
if debugging or self.failAction:
- #~ print "Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
+ #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
if (self.debugActions[0] ):
self.debugActions[0]( instring, loc, self )
if callPreParse and self.callPreparse:
@@ -806,8 +907,8 @@
loc,tokens = self.parseImpl( instring, preloc, doActions )
except IndexError:
raise ParseException( instring, len(instring), self.errmsg, self )
- except ParseException, err:
- #~ print "Exception raised:", err
+ except ParseBaseException, err:
+ #~ print ("Exception raised:", err)
if self.debugActions[2]:
self.debugActions[2]( instring, tokensStart, self, err )
if self.failAction:
@@ -840,7 +941,7 @@
self.resultsName,
asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
- except ParseException, err:
+ except ParseBaseException, err:
#~ print "Exception raised in user parse action:", err
if (self.debugActions[2] ):
self.debugActions[2]( instring, tokensStart, self, err )
@@ -855,14 +956,17 @@
modal=self.modalResults )
if debugging:
- #~ print "Matched",self,"->",retTokens.asList()
+ #~ print ("Matched",self,"->",retTokens.asList())
if (self.debugActions[1] ):
self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
return loc, retTokens
def tryParse( self, instring, loc ):
- return self._parse( instring, loc, doActions=False )[0]
+ try:
+ return self._parse( instring, loc, doActions=False )[0]
+ except ParseFatalException:
+ raise ParseException( instring, loc, self.errmsg, self)
# this method gets repeatedly called during backtracking with the same arguments -
# we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
@@ -871,10 +975,8 @@
if lookup in ParserElement._exprArgCache:
value = ParserElement._exprArgCache[ lookup ]
if isinstance(value,Exception):
- if isinstance(value,ParseBaseException):
- value.loc = loc
raise value
- return (value[0],value[1].copy())
+ return value
else:
try:
value = self._parseNoCache( instring, loc, doActions, callPreParse )
@@ -914,11 +1016,15 @@
ParserElement._parse = ParserElement._parseCache
enablePackrat = staticmethod(enablePackrat)
- def parseString( self, instring ):
+ def parseString( self, instring, parseAll=False ):
"""Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
+ If you want the grammar to require that the entire input string be
+ successfully parsed, then set parseAll to True (equivalent to ending
+ the grammar with StringEnd()).
+
Note: parseString implicitly calls expandtabs() on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
@@ -938,13 +1044,14 @@
#~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
- if self.keepTabs:
- loc, tokens = self._parse( instring, 0 )
- else:
- loc, tokens = self._parse( instring.expandtabs(), 0 )
+ if not self.keepTabs:
+ instring = instring.expandtabs()
+ loc, tokens = self._parse( instring, 0 )
+ if parseAll:
+ StringEnd()._parse( instring, loc )
return tokens
- def scanString( self, instring, maxMatches=sys.maxint ):
+ def scanString( self, instring, maxMatches=_MAX_INT ):
"""Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
maxMatches argument, to clip scanning after 'n' matches are found.
@@ -1001,7 +1108,7 @@
out.append(instring[lastE:])
return "".join(map(_ustr,out))
- def searchString( self, instring, maxMatches=sys.maxint ):
+ def searchString( self, instring, maxMatches=_MAX_INT ):
"""Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found.
@@ -1013,35 +1120,117 @@
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return And( [ self, other ] )
def __radd__(self, other ):
- """Implementation of += operator"""
+ """Implementation of + operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return other + self
+ def __sub__(self, other):
+ """Implementation of - operator, returns And with error stop"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return And( [ self, And._ErrorStop(), other ] )
+
+ def __rsub__(self, other ):
+ """Implementation of - operator when left operand is not a ParserElement"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other - self
+
+ def __mul__(self,other):
+ if isinstance(other,int):
+ minElements, optElements = other,0
+ elif isinstance(other,tuple):
+ if len(other)==0:
+ other = (None,None)
+ elif len(other)==1:
+ other = (other[0],None)
+ if len(other)==2:
+ if other[0] is None:
+ other = (0, other[1])
+ if isinstance(other[0],int) and other[1] is None:
+ if other[0] == 0:
+ return ZeroOrMore(self)
+ if other[0] == 1:
+ return OneOrMore(self)
+ else:
+ return self*other[0] + ZeroOrMore(self)
+ elif isinstance(other[0],int) and isinstance(other[1],int):
+ minElements, optElements = other
+ optElements -= minElements
+ else:
+ raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
+ else:
+ raise TypeError("can only multiply 'ParserElement' and int or (int,int) objects")
+ else:
+ raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
+
+ if minElements < 0:
+ raise ValueError("cannot multiply ParserElement by negative value")
+ if optElements < 0:
+ raise ValueError("second tuple value must be greater or equal to first tuple value")
+ if minElements == optElements == 0:
+ raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
+
+ if (optElements):
+ def makeOptionalList(n):
+ if n>1:
+ return Optional(self + makeOptionalList(n-1))
+ else:
+ return Optional(self)
+ if minElements:
+ if minElements == 1:
+ ret = self + makeOptionalList(optElements)
+ else:
+ ret = And([self]*minElements) + makeOptionalList(optElements)
+ else:
+ ret = makeOptionalList(optElements)
+ else:
+ if minElements == 1:
+ ret = self
+ else:
+ ret = And([self]*minElements)
+ return ret
+
+ def __rmul__(self, other):
+ return self.__mul__(other)
+
def __or__(self, other ):
"""Implementation of | operator - returns MatchFirst"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return MatchFirst( [ self, other ] )
def __ror__(self, other ):
- """Implementation of |= operator"""
+ """Implementation of | operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return other | self
def __xor__(self, other ):
@@ -1049,17 +1238,19 @@
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return Or( [ self, other ] )
def __rxor__(self, other ):
- """Implementation of ^= operator"""
+ """Implementation of ^ operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return other ^ self
def __and__(self, other ):
@@ -1067,17 +1258,19 @@
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return Each( [ self, other ] )
def __rand__(self, other ):
- """Implementation of right-& operator"""
+ """Implementation of & operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
- warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
+ return None
return other & self
def __invert__( self ):
@@ -1189,8 +1382,25 @@
self.myException = ret = self.getException();
return ret;
else:
- raise AttributeError, "no such attribute " + aname
+ raise AttributeError("no such attribute " + aname)
+ def __eq__(self,other):
+ if isinstance(other, basestring):
+ try:
+ (self + StringEnd()).parseString(_ustr(other))
+ return True
+ except ParseBaseException:
+ return False
+ else:
+ return super(ParserElement,self)==other
+
+ def __hash__(self):
+ return hash(id(self))
+
+ def __req__(self,other):
+ return self == other
+
+
class Token(ParserElement):
"""Abstract ParserElement subclass, for defining atomic matching patterns."""
def __init__( self ):
@@ -1261,6 +1471,7 @@
exc.loc = loc
exc.pstr = instring
raise exc
+_L = Literal
class Keyword(Token):
"""Token to exactly match a specified string as a keyword, that is, it must be
@@ -1383,14 +1594,14 @@
self.maxSpecified = max > 0
if min < 1:
- raise ValueError, "cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted"
+ raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
- self.maxLen = sys.maxint
+ self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
@@ -1506,7 +1717,7 @@
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
- except sre_constants.error,e:
+ except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
SyntaxWarning, stacklevel=2)
raise
@@ -1529,7 +1740,7 @@
d = result.groupdict()
ret = ParseResults(result.group())
if d:
- for k in d.keys():
+ for k in d:
ret[k] = d[k]
return loc,ret
@@ -1551,12 +1762,12 @@
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
"""
Defined with the following parameters:
- - quoteChar - string of one or more characters defining the quote delimiting string
- - escChar - character to escape quotes, typically backslash (default=None)
- - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
- - multiline - boolean indicating whether quotes can span multiple lines (default=False)
- - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
- - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
+ - quoteChar - string of one or more characters defining the quote delimiting string
+ - escChar - character to escape quotes, typically backslash (default=None)
+ - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
+ - multiline - boolean indicating whether quotes can span multiple lines (default=False)
+ - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
+ - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
"""
super(QuotedString,self).__init__()
@@ -1611,7 +1822,7 @@
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
- except sre_constants.error,e:
+ except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
SyntaxWarning, stacklevel=2)
raise
@@ -1674,14 +1885,14 @@
self.notChars = notChars
if min < 1:
- raise ValueError, "cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted"
+ raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
- self.maxLen = sys.maxint
+ self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
@@ -1760,7 +1971,7 @@
if max > 0:
self.maxLen = max
else:
- self.maxLen = sys.maxint
+ self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
@@ -1807,7 +2018,7 @@
if col(loc,instring) != self.col:
instrlen = len(instring)
if self.ignoreExprs:
- loc = self.skipIgnorables( instring, loc )
+ loc = self._skipIgnorables( instring, loc )
while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
loc += 1
return loc
@@ -1913,7 +2124,54 @@
exc.pstr = instring
raise exc
+class WordStart(_PositionToken):
+ """Matches if the current position is at the beginning of a Word, and
+ is not preceded by any character in a given set of wordChars
+ (default=printables). To emulate the \b behavior of regular expressions,
+ use WordStart(alphanums). WordStart will also match at the beginning of
+ the string being parsed, or at the beginning of a line.
+ """
+ def __init__(self, wordChars = printables):
+ super(WordStart,self).__init__()
+ self.wordChars = _str2dict(wordChars)
+ self.errmsg = "Not at the start of a word"
+ def parseImpl(self, instring, loc, doActions=True ):
+ if loc != 0:
+ if (instring[loc-1] in self.wordChars or
+ instring[loc] not in self.wordChars):
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ return loc, []
+
+class WordEnd(_PositionToken):
+ """Matches if the current position is at the end of a Word, and
+ is not followed by any character in a given set of wordChars
+ (default=printables). To emulate the \b behavior of regular expressions,
+ use WordEnd(alphanums). WordEnd will also match at the end of
+ the string being parsed, or at the end of a line.
+ """
+ def __init__(self, wordChars = printables):
+ super(WordEnd,self).__init__()
+ self.wordChars = _str2dict(wordChars)
+ self.skipWhitespace = False
+ self.errmsg = "Not at the end of a word"
+
+ def parseImpl(self, instring, loc, doActions=True ):
+ instrlen = len(instring)
+ if instrlen>0 and loc<instrlen:
+ if (instring[loc] in self.wordChars or
+ instring[loc-1] not in self.wordChars):
+ #~ raise ParseException( instring, loc, "Expected end of word" )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ return loc, []
+
+
class ParseExpression(ParserElement):
"""Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
def __init__( self, exprs, savelist = False ):
@@ -2012,6 +2270,13 @@
Expressions may be separated by whitespace.
May be constructed using the '+' operator.
"""
+
+ class _ErrorStop(Empty):
+ def __new__(cls,*args,**kwargs):
+ return And._ErrorStop.instance
+ _ErrorStop.instance = Empty()
+ _ErrorStop.instance.leaveWhitespace()
+
def __init__( self, exprs, savelist = True ):
super(And,self).__init__(exprs, savelist)
self.mayReturnEmpty = True
@@ -2027,8 +2292,20 @@
# pass False as last arg to _parse for first element, since we already
# pre-parsed the string as part of our And pre-parsing
loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
+ errorStop = False
for e in self.exprs[1:]:
- loc, exprtokens = e._parse( instring, loc, doActions )
+ if e is And._ErrorStop.instance:
+ errorStop = True
+ continue
+ if errorStop:
+ try:
+ loc, exprtokens = e._parse( instring, loc, doActions )
+ except ParseBaseException, pe:
+ raise ParseSyntaxException(pe)
+ except IndexError, ie:
+ raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
+ else:
+ loc, exprtokens = e._parse( instring, loc, doActions )
if exprtokens or exprtokens.keys():
resultlist += exprtokens
return loc, resultlist
@@ -2071,6 +2348,7 @@
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxMatchLoc = -1
+ maxException = None
for e in self.exprs:
try:
loc2 = e.tryParse( instring, loc )
@@ -2078,7 +2356,7 @@
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
- except IndexError, err:
+ except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
@@ -2088,7 +2366,7 @@
maxMatchExp = e
if maxMatchLoc < 0:
- if self.exprs:
+ if maxException is not None:
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
@@ -2133,6 +2411,7 @@
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
+ maxException = None
for e in self.exprs:
try:
ret = e._parse( instring, loc, doActions )
@@ -2141,14 +2420,14 @@
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
- except IndexError, err:
+ except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
# only got here if no expression matched, raise exception for match that made it the furthest
else:
- if self.exprs:
+ if maxException is not None:
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
@@ -2186,13 +2465,16 @@
self.mayReturnEmpty = False
break
self.skipWhitespace = True
- self.optionals = [ e.expr for e in exprs if isinstance(e,Optional) ]
- self.multioptionals = [ e.expr for e in exprs if isinstance(e,ZeroOrMore) ]
- self.multirequired = [ e.expr for e in exprs if isinstance(e,OneOrMore) ]
- self.required = [ e for e in exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
- self.required += self.multirequired
+ self.initExprGroups = True
def parseImpl( self, instring, loc, doActions=True ):
+ if self.initExprGroups:
+ self.optionals = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
+ self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
+ self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
+ self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
+ self.required += self.multirequired
+ self.initExprGroups = False
tmpLoc = loc
tmpReqd = self.required[:]
tmpOpt = self.optionals[:]
@@ -2220,6 +2502,9 @@
missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
+ # add any unmatched Optionals, in case they have default values defined
+ matchOrder += list(e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt)
+
resultlist = []
for e in matchOrder:
loc,results = e._parse(instring,loc,doActions)
@@ -2268,6 +2553,7 @@
self.skipWhitespace = expr.skipWhitespace
self.saveAsList = expr.saveAsList
self.callPreparse = expr.callPreparse
+ self.ignoreExprs.extend(expr.ignoreExprs)
def parseImpl( self, instring, loc, doActions=True ):
if self.expr is not None:
@@ -2388,7 +2674,7 @@
hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
while 1:
if hasIgnoreExprs:
- preloc = self.skipIgnorables( instring, loc )
+ preloc = self._skipIgnorables( instring, loc )
else:
preloc = loc
loc, tmptokens = self.expr._parse( instring, preloc, doActions )
@@ -2423,7 +2709,7 @@
hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
while 1:
if hasIgnoreExprs:
- preloc = self.skipIgnorables( instring, loc )
+ preloc = self._skipIgnorables( instring, loc )
else:
preloc = loc
loc, tmptokens = self.expr._parse( instring, preloc, doActions )
@@ -2451,6 +2737,7 @@
class _NullToken(object):
def __bool__(self):
return False
+ __nonzero__ = __bool__
def __str__(self):
return ""
@@ -2470,7 +2757,11 @@
loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
except (ParseException,IndexError):
if self.defaultValue is not _optionalNotMatched:
- tokens = [ self.defaultValue ]
+ if self.expr.resultsName:
+ tokens = ParseResults([ self.defaultValue ])
+ tokens[self.expr.resultsName] = self.defaultValue
+ else:
+ tokens = [ self.defaultValue ]
else:
tokens = []
return loc, tokens
@@ -2509,7 +2800,7 @@
expr = self.expr
while loc <= instrlen:
try:
- loc = expr.skipIgnorables( instring, loc )
+ loc = expr._skipIgnorables( instring, loc )
expr._parse( instring, loc, doActions=False, callPreParse=False )
if self.includeMatch:
skipText = instring[startLoc:loc]
@@ -2557,7 +2848,8 @@
self.setWhitespaceChars( self.expr.whiteChars )
self.skipWhitespace = self.expr.skipWhitespace
self.saveAsList = self.expr.saveAsList
- return self
+ self.ignoreExprs.extend(self.expr.ignoreExprs)
+ return None
def leaveWhitespace( self ):
self.skipWhitespace = False
@@ -2617,7 +2909,7 @@
DeprecationWarning,stacklevel=2)
def postParse( self, instring, loc, tokenlist ):
- return map( string.upper, tokenlist )
+ return list(map( string.upper, tokenlist ))
class Combine(TokenConverter):
@@ -2706,7 +2998,7 @@
class OnlyOnce(object):
"""Wrapper for parse actions, to ensure they are only called once."""
def __init__(self, methodCall):
- self.callable = ParserElement.normalizeParseActionArgs(methodCall)
+ self.callable = ParserElement._normalizeParseActionArgs(methodCall)
self.called = False
def __call__(self,s,l,t):
if not self.called:
@@ -2719,7 +3011,7 @@
def traceParseAction(f):
"""Decorator for debugging parse actions."""
- f = ParserElement.normalizeParseActionArgs(f)
+ f = ParserElement._normalizeParseActionArgs(f)
def z(*paArgs):
thisFunc = f.func_name
s,l,t = paArgs[-3:]
@@ -2864,23 +3156,23 @@
warnings.warn("Invalid argument to oneOf, expected string or list",
SyntaxWarning, stacklevel=2)
- try:
- symbols.sort(reverse=True)
- except TypeError:
- symbols.sort()
- symbols.reverse()
i = 0
while i < len(symbols)-1:
cur = symbols[i]
- for j, other in enumerate(symbols[i+1:]):
+ for j,other in enumerate(symbols[i+1:]):
if ( isequal(other, cur) ):
del symbols[i+j+1]
- else:
break
- i += 1
+ elif ( masks(cur, other) ):
+ del symbols[i+j+1]
+ symbols.insert(i,other)
+ cur = other
+ break
+ else:
+ i += 1
if not caseless and useRegex:
- #~ print strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )
+ #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
try:
if len(symbols)==len("".join(symbols)):
return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
@@ -2904,9 +3196,6 @@
"""
return Dict( ZeroOrMore( Group ( key + value ) ) )
-_bslash = "\\"
-printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
-
# convenience constants for positional expressions
empty = Empty().setName("empty")
lineStart = LineStart().setName("lineStart")
@@ -2945,6 +3234,15 @@
except:
return ""
+def matchOnlyAtCol(n):
+ """Helper method for defining parse actions that require matching at a specific
+ column in the input text.
+ """
+ def verifyCol(strg,locn,toks):
+ if col(locn,strg) != n:
+ raise ParseException(strg,locn,"matched token not at column %d" % n)
+ return verifyCol
+
def replaceWith(replStr):
"""Helper method for common parse actions that simply return a literal value. Especially
useful when used with transformString().
@@ -2974,7 +3272,7 @@
try:
endloc = getTokensEndLoc()
except ParseException:
- raise ParseFatalException, "incorrect usage of keepOriginalText - may only be called as a parse action"
+ raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
del t[:]
t += ParseResults(s[startLoc:endloc])
return t
@@ -2991,7 +3289,7 @@
endloc = f[0].f_locals["loc"]
return endloc
else:
- raise ParseFatalException, "incorrect usage of getTokensEndLoc - may only be called from within a parse action"
+ raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack
@@ -3016,7 +3314,7 @@
Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
Optional( Suppress("=") + tagAttrValue ) ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
- closeTag = Combine("</" + tagStr + ">")
+ closeTag = Combine(_L("</") + tagStr + ">")
openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
@@ -3043,35 +3341,29 @@
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
For attribute names with a namespace prefix, you must use the second form. Attribute
names are matched insensitive to upper/lower case.
+
+ To verify that the attribute exists, but without specifying a value, pass
+ withAttribute.ANY_VALUE as the value.
"""
if args:
attrs = args[:]
else:
attrs = attrDict.items()
- attrs = [(k.lower(),v) for k,v in attrs]
+ attrs = [(k,v) for k,v in attrs]
def pa(s,l,tokens):
for attrName,attrValue in attrs:
if attrName not in tokens:
raise ParseException(s,l,"no matching attribute " + attrName)
- if tokens[attrName] != attrValue:
+ if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
(attrName, tokens[attrName], attrValue))
return pa
+withAttribute.ANY_VALUE = object()
opAssoc = _Constants()
opAssoc.LEFT = object()
opAssoc.RIGHT = object()
-def _flattenOpPrecTokens(tokens):
- if isinstance(tokens,ParseResults):
- if len(tokens)==1:
- if isinstance(tokens[0],ParseResults):
- return _flattenOpPrecTokens(tokens[0])
- else:
- return tokens[0]
- return map(_flattenOpPrecTokens,tokens)
- return tokens
-
def operatorPrecedence( baseExpr, opList ):
"""Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
@@ -3084,9 +3376,11 @@
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
- may also be a string, which will be converted to a Literal
+ may also be a string, which will be converted to a Literal;
+ if numTerms is 3, opExpr is a tuple of two expressions, for the
+ two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
- be 1 or 2)
+ be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants opAssoc.RIGHT and opAssoc.LEFT.
@@ -3098,38 +3392,53 @@
lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
for i,operDef in enumerate(opList):
opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
+ if arity == 3:
+ if opExpr is None or len(opExpr) != 2:
+ raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
+ opExpr1, opExpr2 = opExpr
thisExpr = Forward()#.setName("expr%d" % i)
if rightLeftAssoc == opAssoc.LEFT:
if arity == 1:
- matchExpr = Group( lastExpr + ZeroOrMore( opExpr ) )
+ matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
elif arity == 2:
- matchExpr = Group( lastExpr + ZeroOrMore( opExpr + lastExpr ) )
+ if opExpr is not None:
+ matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
+ else:
+ matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
+ elif arity == 3:
+ matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
+ Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
else:
- raise ValueError, "operator must be unary (1) or binary (2)"
+ raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
elif rightLeftAssoc == opAssoc.RIGHT:
if arity == 1:
# try to avoid LR with this extra test
if not isinstance(opExpr, Optional):
opExpr = Optional(opExpr)
matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
- matchExpr |= lastExpr
elif arity == 2:
- matchExpr = Group( lastExpr + ZeroOrMore( opExpr + thisExpr ) )
+ if opExpr is not None:
+ matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
+ else:
+ matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
+ elif arity == 3:
+ matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
+ Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisEx...
[truncated message content] |
|
From: <jd...@us...> - 2008-06-03 20:57:06
|
Revision: 5379
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5379&view=rev
Author: jdh2358
Date: 2008-06-03 13:57:02 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
added sphinx template for doc unit
Added Paths:
-----------
trunk/py4science/examples/sphinx_template/
trunk/py4science/examples/sphinx_template/README.txt
trunk/py4science/examples/sphinx_template/_static/
trunk/py4science/examples/sphinx_template/_templates/
trunk/py4science/examples/sphinx_template/build/
trunk/py4science/examples/sphinx_template/conf.py
trunk/py4science/examples/sphinx_template/index.rst
trunk/py4science/examples/sphinx_template/make.py
trunk/py4science/examples/sphinx_template/model/
trunk/py4science/examples/sphinx_template/model/index.rst
trunk/py4science/examples/sphinx_template/model/introduction.rst
trunk/py4science/examples/sphinx_template/model/next_steps.rst
trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst
trunk/py4science/examples/sphinx_template/simulations/
trunk/py4science/examples/sphinx_template/simulations/code/
trunk/py4science/examples/sphinx_template/simulations/code/elegant.py
trunk/py4science/examples/sphinx_template/simulations/code/hairy.py
trunk/py4science/examples/sphinx_template/simulations/code/make.py
trunk/py4science/examples/sphinx_template/simulations/finale.rst
trunk/py4science/examples/sphinx_template/simulations/index.rst
trunk/py4science/examples/sphinx_template/simulations/introduction.rst
trunk/py4science/examples/sphinx_template/simulations/preliminary.rst
Added: trunk/py4science/examples/sphinx_template/README.txt
===================================================================
--- trunk/py4science/examples/sphinx_template/README.txt (rev 0)
+++ trunk/py4science/examples/sphinx_template/README.txt 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,26 @@
+sphinx template sampledoc
+=========================
+
+This is the top level build directory for the sphinx sampledoc
+documentation. All of the documentation is written using sphinx, a
+python documentation system built on top of ReST. This directory
+contains
+
+
+* model - A document describing a model
+
+* simulations - A document describing the simulations -- contains a
+ code subdir with python scripts and a make.py file to build them
+ into PNGs
+
+* make.py - the build script to build the html or PDF docs. Do
+ `python make.py html` or `python make.py latex` for PDF
+
+* index.rst - the top level include document for sampledocs document
+
+* conf.py - the sphinx configuration
+
+* _static - used by the sphinx build system
+
+* _templates - used by the sphinx build system
+
Added: trunk/py4science/examples/sphinx_template/conf.py
===================================================================
--- trunk/py4science/examples/sphinx_template/conf.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/conf.py 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,161 @@
+# -*- coding: utf-8 -*-
+#
+# sampledoc documentation build configuration file, created by
+# sphinx-quickstart on Tue Jun 3 12:40:24 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default value; values that are commented out
+# serve to show the default value.
+
+import sys, os
+
+# If your extensions are in another directory, add it here. If the directory
+# is relative to the documentation root, use os.path.abspath to make it
+# absolute, like shown here.
+#sys.path.append(os.path.abspath('some/directory'))
+
+# General configuration
+# ---------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+#extensions = []
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General substitutions.
+project = 'sampledoc'
+copyright = '2008, John D. Hunter, Cast of Thousands'
+
+# The default replacements for |version| and |release|, also used in various
+# other places throughout the built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directories, that shouldn't be searched
+# for source files.
+#exclude_dirs = []
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+
+# Options for HTML output
+# -----------------------
+
+# The style sheet to use for HTML and HTML Help pages. A file of that name
+# must exist either in Sphinx' static/ path, or in one of the custom paths
+# given in html_static_path.
+html_style = 'default.css'
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# The name of an image file (within the static path) to place at the top of
+# the sidebar.
+#html_logo = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If true, the reST sources are included in the HTML build as _sources/<name>.
+#html_copy_source = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'sampledoc'
+
+
+# Options for LaTeX output
+# ------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, document class [howto/manual]).
+latex_documents = [
+ ('index', 'sampledoc.tex', 'sampledoc Documentation', 'John D. Hunter, Cast of Thousands', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_use_modindex = True
Added: trunk/py4science/examples/sphinx_template/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/index.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,23 @@
+.. sampledoc documentation master file, created by sphinx-quickstart on Tue Jun 3 12:40:24 2008.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to sampledoc's documentation!
+=====================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+ model/index.rst
+ simulations/index.rst
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
Added: trunk/py4science/examples/sphinx_template/make.py
===================================================================
--- trunk/py4science/examples/sphinx_template/make.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/make.py 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+import fileinput
+import glob
+import os
+import shutil
+import sys
+
+def check_build():
+ build_dirs = ['build', 'build/doctrees', 'build/html', 'build/latex',
+ '_static', '_templates']
+ for d in build_dirs:
+ try:
+ os.mkdir(d)
+ except OSError:
+ pass
+
+def figs():
+ os.system('cd simulations/code/ && python make.py')
+
+def html():
+ check_build()
+ figs()
+ os.system('sphinx-build -b html -d build/doctrees . build/html')
+
+def latex():
+ check_build()
+ figs()
+ if sys.platform != 'win32':
+ # LaTeX format.
+ os.system('sphinx-build -b latex -d build/doctrees . build/latex')
+
+ # Produce pdf.
+ os.chdir('build/latex')
+
+ # Copying the makefile produced by sphinx...
+ os.system('pdflatex sampledoc.tex')
+ os.system('pdflatex sampledoc.tex')
+ os.system('makeindex -s python.ist sampledoc.idx')
+ os.system('makeindex -s python.ist modsampledoc.idx')
+ os.system('pdflatex sampledoc.tex')
+
+ os.chdir('../..')
+ else:
+ print 'latex build has not been tested on windows'
+
+def clean():
+ shutil.rmtree('build')
+
+def all():
+ figs()
+ html()
+ latex()
+
+
+funcd = {'figs':figs,
+ 'html':html,
+ 'latex':latex,
+ 'clean':clean,
+ 'all':all,
+ }
+
+
+if len(sys.argv)>1:
+ for arg in sys.argv[1:]:
+ func = funcd.get(arg)
+ if func is None:
+ raise SystemExit('Do not know how to handle %s; valid args are'%(
+ arg, funcd.keys()))
+ func()
+else:
+ all()
Added: trunk/py4science/examples/sphinx_template/model/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/model/index.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,14 @@
+.. _model-index:
+
+##############
+My Fancy Model
+##############
+
+:Release: |version|
+:Date: |today|
+
+.. toctree::
+
+ introduction.rst
+ next_steps.rst
+ sphinx_helpers.rst
Added: trunk/py4science/examples/sphinx_template/model/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/introduction.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/model/introduction.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,23 @@
+.. _model-introduction:
+
+******************
+Model Introduction
+******************
+
+Wherein I describe my fancy model
+
+.. _other-models:
+
+Other Models
+============
+
+Where in I describe
+
+* model A
+
+* model B
+
+* model C
+
+and why they all suck
+
Added: trunk/py4science/examples/sphinx_template/model/next_steps.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/next_steps.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/model/next_steps.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,8 @@
+.. _next-steps:
+
+**********
+Next steps
+**********
+
+Wherein I describe my next steps
+
Added: trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,127 @@
+.. _sphinx_helpers:
+
+******************
+Sphinx Cheat Sheet
+******************
+
+Wherein I show by example how to do some things in Sphinx (you can see
+a literal version of this file below in :ref:`sphinx-literal`)
+
+
+.. _making-a-list:
+
+Making a list
+=============
+
+It is easy to make lists in rest
+
+Bullet points
+-------------
+
+This is a subsection making bullet points
+
+* point A
+
+* point B
+
+* point C
+
+
+Enumerated points
+------------------
+
+This is a subsection making numbered points
+
+#. point A
+
+#. point B
+
+#. point C
+
+
+.. _making-a-table:
+
+Making a table
+==============
+
+This shows you how to make a table -- if you only want to make a list see :ref:`making-a-list`.
+
+================== ============
+Name Age
+================== ============
+John D Hunter 40
+Cast of Thousands 41
+And Still More 42
+================== ============
+
+.. _making-links:
+
+Making links
+============
+
+It is easy to make a link to `yahoo <http://yahoo.com>`_ or to some
+section inside this document (see :ref:`making-a-table`) or another
+document (see :ref:`final-results`).
+
+.. _formatting-text:
+
+Formatting text
+===============
+
+You use inline markup to make text *italics*, **bold**, or ``monotype``.
+
+You can represent code blocks fairly easily::
+
+ import numpy as np
+ x = np.random.rand(12)
+
+Or literally include code:
+
+.. literalinclude:: ../simulations/code/elegant.py
+
+
+.. _emacs-helpers:
+
+Emacs helpers
+=============
+
+There is an emacs mode `rst.el
+<http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_ which
+automates many important ReST tasks like building and updateing
+table-of-contents, and promoting or demoting section headings. Here
+is the basic ``.emacs`` configuration::
+
+ (require 'rst)
+ (setq auto-mode-alist
+ (append '(("\\.txt$" . rst-mode)
+ ("\\.rst$" . rst-mode)
+ ("\\.rest$" . rst-mode)) auto-mode-alist))
+
+
+Some helpful functions::
+
+ C-c TAB - rst-toc-insert
+
+ Insert table of contents at point
+
+ C-c C-u - rst-toc-update
+
+ Update the table of contents at point
+
+ C-c C-l rst-shift-region-left
+
+ Shift region to the left
+
+ C-c C-r rst-shift-region-right
+
+ Shift region to the right
+
+
+.. _sphinx-literal:
+
+This file
+=========
+
+.. literalinclude:: sphinx_helpers.rst
+
+
Added: trunk/py4science/examples/sphinx_template/simulations/code/elegant.py
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/code/elegant.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/code/elegant.py 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3], [4,5,6])
+plt.ylabel('some more numbers')
+
Added: trunk/py4science/examples/sphinx_template/simulations/code/hairy.py
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/code/hairy.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/code/hairy.py 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3])
+plt.ylabel('some numbers')
+
Added: trunk/py4science/examples/sphinx_template/simulations/code/make.py
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/code/make.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/code/make.py 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+import sys, os, glob
+import matplotlib
+import IPython.Shell
+matplotlib.rcdefaults()
+matplotlib.use('Agg')
+
+mplshell = IPython.Shell.MatplotlibShell('mpl')
+
+def figs():
+ print 'making figs'
+ import matplotlib.pyplot as plt
+ for fname in glob.glob('*.py'):
+ if fname==__file__: continue
+ basename, ext = os.path.splitext(fname)
+ outfile = '%s.png'%basename
+
+ if os.path.exists(outfile):
+ print ' already have %s'%outfile
+ continue
+ else:
+ print ' building %s'%fname
+ plt.close('all') # we need to clear between runs
+ mplshell.magic_run(basename)
+ plt.savefig('%s.png'%basename)
+ print 'all figures made'
+
+
+def clean():
+ patterns = ['#*', '*~', '*.png', '*pyc']
+ for pattern in patterns:
+ for fname in glob.glob(pattern):
+ os.remove(fname)
+ print 'all clean'
+
+
+
+def all():
+ figs()
+
+funcd = {'figs':figs,
+ 'clean':clean,
+ 'all':all,
+ }
+
+if len(sys.argv)>1:
+ for arg in sys.argv[1:]:
+ func = funcd.get(arg)
+ if func is None:
+ raise SystemExit('Do not know how to handle %s; valid args are'%(
+ arg, funcd.keys()))
+ func()
+else:
+ all()
+
+
+
+
Added: trunk/py4science/examples/sphinx_template/simulations/finale.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/finale.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/finale.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,17 @@
+.. _final-results:
+
+*************
+Final Results
+*************
+
+
+After much head scratching, I wrote this big elegant piece of code
+
+.. literalinclude:: code/elegant.py
+
+which produced this elegant figure
+
+.. image:: code/elegant.png
+ :scale: 50
+
+
Added: trunk/py4science/examples/sphinx_template/simulations/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/index.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,15 @@
+.. _simulations-index:
+
+#########################
+My Stupendous Simulations
+#########################
+
+:Release: |version|
+:Date: |today|
+
+.. toctree::
+
+ introduction.rst
+ preliminary.rst
+ finale.rst
+
Added: trunk/py4science/examples/sphinx_template/simulations/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/introduction.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/introduction.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,24 @@
+.. _simulations-introduction:
+
+********************
+Simulations overview
+********************
+
+Wherein I describe my fancy code and libraries to implement my fancy model (:ref:`model-introduction`)
+
+.. _python-libraries:
+
+The python libraries
+====================
+
+Why `matplotlib <http://matplotlib.sf.net>`_ rules
+
+.. _data-sources:
+
+The data sources
+====================
+
+Now how much would you pay?
+
+
+
Added: trunk/py4science/examples/sphinx_template/simulations/preliminary.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/simulations/preliminary.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/simulations/preliminary.rst 2008-06-03 20:57:02 UTC (rev 5379)
@@ -0,0 +1,17 @@
+.. _preliminary-tests:
+
+*****************
+Preliminary tests
+*****************
+
+I wrote this big hairy piece of code
+
+.. literalinclude:: code/hairy.py
+
+
+which produced this lovely figure
+
+.. image:: code/hairy.png
+ :scale: 50
+
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-03 20:34:55
|
Revision: 5378
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5378&view=rev
Author: jdh2358
Date: 2008-06-03 13:34:52 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
updated readme
Modified Paths:
--------------
trunk/matplotlib/examples/README.txt
Modified: trunk/matplotlib/examples/README.txt
===================================================================
--- trunk/matplotlib/examples/README.txt 2008-06-03 20:33:41 UTC (rev 5377)
+++ trunk/matplotlib/examples/README.txt 2008-06-03 20:34:52 UTC (rev 5378)
@@ -7,7 +7,7 @@
Probably the most common way people use matplotlib is with the
procedural interface, which follows the matlab/IDL/mathematica
approach of using simple procedures like "plot" or "title" to modify
-the current figure. These examples are included in the "pylab"
+the current figure. These examples are included in the "pylab_examples"
directory. If you want to write more robust scripts, eg for
production use or in a web application server, you will probably want
to use the matplotlib API for full control. These examples are found
@@ -31,7 +31,7 @@
* misc - some miscellaneous examples. some demos for loading and
working with record arrays
- * pylab - the interface to matplotlib similar to matlab
+ * pylab_examples - the interface to matplotlib similar to matlab
* tests - tests used by matplotlib developers to check functionality
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-03 20:33:48
|
Revision: 5377
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5377&view=rev
Author: jdh2358
Date: 2008-06-03 13:33:41 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
api does not need to be renamed since it doesnt clash
Added Paths:
-----------
trunk/matplotlib/examples/api/
Removed Paths:
-------------
trunk/matplotlib/examples/api_examples/
Copied: trunk/matplotlib/examples/api (from rev 5376, trunk/matplotlib/examples/api_examples)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-03 20:30:40
|
Revision: 5376
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5376&view=rev
Author: jdh2358
Date: 2008-06-03 13:30:38 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
renamed pylab examples dir to fix import breaks
Added Paths:
-----------
trunk/matplotlib/examples/api_examples/
trunk/matplotlib/examples/pylab_examples/
Removed Paths:
-------------
trunk/matplotlib/examples/api/
trunk/matplotlib/examples/pylab/
Copied: trunk/matplotlib/examples/api_examples (from rev 5375, trunk/matplotlib/examples/api)
Copied: trunk/matplotlib/examples/pylab_examples (from rev 5375, trunk/matplotlib/examples/pylab)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-03 20:28:26
|
Revision: 5375
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5375&view=rev
Author: jdh2358
Date: 2008-06-03 13:28:14 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
cleaned up some imports to accord with coding guide
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/axis.py
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2008-06-03 16:41:53 UTC (rev 5374)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2008-06-03 20:28:14 UTC (rev 5375)
@@ -1,6 +1,6 @@
from __future__ import division
import re, warnings
-from cbook import iterable, flatten
+import matplotlib.cbook as cbook
from transforms import Bbox, IdentityTransform, TransformedBbox, TransformedPath
from path import Path
@@ -507,7 +507,7 @@
sequence (all Artists are of the same type) and it is your
responsibility to make sure this is so.
"""
- if iterable(o) and len(o): o = o[0]
+ if cbook.iterable(o) and len(o): o = o[0]
self.o = o
self.aliasd = self.get_aliases()
@@ -757,8 +757,8 @@
print insp.pprint_setters(prop=args[0])
return
- if not iterable(h): h = [h]
- else: h = flatten(h)
+ if not cbook.iterable(h): h = [h]
+ else: h = cbook.flatten(h)
if len(args)%2:
@@ -776,7 +776,7 @@
funcName = "set_%s"%s
func = getattr(o,funcName)
ret.extend( [func(val)] )
- return [x for x in flatten(ret)]
+ return [x for x in cbook.flatten(ret)]
def kwdoc(a):
return '\n'.join(ArtistInspector(a).pprint_setters(leadingspace=2))
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-03 16:41:53 UTC (rev 5374)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-03 20:28:14 UTC (rev 5375)
@@ -7,25 +7,25 @@
import matplotlib
rcParams = matplotlib.rcParams
-from matplotlib import artist as martist
-from matplotlib import axis as maxis
-from matplotlib import cbook
-from matplotlib import collections as mcoll
-from matplotlib import colors as mcolors
-from matplotlib import contour as mcontour
-from matplotlib import dates as mdates
-from matplotlib import font_manager
-from matplotlib import image as mimage
-from matplotlib import legend as mlegend
-from matplotlib import lines as mlines
-from matplotlib import mlab
-from matplotlib import patches as mpatches
-from matplotlib import quiver as mquiver
-from matplotlib import scale as mscale
-from matplotlib import table as mtable
-from matplotlib import text as mtext
-from matplotlib import ticker as mticker
-from matplotlib import transforms as mtransforms
+import matplotlib.artist as martist
+import matplotlib.axis as maxis
+import matplotlib.cbook as cbook
+import matplotlib.collections as mcoll
+import matplotlib.colors as mcolors
+import matplotlib.contour as mcontour
+import matplotlib.dates as mdates
+import matplotlib.font_manager as font_manager
+import matplotlib.image as mimage
+import matplotlib.legend as mlegend
+import matplotlib.lines as mlines
+import matplotlib.mlab as mlab
+import matplotlib.patches as mpatches
+import matplotlib.quiver as mquiver
+import matplotlib.scale as mscale
+import matplotlib.table as mtable
+import matplotlib.text as mtext
+import matplotlib.ticker as mticker
+import matplotlib.transforms as mtransforms
iterable = cbook.iterable
is_string_like = cbook.is_string_like
Modified: trunk/matplotlib/lib/matplotlib/axis.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axis.py 2008-06-03 16:41:53 UTC (rev 5374)
+++ trunk/matplotlib/lib/matplotlib/axis.py 2008-06-03 20:28:14 UTC (rev 5375)
@@ -3,25 +3,20 @@
"""
from __future__ import division
-from artist import Artist, setp
-from cbook import silent_list, popall, CallbackRegistry
-from lines import Line2D, TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN
-from matplotlib import rcParams
-from patches import bbox_artist
-from ticker import NullFormatter, FixedFormatter, ScalarFormatter
-from ticker import NullLocator, FixedLocator, AutoLocator
+from matplotlib import rcParams
+import matplotlib.artist as artist
+import matplotlib.cbook as cbook
+import matplotlib.font_manager as font_manager
+import matplotlib.lines as mlines
+import matplotlib.patches as mpatches
+import matplotlib.scale as mscale
+import matplotlib.text as mtext
+import matplotlib.ticker as mticker
+import matplotlib.transforms as mtransforms
+import matplotlib.units as munits
-from font_manager import FontProperties
-from text import Text, TextWithDash
-from transforms import Affine2D, Bbox, blended_transform_factory, \
- IdentityTransform, interval_contains
-from patches import bbox_artist
-from scale import scale_factory
-import matplotlib.units as units
-
-
-class Tick(Artist):
+class Tick(artist.Artist):
"""
Abstract base class for the axis ticks, grid lines and labels
@@ -41,7 +36,6 @@
label1On : a boolean which determines whether to draw tick label
label2On : a boolean which determines whether to draw tick label
-
"""
def __init__(self, axes, loc, label,
size = None, # points
@@ -57,7 +51,7 @@
loc is the tick location in data coords
size is the tick size in relative, axes coords
"""
- Artist.__init__(self)
+ artist.Artist.__init__(self)
if gridOn is None: gridOn = rcParams['axes.grid']
@@ -75,12 +69,12 @@
self._tickdir = rcParams['%s.direction'%name]
if self._tickdir == 'in':
- self._xtickmarkers = (TICKUP, TICKDOWN)
- self._ytickmarkers = (TICKRIGHT, TICKLEFT)
+ self._xtickmarkers = (mlines.TICKUP, mlines.TICKDOWN)
+ self._ytickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)
self._pad = pad
else:
- self._xtickmarkers = (TICKDOWN, TICKUP)
- self._ytickmarkers = (TICKLEFT, TICKRIGHT)
+ self._xtickmarkers = (mlines.TICKDOWN, mlines.TICKUP)
+ self._ytickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)
self._pad = pad + size
self._loc = loc
@@ -107,11 +101,11 @@
return children
def set_clip_path(self, clippath, transform=None):
- Artist.set_clip_path(self, clippath, transform)
+ artist.Artist.set_clip_path(self, clippath, transform)
#self.tick1line.set_clip_path(clippath, transform)
#self.tick2line.set_clip_path(clippath, transform)
self.gridline.set_clip_path(clippath, transform)
- set_clip_path.__doc__ = Artist.set_clip_path.__doc__
+ set_clip_path.__doc__ = artist.Artist.set_clip_path.__doc__
def get_pad_pixels(self):
return self.figure.dpi * self._pad / 72.0
@@ -165,7 +159,7 @@
def draw(self, renderer):
if not self.get_visible(): return
renderer.open_group(self.__name__)
- midPoint = interval_contains(self.get_view_interval(), self.get_loc())
+ midPoint = mtransforms.interval_contains(self.get_view_interval(), self.get_loc())
if midPoint:
if self.gridOn:
@@ -201,7 +195,7 @@
def _set_artist_props(self, a):
a.set_figure(self.figure)
- #if isinstance(a, Line2D): a.set_clip_box(self.axes.bbox)
+ #if isinstance(a, mlines.Line2D): a.set_clip_box(self.axes.bbox)
def get_view_interval(self):
'return the view Interval instance for the axis tjis tick is ticking'
@@ -222,12 +216,12 @@
# the y loc is 3 points below the min of y axis
# get the affine as an a,b,c,d,tx,ty list
# x in data coords, y in axes coords
- #t = Text(
+ #t = mtext.Text(
trans, vert, horiz = self.axes.get_xaxis_text1_transform(self._pad)
-
- t = TextWithDash(
+ size = rcParams['xtick.labelsize']
+ t = mtext.TextWithDash(
x=0, y=0,
- fontproperties=FontProperties(size=rcParams['xtick.labelsize']),
+ fontproperties=font_manager.FontProperties(size=size),
color=rcParams['xtick.color'],
verticalalignment=vert,
horizontalalignment=horiz,
@@ -244,12 +238,12 @@
'Get the default Text 2 instance'
# x in data coords, y in axes coords
- #t = Text(
+ #t = mtext.Text(
trans, vert, horiz = self.axes.get_xaxis_text2_transform(self._pad)
- t = TextWithDash(
+ t = mtext.TextWithDash(
x=0, y=1,
- fontproperties=FontProperties(size=rcParams['xtick.labelsize']),
+ fontproperties=font_manager.FontProperties(size=rcParams['xtick.labelsize']),
color=rcParams['xtick.color'],
verticalalignment=vert,
dashdirection=1,
@@ -263,7 +257,7 @@
def _get_tick1line(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
- l = Line2D(xdata=(0,), ydata=(0,),
+ l = mlines.Line2D(xdata=(0,), ydata=(0,),
color='k',
linestyle = 'None',
marker = self._xtickmarkers[0],
@@ -276,7 +270,7 @@
def _get_tick2line(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
- l = Line2D( xdata=(0,), ydata=(1,),
+ l = mlines.Line2D( xdata=(0,), ydata=(1,),
color='k',
linestyle = 'None',
marker = self._xtickmarkers[1],
@@ -290,7 +284,7 @@
def _get_gridline(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
- l = Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0),
+ l = mlines.Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0),
color=rcParams['grid.color'],
linestyle=rcParams['grid.linestyle'],
linewidth=rcParams['grid.linewidth'],
@@ -357,12 +351,12 @@
def _get_text1(self):
'Get the default Text instance'
# x in axes coords, y in data coords
- #t = Text(
+ #t = mtext.Text(
trans, vert, horiz = self.axes.get_yaxis_text1_transform(self._pad)
- t = TextWithDash(
+ t = mtext.TextWithDash(
x=0, y=0,
- fontproperties=FontProperties(size=rcParams['ytick.labelsize']),
+ fontproperties=font_manager.FontProperties(size=rcParams['ytick.labelsize']),
color=rcParams['ytick.color'],
verticalalignment=vert,
horizontalalignment=horiz,
@@ -377,12 +371,12 @@
def _get_text2(self):
'Get the default Text instance'
# x in axes coords, y in data coords
- #t = Text(
+ #t = mtext.Text(
trans, vert, horiz = self.axes.get_yaxis_text2_transform(self._pad)
- t = TextWithDash(
+ t = mtext.TextWithDash(
x=1, y=0,
- fontproperties=FontProperties(size=rcParams['ytick.labelsize']),
+ fontproperties=font_manager.FontProperties(size=rcParams['ytick.labelsize']),
color=rcParams['ytick.color'],
verticalalignment=vert,
dashdirection=1,
@@ -397,7 +391,7 @@
'Get the default line2D instance'
# x in axes coords, y in data coords
- l = Line2D( (0,), (0,), color='k',
+ l = mlines.Line2D( (0,), (0,), color='k',
marker = self._ytickmarkers[0],
linestyle = 'None',
markersize=self._size,
@@ -409,7 +403,7 @@
def _get_tick2line(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
- l = Line2D( (1,), (0,), color='k',
+ l = mlines.Line2D( (1,), (0,), color='k',
marker = self._ytickmarkers[1],
linestyle = 'None',
markersize=self._size,
@@ -422,7 +416,7 @@
def _get_gridline(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
- l = Line2D( xdata=(0,1), ydata=(0, 0),
+ l = mlines.Line2D( xdata=(0,1), ydata=(0, 0),
color=rcParams['grid.color'],
linestyle=rcParams['grid.linestyle'],
linewidth=rcParams['grid.linewidth'],
@@ -485,7 +479,7 @@
-class Axis(Artist):
+class Axis(artist.Artist):
"""
Public attributes
@@ -505,13 +499,13 @@
"""
Init the axis with the parent Axes instance
"""
- Artist.__init__(self)
+ artist.Artist.__init__(self)
self.set_figure(axes.figure)
self.axes = axes
self.major = Ticker()
self.minor = Ticker()
- self.callbacks = CallbackRegistry(('units', 'units finalize'))
+ self.callbacks = cbook.CallbackRegistry(('units', 'units finalize'))
#class dummy:
# locator = None
@@ -535,7 +529,7 @@
return self._scale.name
def set_scale(self, value, **kwargs):
- self._scale = scale_factory(value, self, **kwargs)
+ self._scale = mscale.scale_factory(value, self, **kwargs)
self._scale.set_default_locators_and_formatters(self)
def limit_range_for_scale(self, vmin, vmax):
@@ -552,13 +546,13 @@
def cla(self):
'clear the current axis'
- self.set_major_locator(AutoLocator())
- self.set_major_formatter(ScalarFormatter())
- self.set_minor_locator(NullLocator())
- self.set_minor_formatter(NullFormatter())
+ self.set_major_locator(mticker.AutoLocator())
+ self.set_major_formatter(mticker.ScalarFormatter())
+ self.set_minor_locator(mticker.NullLocator())
+ self.set_minor_formatter(mticker.NullFormatter())
# Clear the callback registry for this axis, or it may "leak"
- self.callbacks = CallbackRegistry(('units', 'units finalize'))
+ self.callbacks = cbook.CallbackRegistry(('units', 'units finalize'))
# whether the grids are on
self._gridOnMajor = rcParams['axes.grid']
@@ -571,8 +565,8 @@
# define 1 so properties set on ticks will be copied as they
# grow
- popall(self.majorTicks)
- popall(self.minorTicks)
+ cbook.popall(self.majorTicks)
+ cbook.popall(self.minorTicks)
self.majorTicks.extend([self._get_tick(major=True)])
self.minorTicks.extend([self._get_tick(major=False)])
@@ -584,7 +578,7 @@
self.set_units(None)
def set_clip_path(self, clippath, transform=None):
- Artist.set_clip_path(self, clippath, transform)
+ artist.Artist.set_clip_path(self, clippath, transform)
majorticks = self.get_major_ticks()
minorticks = self.get_minor_ticks()
for child in self.majorTicks + self.minorTicks:
@@ -642,7 +636,7 @@
interval = self.get_view_interval()
for tick, loc, label in self.iter_ticks():
if tick is None: continue
- if not interval_contains(interval, loc): continue
+ if not mtransforms.interval_contains(interval, loc): continue
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
@@ -654,13 +648,13 @@
ticklabelBoxes2.append(extent)
if len(ticklabelBoxes):
- bbox = Bbox.union(ticklabelBoxes)
+ bbox = mtransforms.Bbox.union(ticklabelBoxes)
else:
- bbox = Bbox.from_extents(0, 0, 0, 0)
+ bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0)
if len(ticklabelBoxes2):
- bbox2 = Bbox.union(ticklabelBoxes2)
+ bbox2 = mtransforms.Bbox.union(ticklabelBoxes2)
else:
- bbox2 = Bbox.from_extents(0, 0, 0, 0)
+ bbox2 = mtransforms.Bbox.from_extents(0, 0, 0, 0)
return bbox, bbox2
def draw(self, renderer, *args, **kwargs):
@@ -673,7 +667,7 @@
interval = self.get_view_interval()
for tick, loc, label in self.iter_ticks():
if tick is None: continue
- if not interval_contains(interval, loc): continue
+ if not mtransforms.interval_contains(interval, loc): continue
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
@@ -699,8 +693,8 @@
if 0: # draw the bounding boxes around the text for debug
for tick in majorTicks:
label = tick.label1
- bbox_artist(label, renderer)
- bbox_artist(self.label, renderer)
+ mpatches.bbox_artist(label, renderer)
+ mpatches.bbox_artist(self.label, renderer)
renderer.close_group(__name__)
@@ -713,7 +707,7 @@
def get_gridlines(self):
'Return the grid lines as a list of Line2D instance'
ticks = self.get_major_ticks()
- return silent_list('Line2D gridline', [tick.gridline for tick in ticks])
+ return cbook.silent_list('Line2D gridline', [tick.gridline for tick in ticks])
def get_label(self):
'Return the axis label as a Text instance'
@@ -732,14 +726,14 @@
ticks = self.get_major_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1On]
labels2 = [tick.label2 for tick in ticks if tick.label2On]
- return silent_list('Text major ticklabel', labels1+labels2)
+ return cbook.silent_list('Text major ticklabel', labels1+labels2)
def get_minorticklabels(self):
'Return a list of Text instances for the minor ticklabels'
ticks = self.get_minor_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1On]
labels2 = [tick.label2 for tick in ticks if tick.label2On]
- return silent_list('Text minor ticklabel', labels1+labels2)
+ return cbook.silent_list('Text minor ticklabel', labels1+labels2)
def get_ticklabels(self, minor=False):
'Return a list of Text instances for ticklabels'
@@ -754,7 +748,7 @@
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
- return silent_list('Line2D ticklines', lines)
+ return cbook.silent_list('Line2D ticklines', lines)
def get_minorticklines(self):
'Return the minor tick lines as a list of Line2D instances'
@@ -763,7 +757,7 @@
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
- return silent_list('Line2D ticklines', lines)
+ return cbook.silent_list('Line2D ticklines', lines)
def get_ticklines(self, minor=False):
'Return the tick lines as a list of Line2D instances'
@@ -887,14 +881,14 @@
for tick in self.minorTicks: # don't use get_ticks here!
if tick is None: continue
tick.gridOn = self._gridOnMinor
- if len(kwargs): setp(tick.gridline,**kwargs)
+ if len(kwargs): artist.setp(tick.gridline,**kwargs)
else:
if b is None: self._gridOnMajor = not self._gridOnMajor
else: self._gridOnMajor = b
for tick in self.majorTicks: # don't use get_ticks here!
if tick is None: continue
tick.gridOn = self._gridOnMajor
- if len(kwargs): setp(tick.gridline,**kwargs)
+ if len(kwargs): artist.setp(tick.gridline,**kwargs)
def update_units(self, data):
@@ -904,7 +898,7 @@
registered for unit conversion
"""
- converter = units.registry.get_converter(data)
+ converter = munits.registry.get_converter(data)
if converter is None: return False
self.converter = converter
default = self.converter.default_units(data)
@@ -944,7 +938,7 @@
def convert_units(self, x):
if self.converter is None:
- self.converter = units.registry.get_converter(x)
+ self.converter = munits.registry.get_converter(x)
if self.converter is None:
#print 'convert_units returning identity: units=%s, converter=%s'%(self.units, self.converter)
@@ -967,7 +961,7 @@
else:
if u!=self.units:
self.units = u
- #print 'setting units', self.converter, u, units.registry.get_converter(u)
+ #print 'setting units', self.converter, u, munits.registry.get_converter(u)
pchanged = True
if pchanged:
self._update_axisinfo()
@@ -1036,13 +1030,13 @@
#ticklabels = [str(l) for l in ticklabels]
minor = kwargs.pop('minor', False)
if minor:
- self.set_minor_formatter(FixedFormatter(ticklabels))
+ self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_minor_ticks()
else:
- self.set_major_formatter( FixedFormatter(ticklabels) )
+ self.set_major_formatter( mticker.FixedFormatter(ticklabels) )
ticks = self.get_major_ticks()
- self.set_major_formatter( FixedFormatter(ticklabels) )
+ self.set_major_formatter( mticker.FixedFormatter(ticklabels) )
ret = []
for i, tick in enumerate(ticks):
@@ -1067,10 +1061,10 @@
else:
self.set_view_interval(max(ticks), min(ticks))
if minor:
- self.set_minor_locator(FixedLocator(ticks))
+ self.set_minor_locator(mticker.FixedLocator(ticks))
return self.get_minor_ticks(len(ticks))
else:
- self.set_major_locator( FixedLocator(ticks) )
+ self.set_major_locator( mticker.FixedLocator(ticks) )
return self.get_major_ticks(len(ticks))
def _update_label_position(self, bboxes, bboxes2):
@@ -1119,14 +1113,14 @@
def _get_label(self):
# x in axes coords, y in display coords (to be updated at draw
# time by _update_label_positions)
- label = Text(x=0.5, y=0,
- fontproperties = FontProperties(size=rcParams['axes.labelsize']),
+ label = mtext.Text(x=0.5, y=0,
+ fontproperties = font_manager.FontProperties(size=rcParams['axes.labelsize']),
color = rcParams['axes.labelcolor'],
verticalalignment='top',
horizontalalignment='center',
)
- label.set_transform( blended_transform_factory(
- self.axes.transAxes, IdentityTransform() ))
+ label.set_transform( mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform() ))
self._set_artist_props(label)
self.label_position='bottom'
@@ -1134,14 +1128,14 @@
def _get_offset_text(self):
# x in axes coords, y in display coords (to be updated at draw time)
- offsetText = Text(x=1, y=0,
- fontproperties = FontProperties(size=rcParams['xtick.labelsize']),
+ offsetText = mtext.Text(x=1, y=0,
+ fontproperties = font_manager.FontProperties(size=rcParams['xtick.labelsize']),
color = rcParams['xtick.color'],
verticalalignment='top',
horizontalalignment='right',
)
- offsetText.set_transform( blended_transform_factory(
- self.axes.transAxes, IdentityTransform() ))
+ offsetText.set_transform( mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform() ))
self._set_artist_props(offsetText)
self.offset_text_position='bottom'
return offsetText
@@ -1176,7 +1170,7 @@
if not len(bboxes):
bottom = self.axes.bbox.ymin
else:
- bbox = Bbox.union(bboxes)
+ bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
self.label.set_position( (x, bottom - self.LABELPAD*self.figure.dpi / 72.0))
@@ -1184,7 +1178,7 @@
if not len(bboxes2):
top = self.axes.bbox.ymax
else:
- bbox = Bbox.union(bboxes2)
+ bbox = mtransforms.Bbox.union(bboxes2)
top = bbox.y1
self.label.set_position( (x, top+self.LABELPAD*self.figure.dpi / 72.0))
@@ -1197,7 +1191,7 @@
if not len(bboxes):
bottom = self.axes.bbox.ymin
else:
- bbox = Bbox.union(bboxes)
+ bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
self.offsetText.set_position((x, bottom-self.OFFSETTEXTPAD*self.figure.dpi/72.0))
@@ -1351,16 +1345,16 @@
def _get_label(self):
# x in display coords (updated by _update_label_position)
# y in axes coords
- label = Text(x=0, y=0.5,
+ label = mtext.Text(x=0, y=0.5,
# todo: get the label position
- fontproperties=FontProperties(size=rcParams['axes.labelsize']),
+ fontproperties=font_manager.FontProperties(size=rcParams['axes.labelsize']),
color = rcParams['axes.labelcolor'],
verticalalignment='center',
horizontalalignment='right',
rotation='vertical',
)
- label.set_transform( blended_transform_factory(
- IdentityTransform(), self.axes.transAxes) )
+ label.set_transform( mtransforms.blended_transform_factory(
+ mtransforms.IdentityTransform(), self.axes.transAxes) )
self._set_artist_props(label)
self.label_position='left'
@@ -1368,14 +1362,14 @@
def _get_offset_text(self):
# x in display coords, y in axes coords (to be updated at draw time)
- offsetText = Text(x=0, y=0.5,
- fontproperties = FontProperties(size=rcParams['ytick.labelsize']),
+ offsetText = mtext.Text(x=0, y=0.5,
+ fontproperties = font_manager.FontProperties(size=rcParams['ytick.labelsize']),
color = rcParams['ytick.color'],
verticalalignment = 'bottom',
horizontalalignment = 'left',
)
- offsetText.set_transform(blended_transform_factory(
- self.axes.transAxes, IdentityTransform()) )
+ offsetText.set_transform(mtransforms.blended_transform_factory(
+ self.axes.transAxes, mtransforms.IdentityTransform()) )
self._set_artist_props(offsetText)
self.offset_text_position='left'
return offsetText
@@ -1410,7 +1404,7 @@
if not len(bboxes):
left = self.axes.bbox.xmin
else:
- bbox = Bbox.union(bboxes)
+ bbox = mtransforms.Bbox.union(bboxes)
left = bbox.x0
self.label.set_position( (left-self.LABELPAD*self.figure.dpi/72.0, y))
@@ -1419,7 +1413,7 @@
if not len(bboxes2):
right = self.axes.bbox.xmax
else:
- bbox = Bbox.union(bboxes2)
+ bbox = mtransforms.Bbox.union(bboxes2)
right = bbox.x1
self.label.set_position( (right+self.LABELPAD*self.figure.dpi/72.0, y))
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-06-03 16:41:53 UTC (rev 5374)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-06-03 20:28:14 UTC (rev 5375)
@@ -88,8 +88,8 @@
import numpy as np
-from matplotlib import nxutils
-from matplotlib import cbook
+import matplotlib.nxutils as nxutils
+import matplotlib.cbook as cbook
# set is a new builtin function in 2.4; delete the following when
# support for 2.3 is dropped.
@@ -1231,7 +1231,7 @@
converters, if not None, is a dictionary mapping column number to
a function that will convert that column to a float (or the optional
- dtype if specified). Eg, if column 0 is a date string:
+ dtype if specified). Eg, if column 0 is a date string:
converters={0:datestr2num}
skiprows is the number of rows from the top to skip
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-03 16:42:16
|
Revision: 5374
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5374&view=rev
Author: mdboom
Date: 2008-06-03 09:41:53 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
Describe polar-plot-specific zooming/panning.
Modified Paths:
--------------
trunk/matplotlib/doc/users/navigation_toolbar.rst
Modified: trunk/matplotlib/doc/users/navigation_toolbar.rst
===================================================================
--- trunk/matplotlib/doc/users/navigation_toolbar.rst 2008-06-03 16:40:52 UTC (rev 5373)
+++ trunk/matplotlib/doc/users/navigation_toolbar.rst 2008-06-03 16:41:53 UTC (rev 5374)
@@ -47,6 +47,11 @@
modifier keys 'x', 'y' or 'CONTROL' to constrain the zoom to the x
axes, the y axes, or aspect ratio preserve, respectively.
+ With polar plots, the pan and zoom functionality behaves
+ differently. The radius axis labels can be dragged using the left
+ mouse button. The radius scale can be zoomed in and out using the
+ right mouse button.
+
.. image:: ../mpl_data/images/zoom_to_rect.png
:scale: 100
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-03 16:41:06
|
Revision: 5373
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5373&view=rev
Author: jswhit
Date: 2008-06-03 09:40:52 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
forgot to plot circles in last plot (bluemarble background)
Modified Paths:
--------------
trunk/toolkits/basemap/examples/wiki_example.py
Modified: trunk/toolkits/basemap/examples/wiki_example.py
===================================================================
--- trunk/toolkits/basemap/examples/wiki_example.py 2008-06-03 13:36:33 UTC (rev 5372)
+++ trunk/toolkits/basemap/examples/wiki_example.py 2008-06-03 16:40:52 UTC (rev 5373)
@@ -42,6 +42,8 @@
map.drawmapboundary()
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))
+# plot filled circles at the locations of the cities.
+map.plot(xc,yc,'wo')
# plot the names of five cities.
for name,xpt,ypt in zip(cities,xc,yc):
plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-03 13:37:37
|
Revision: 5372
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5372&view=rev
Author: jdh2358
Date: 2008-06-03 06:36:33 -0700 (Tue, 03 Jun 2008)
Log Message:
-----------
some ports of the old locators and formatters to the new api
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/ticker.py
trunk/matplotlib/matplotlibrc.template
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py 2008-06-03 03:16:55 UTC (rev 5371)
+++ trunk/matplotlib/lib/matplotlib/ticker.py 2008-06-03 13:36:33 UTC (rev 5372)
@@ -244,9 +244,7 @@
class OldScalarFormatter(Formatter):
"""
- Tick location is a plain old number. If viewInterval is set, the
- formatter will use %d, %1.#f or %1.ef as appropriate. If it is
- not set, the formatter will do str conversion
+ Tick location is a plain old number.
"""
def __call__(self, x, pos=None):
@@ -557,8 +555,11 @@
def __call__(self, x, pos=None):
'Return the format for tick val x at position pos'
- self.verify_intervals()
- d = abs(self.viewInterval.span())
+
+
+ vmin, vmax = self.axis.get_view_interval()
+ vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = 0.05)
+ d = abs(vmax-vmin)
b=self._base
if x == 0:
return '0'
@@ -641,17 +642,28 @@
if numticks>2:
step = numsteps*abs(ticks[0]-ticks[1])
else:
- step = numsteps*self.viewInterval.span()/6
+ vmin, vmax = self.axis.get_view_interval()
+ vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = 0.05)
+ d = abs(vmax-vmin)
+ step = numsteps*d/6.
- self.viewInterval.shift(step)
+ vmin += step
+ vmax += step
+ self.axis.set_view_interval(vmin, vmax)
+
def zoom(self, direction):
"Zoom in/out on axis; if direction is >0 zoom in, else zoom out"
- vmin, vmax = self.viewInterval.get_bounds()
+
+ vmin, vmax = self.axis.get_view_interval()
+ vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = 0.05)
+ interval = abs(vmax-vmin)
interval = self.viewInterval.span()
step = 0.1*interval*direction
- self.viewInterval.set_bounds(vmin + step, vmax - step)
+
+ self.axis.set_view_interval(vmin + step, vmax - step)
+
def refresh(self):
'refresh internal information based on current lim'
pass
@@ -731,8 +743,8 @@
def __call__(self):
'Return the locations of the ticks'
- self.verify_intervals()
- vmin, vmax = self.viewInterval.get_bounds()
+ vmin, vmax = self.axis.get_view_interval()
+ vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = 0.05)
if vmax<vmin:
vmin, vmax = vmax, vmin
@@ -755,9 +767,9 @@
def autoscale(self):
'Try to choose the view limits intelligently'
- self.verify_intervals()
- vmin, vmax = self.dataInterval.get_bounds()
+ vmin, vmax = self.axis.get_data_interval()
+
if vmax<vmin:
vmin, vmax = vmax, vmin
@@ -822,7 +834,7 @@
class MultipleLocator(Locator):
"""
Set a tick on every integer that is multiple of base in the
- viewInterval
+ view interval
"""
def __init__(self, base=1.0):
@@ -1141,14 +1153,16 @@
def refresh(self):
'refresh internal information based on current lim'
- d = self.viewInterval.span()
+ vmin, vmax = self.axis.get_view_interval()
+ vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander = 0.05)
+ d = abs(vmax-vmin)
self._locator = self.get_locator(d)
def autoscale(self):
'Try to choose the view limits intelligently'
- self.verify_intervals()
- d = abs(self.dataInterval.span())
+ vmin, vmax = self.axis.get_data_interval()
+ d = abs(vmax-vmin)
self._locator = self.get_locator(d)
return self._locator.autoscale()
@@ -1161,7 +1175,7 @@
try: ld = math.log10(d)
except OverflowError:
- raise RuntimeError('AutoLocator illegal dataInterval range')
+ raise RuntimeError('AutoLocator illegal data interval range')
fld = math.floor(ld)
@@ -1173,13 +1187,9 @@
if d >= 5*base : ticksize = base
elif d >= 2*base : ticksize = base/2.0
else : ticksize = base/5.0
- #print 'base, ticksize, d', base, ticksize, d, self.viewInterval
-
- #print self.dataInterval, d, ticksize
locator = MultipleLocator(ticksize)
- locator.set_view_interval(self.viewInterval)
- locator.set_data_interval(self.dataInterval)
+
return locator
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2008-06-03 03:16:55 UTC (rev 5371)
+++ trunk/matplotlib/matplotlibrc.template 2008-06-03 13:36:33 UTC (rev 5372)
@@ -1,27 +1,22 @@
### MATPLOTLIBRC FORMAT
-# This is a sample matplotlib configuration file. It should be placed
-# in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and
-# C:\Documents and Settings\yourname\.matplotlib (win32 systems)
+# This is a sample matplotlib configuration file - you can find a copy
+# of it on your system in
+# site-packages/matplotlib/mpl-data/matplotlibrc. If you edit it
+# there, please note that it will be overridden in your next install.
+# If you want to keep a permanent local bopy that will not be
+# over-written, place it in HOME/.matplotlib/matplotlibrc (unix/linux
+# like systems) and C:\Documents and Settings\yourname\.matplotlib
+# (win32 systems).
#
-# By default, the installer will overwrite the existing file in the
-# install path, so if you want to preserve your's, please move it to
-# your HOME dir and set the environment variable if necessary.
-#
# This file is best viewed in a editor which supports python mode
-# syntax highlighting
-#
-# Blank lines, or lines starting with a comment symbol, are ignored,
-# as are trailing comments. Other lines must have the format
-#
-# key : val # optional comment
-#
-# Colors: for the color values below, you can either use
-# - a matplotlib color string, such as r, k, or b
-# - an rgb tuple, such as (1.0, 0.5, 0.0)
-# - a hex string, such as ff00ff or #ff00ff
-# - a scalar grayscale intensity such as 0.75
-# - a legal html color name, eg red, blue, darkslategray
+# syntax highlighting # Blank lines, or lines starting with a comment
+# symbol, are ignored, as are trailing comments. Other lines must
+# have the format # key : val # optional comment # Colors: for the
+# color values below, you can either use - a matplotlib color string,
+# such as r, k, or b - an rgb tuple, such as (1.0, 0.5, 0.0) - a hex
+# string, such as ff00ff or #ff00ff - a scalar grayscale intensity
+# such as 0.75 - a legal html color name, eg red, blue, darkslategray
#### CONFIGURATION BEGINS HERE
# the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-03 03:16:57
|
Revision: 5371
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5371&view=rev
Author: jswhit
Date: 2008-06-02 20:16:55 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
don't use runtime_library_dirs on windows
Modified Paths:
--------------
trunk/toolkits/basemap/setup.py
Modified: trunk/toolkits/basemap/setup.py
===================================================================
--- trunk/toolkits/basemap/setup.py 2008-06-03 02:05:07 UTC (rev 5370)
+++ trunk/toolkits/basemap/setup.py 2008-06-03 03:16:55 UTC (rev 5371)
@@ -83,11 +83,19 @@
extensions.append(Extension("mpl_toolkits.basemap._geod",deps+['src/_geod.c'],include_dirs = ['src'],))
# for some reason, pickling won't work if this extension is installed
# as "matplotlib.toolkits.basemap._geoslib"
-extensions.append(Extension("_geoslib",['src/_geoslib.c'],
- library_dirs=geos_library_dirs,
- runtime_library_dirs=geos_library_dirs,
- include_dirs=geos_include_dirs,
- libraries=['geos_c','geos']))
+if sys.platform == 'win32':
+# don't use runtime_library_dirs on windows (workaround
+# for a distutils bug - http://bugs.python.org/issue2437).
+ extensions.append(Extension("_geoslib",['src/_geoslib.c'],
+ library_dirs=geos_library_dirs,
+ include_dirs=geos_include_dirs,
+ libraries=['geos_c','geos']))
+else:
+ extensions.append(Extension("_geoslib",['src/_geoslib.c'],
+ library_dirs=geos_library_dirs,
+ runtime_library_dirs=geos_library_dirs,
+ include_dirs=geos_include_dirs,
+ libraries=['geos_c','geos']))
# install shapelib and dbflib.
packages = packages + ['shapelib','dbflib']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <as...@us...> - 2008-06-03 02:05:11
|
Revision: 5370
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5370&view=rev
Author: astraw
Date: 2008-06-02 19:05:07 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
add expand_vertical and expand_horizontal flags
Modified Paths:
--------------
trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py
Modified: trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py
===================================================================
--- trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py 2008-06-03 02:03:56 UTC (rev 5369)
+++ trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py 2008-06-03 02:05:07 UTC (rev 5370)
@@ -11,6 +11,11 @@
'align_centre_horizontal',
'align_right',
'align_bottom',
+
+ # XXX TODO: check if there is another way to do this
+ # in wx (in context of grid sizer):
+ 'expand_vertical',
+ 'expand_horizontal',
]
def as_sizer_element(ax,**kwargs):
@@ -433,6 +438,12 @@
elif el.flag.get('align_centre_vertical',False):
el_lbrt_inch = (x0, y05-h2,
x0+w,y05+h2)
+ elif el.flag.get('expand_vertical',False):
+ el_lbrt_inch = (x05-w2, y0,
+ x05+w2, y1)
+ elif el.flag.get('expand_horizontal',False):
+ el_lbrt_inch = (x0, y05-h2,
+ x1, y05+h2)
# XXX more needed
else:
# top left default
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <as...@us...> - 2008-06-03 02:04:00
|
Revision: 5369
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5369&view=rev
Author: astraw
Date: 2008-06-02 19:03:56 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
remove trailing whitespace
Modified Paths:
--------------
trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py
Modified: trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py
===================================================================
--- trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py 2008-06-02 21:21:29 UTC (rev 5368)
+++ trunk/toolkits/mplsizer/mpl_toolkits/mplsizer/mplsizer.py 2008-06-03 02:03:56 UTC (rev 5369)
@@ -46,14 +46,14 @@
else:
raise ValueError('key "%s" is not understood'%key) # hint: try centre instead of center
self.Update() # update self.minsize and self.minsize_bordered
-
+
def _show_contents(self,indent=0):
buf = (' '*indent)+'MplSizerElement\n'
return buf
-
+
def Update(self):
# updates self.minsize and self.minsize_bordered
-
+
left = self.flag.get('left',False) or self.flag.get('all',False)
right = self.flag.get('right',False) or self.flag.get('all',False)
bottom = self.flag.get('bottom',False) or self.flag.get('all',False)
@@ -75,7 +75,7 @@
print self.name,'MplSizerElement.Update() setting minsize',self.minsize
print
return
-
+
def _layout(self,lbrt_inch,fig_w_inch,fig_h_inch,eps=1e-10):
#print 'MplSizerElement._layout',self,self.name,lbrt_inch
@@ -117,14 +117,14 @@
h_inch = lbrt_inch[3]-lbrt_inch[1]
self._rect = (lbrt_inch[0]/fig_w_inch, lbrt_inch[1]/fig_h_inch,
w_inch/fig_w_inch, h_inch/fig_h_inch )
-
+
# call derived class layout_core (where the action is)
return self._layout_core(lbrt_inch,fig_w_inch,fig_h_inch)
-
+
def _layout_core(self,lbrt_inch,fig_w_inch,fig_h_inch):
# does nothing in this base class -- override for interesting behavior
return None,None
-
+
class MplAxesSizerElement( MplSizerElement ):
def __init__(self,ax,**kwargs):
self.ax = ax
@@ -161,7 +161,7 @@
for el in self.elements:
buf += el._show_contents(indent=indent+2)
return buf
-
+
class MplBoxSizer( MplSizer ):
"""vertical or horizontal sizer"""
def __init__(self,orientation=None):
@@ -190,29 +190,29 @@
else:
dir_idx=0
other_idx=1
-
+
minsize = [0,0]
for el in self.elements:
el.Update() # updates minsize, may not be necessary
dir_minsize = el.minsize_bordered[dir_idx]
other_minsize = el.minsize_bordered[other_idx]
-
+
minsize[dir_idx] = minsize[dir_idx] + dir_minsize
minsize[other_idx] = max(minsize[other_idx],other_minsize)
-
+
self.minsize = minsize
#print self.name,'MplBoxSizer.Update() setting minsize',self.minsize
MplSizer.Update(self) # call base class (sets self.minsize_bordered)
def _layout_core(self,lbrt_inch,fig_w_inch,fig_h_inch):
#print 'MplBoxSizer._layout_core',self,self.name,lbrt_inch
-
+
if self.orientation.startswith('v'):
vertical=True
elif self.orientation.startswith('h'):
vertical=False
else: ValueError("only vertical and horizontal supported")
-
+
if vertical:
dir_idx = 1
sizer_width_inch = lbrt_inch[2]-lbrt_inch[0]
@@ -224,7 +224,7 @@
stop = lbrt_inch[dir_idx+2]
dist_avail = stop-start
total_weight = 0
-
+
# first iteration -- find inches remaining after borders and minsizes allocated
optioned_minimum = 0
for el in self.elements:
@@ -270,7 +270,7 @@
else:
current_location_inch += dir*el.minsize_bordered[dir_idx]
el_rb = current_location_inch
-
+
if vertical:
el_bottom = el_rb
el_top = el_lt
@@ -296,7 +296,7 @@
else:
el_lbrt_inch = (lbrt_inch[0], el_bottom,
lbrt_inch[0]+minwidth, el_top)
-
+
else: #horizonal
el_left = el_lt
el_right = el_rb
@@ -339,7 +339,7 @@
self.vgap_inch = vgap
self.append_horiz = append_horiz # if true, add horizontally
MplSizer.__init__(self)
-
+
def _show_contents(self,indent=0):
buf = (' '*indent)+'MplGridSizer:\n'
buf += MplSizer._show_contents(self,indent+2)
@@ -376,14 +376,14 @@
n_hgaps = max(0,self.cols-1)
total_hgap = n_hgaps*self.hgap_inch
-
+
if self.flag.get('expand',False):
total_width_inches = lbrt_inch[2]-lbrt_inch[0]
else:
total_width_inches = self.minsize[0]
col_width = (total_width_inches-total_hgap)/self.cols
col_stride = col_width + self.hgap_inch
-
+
n_vgaps = max(0,rows-1)
total_vgap = n_vgaps*self.vgap_inch
@@ -396,7 +396,7 @@
req_w_inch = None
req_h_inch = None
-
+
for i in range(rows):
y1 = lbrt_inch[3] - i*row_stride # top
y0 = lbrt_inch[3] - i*row_stride - row_height # bottom
@@ -411,7 +411,7 @@
continue
el = self.elements[idx]
-
+
x0 = lbrt_inch[0] + j*col_stride
x1 = lbrt_inch[0] + j*col_stride + col_width
@@ -446,13 +446,13 @@
if req_w_inch is not None:
req_w_inch = self.cols*req_w_inch
-
+
if req_h_inch is not None:
req_h_inch = rows*req_h_inch
-
+
# call base class
return req_w_inch, req_h_inch
-
+
class MplSizerFrame:
def __init__(self,fig):
self.fig = fig
@@ -466,10 +466,10 @@
sizer._update_sizer_element_kwargs(**kwargs)
sizer.Update() # calculate minsize requirements
self.sizer = sizer
-
+
def Layout(self):
self.sizer.Update() # calculate minsize requirements
-
+
fig_w_inch = self.fig.get_figwidth()
fig_h_inch = self.fig.get_figheight()
lbrt_inch = (0,0,fig_w_inch,fig_h_inch) # bounding box within figure
@@ -497,4 +497,4 @@
## print 'ntry %d: req_w_inch, req_h_inch'%(ntry,),repr(req_w_inch), repr(req_h_inch)
if (req_w_inch is not None) or (req_h_inch is not None):
raise RuntimeError('failed to layout')
-
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-02 21:21:32
|
Revision: 5368
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5368&view=rev
Author: jdh2358
Date: 2008-06-02 14:21:29 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
moved intro into separate doc
Modified Paths:
--------------
trunk/matplotlib/doc/devel/coding_guide.rst
trunk/matplotlib/doc/faq/installing_faq.rst
trunk/matplotlib/doc/faq/troubleshooting_faq.rst
trunk/matplotlib/doc/users/index.rst
Added Paths:
-----------
trunk/matplotlib/doc/users/intro.rst
Modified: trunk/matplotlib/doc/devel/coding_guide.rst
===================================================================
--- trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-02 21:01:47 UTC (rev 5367)
+++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-02 21:21:29 UTC (rev 5368)
@@ -172,7 +172,7 @@
(lambda ()
(add-hook 'write-file-functions 'delete-trailing-whitespace)))
-for older versions of emacs (emacs<22) you need to do:
+for older versions of emacs (emacs<22) you need to do:
.. code-block:: cl
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 21:01:47 UTC (rev 5367)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 21:21:29 UTC (rev 5368)
@@ -19,7 +19,7 @@
does not properly clean the build directory, and does nothing to the
install directory. To cleanly rebuild:
- * delete the ``build`` directory in the source tree
+ * delete the ``build`` directory in the source tree
* delete ``site-packages/matplotlib`` directory in the Python
installation. The location of ``site-packages`` is
platform-specific. You can find out where matplotlib is installed by doing::
@@ -63,7 +63,7 @@
the ``backend`` parameter in you ``matplotlibrc`` file (see
:ref:`customizing-matplotlib`)::
- backend : WXAgg # use wxpython with antigrain (agg) rendering
+ backend : WXAgg # use wxpython with antigrain (agg) rendering
The other is to use the matplotlib :func:`~matplotlib.use` directive::
@@ -74,7 +74,7 @@
:mod:`matplotlib.pyplot` or :mod:`matplotlib.pylab`.
If you are unsure what to do, and just want to get cranking, just set
-your backend to `TkAgg`. This will do the right thing for 95% of the
+your backend to ``TkAgg``. This will do the right thing for 95% of the
users. It gives you the option of running your scripts in batch or
working interactively from the python shell, with the least amount of
hassles, and is smart enough to do the right thing when you ask for
@@ -100,7 +100,8 @@
backends generate a pixel represenation of the line whose accuracy
depends on a DPI setting.
-Here is a summary of the matplotlib rendering backends:
+Here is a summary of the matplotlib renders (there is an eponymous
+backed for each):
=============================== =====================================================================================
Renderer (Filetypes) Description
@@ -116,7 +117,7 @@
And here are the user interfaces and renderer combinations supported:
============ ===================================================================================================
-Backend Description
+Backend Description
============ ===================================================================================================
GTKAgg Agg rendering to a GTK canvas (`pygtk <http://www.pygtk.org>`_)
GTK GDK rendering to a GTK canvas (not recommended) (`pygtk <http://www.pygtk.org>`_)
@@ -129,3 +130,30 @@
FLTKAgg Agg rendering to a FLTK canvas (`pyfltk <http://pyfltk.sourceforge.net>`)_
============ ===================================================================================================
+
+OS X Questions
+==============
+
+.. _easy-install-osx-egg:
+
+How can I easy_install my egg?
+------------------------------
+
+I downloaded the egg for 0.98 from the matplotlib webpages,
+and I am trying to ``easy_install`` it, but I am getting an error::
+
+ > easy_install ./matplotlib-0.98.0-py2.5-macosx-10.3-fat.egg
+ Processing matplotlib-0.98.0-py2.5-macosx-10.3-fat.egg
+ removing '/Library/Python/2.5/site-packages/matplotlib-0.98.0-py2.5-
+ ...snip...
+ Reading http://matplotlib.sourceforge.net
+ Reading http://cheeseshop.python.org/pypi/matplotlib/0.91.3
+ No local packages or download links found for matplotlib==0.98.0
+ error: Could not find suitable distribution for
+ Requirement.parse('matplotlib==0.98.0')
+
+If you rename ``matplotlib-0.98.0-py2.5-macosx-10.3-fat.egg`` to
+``matplotlib-0.98.0-py2.5.egg``, ``easy_install`` will install it from
+the disk. Many Mac OS X eggs with cruft at the end of the filename,
+which prevents their installation through easy_install. Renaming is
+all it takes to install them; still, it's annoying.
Modified: trunk/matplotlib/doc/faq/troubleshooting_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 21:01:47 UTC (rev 5367)
+++ trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 21:21:29 UTC (rev 5368)
@@ -63,3 +63,4 @@
a bug and can not be quickly solved, you may be asked to file a bug in
the tracker so the issue doesn't get lost.
+
Modified: trunk/matplotlib/doc/users/index.rst
===================================================================
--- trunk/matplotlib/doc/users/index.rst 2008-06-02 21:01:47 UTC (rev 5367)
+++ trunk/matplotlib/doc/users/index.rst 2008-06-02 21:21:29 UTC (rev 5368)
@@ -9,6 +9,7 @@
.. toctree::
+ intro.rst
pyplot_tutorial.rst
mathtext.rst
navigation_toolbar.rst
@@ -17,86 +18,3 @@
event_handling.rst
-matplotlib is a library for making 2D plots of arrays in `Python
-<http://www.python.org>`_. Although it has its origins in emulating
-the `MATLAB™ <http://www.mathworks.com>`_ graphics commands, it does
-not require MATLAB, and can be used in a Pythonic, object oriented
-way. Although matplotlib is written primarily in pure Python, it
-makes heavy use of `NumPy <http://www.numpy.org>`_ and other extension
-code to provide good performance even for large arrays.
-
-matplotlib is designed with the philosophy that you should be able to
-create simple plots with just a few commands, or just one! If you
-want to see a histogram of your data, you shouldn't need to
-instantiate objects, call methods, set properties, and so on; it
-should just work.
-
-For years, I used to use MATLAB exclusively for data analysis and
-visualization. MATLAB excels at making nice looking plots easy. When
-I began working with EEG data, I found that I needed to write
-applications to interact with my data, and developed and EEG analysis
-application in MATLAB. As the application grew in complexity,
-interacting with databases, http servers, manipulating complex data
-structures, I began to strain against the limitations of MATLAB as a
-programming language, and decided to start over in Python. Python
-more than makes up for all of MATLAB's deficiencies as a programming
-language, but I was having difficulty finding a 2D plotting package
-(for 3D `VTK <http://www.vtk.org/>`_) more than exceeds all of my needs).
-
-When I went searching for a Python plotting package, I had several
-requirements:
-
-* Plots should look great - publication quality. One important
- requirement for me is that the text looks good (antialiased, etc.)
-
-* Postscript output for inclusion with TeX documents
-
-* Embeddable in a graphical user interface for application
- development
-
-* Code should be easy enough that I can understand it and extend
- it
-
-* Making plots should be easy
-
-Finding no package that suited me just right, I did what any
-self-respecting Python programmer would do: rolled up my sleeves and
-dived in. Not having any real experience with computer graphics, I
-decided to emulate MATLAB's plotting capabilities because that is
-something MATLAB does very well. This had the added advantage that
-many people have a lot of MATLAB experience, and thus they can
-quickly get up to steam plotting in python. From a developer's
-perspective, having a fixed user interface (the pylab interface) has
-been very useful, because the guts of the code base can be redesigned
-without affecting user code.
-
-The matplotlib code is conceptually divided into three parts: the
-*pylab interface* is the set of functions provided by
-:mod:`matplotlib.pylab` which allow the user to create plots with code
-quite similar to MATLAB figure generating code. The *matplotlib
-frontend* or *matplotlib API* is the set of classes that do the heavy
-lifting, creating and managing figures, text, lines, plots and so on.
-This is an abstract interface that knows nothing about output. The
-*backends* are device dependent drawing devices, aka renderers, that
-transform the frontend representation to hardcopy or a display device.
-Example backends: PS creates `PostScript®
-<http://http://www.adobe.com/products/postscript/>`_ hardcopy, SVG
-creates `Scalable Vector Graphics <http://www.w3.org/Graphics/SVG/>`_
-hardcopy, Agg creates PNG output using the high quality `Anti-Grain
-Geometry <http://www.antigrain.com>`_ library that ships with
-matplotlib, GTK embeds matplotlib in a `Gtk+ <http://www.gtk.org/>`_
-application, GTKAgg uses the Anti-Grain renderer to create a figure
-and embed it a Gtk+ application, and so on for `PDF
-<http://www.adobe.com/products/acrobat/adobepdf.html>`_, `WxWidgets
-<http://www.wxpython.org/>`_, `Tkinter
-<http://docs.python.org/lib/module-Tkinter.html>`_ etc.
-
-matplotlib is used by many people in many different contexts. Some
-people want to automatically generate PostScript® files to send
-to a printer or publishers. Others deploy matplotlib on a web
-application server to generate PNG output for inclusion in
-dynamically-generated web pages. Some use matplotlib interactively
-from the Python shell in Tkinter on Windows™. My primary use is to
-embed matplotlib in a Gtk+ EEG application that runs on Windows, Linux
-and Macintosh OS X.
-
Added: trunk/matplotlib/doc/users/intro.rst
===================================================================
--- trunk/matplotlib/doc/users/intro.rst (rev 0)
+++ trunk/matplotlib/doc/users/intro.rst 2008-06-02 21:21:29 UTC (rev 5368)
@@ -0,0 +1,86 @@
+Introduction
+============
+
+matplotlib is a library for making 2D plots of arrays in `Python
+<http://www.python.org>`_. Although it has its origins in emulating
+the `MATLAB™ <http://www.mathworks.com>`_ graphics commands, it does
+not require MATLAB, and can be used in a Pythonic, object oriented
+way. Although matplotlib is written primarily in pure Python, it
+makes heavy use of `NumPy <http://www.numpy.org>`_ and other extension
+code to provide good performance even for large arrays.
+
+matplotlib is designed with the philosophy that you should be able to
+create simple plots with just a few commands, or just one! If you
+want to see a histogram of your data, you shouldn't need to
+instantiate objects, call methods, set properties, and so on; it
+should just work.
+
+For years, I used to use MATLAB exclusively for data analysis and
+visualization. MATLAB excels at making nice looking plots easy. When
+I began working with EEG data, I found that I needed to write
+applications to interact with my data, and developed and EEG analysis
+application in MATLAB. As the application grew in complexity,
+interacting with databases, http servers, manipulating complex data
+structures, I began to strain against the limitations of MATLAB as a
+programming language, and decided to start over in Python. Python
+more than makes up for all of MATLAB's deficiencies as a programming
+language, but I was having difficulty finding a 2D plotting package
+(for 3D `VTK <http://www.vtk.org/>`_) more than exceeds all of my needs).
+
+When I went searching for a Python plotting package, I had several
+requirements:
+
+* Plots should look great - publication quality. One important
+ requirement for me is that the text looks good (antialiased, etc.)
+
+* Postscript output for inclusion with TeX documents
+
+* Embeddable in a graphical user interface for application
+ development
+
+* Code should be easy enough that I can understand it and extend
+ it
+
+* Making plots should be easy
+
+Finding no package that suited me just right, I did what any
+self-respecting Python programmer would do: rolled up my sleeves and
+dived in. Not having any real experience with computer graphics, I
+decided to emulate MATLAB's plotting capabilities because that is
+something MATLAB does very well. This had the added advantage that
+many people have a lot of MATLAB experience, and thus they can
+quickly get up to steam plotting in python. From a developer's
+perspective, having a fixed user interface (the pylab interface) has
+been very useful, because the guts of the code base can be redesigned
+without affecting user code.
+
+The matplotlib code is conceptually divided into three parts: the
+*pylab interface* is the set of functions provided by
+:mod:`matplotlib.pylab` which allow the user to create plots with code
+quite similar to MATLAB figure generating code. The *matplotlib
+frontend* or *matplotlib API* is the set of classes that do the heavy
+lifting, creating and managing figures, text, lines, plots and so on.
+This is an abstract interface that knows nothing about output. The
+*backends* are device dependent drawing devices, aka renderers, that
+transform the frontend representation to hardcopy or a display device.
+Example backends: PS creates `PostScript®
+<http://http://www.adobe.com/products/postscript/>`_ hardcopy, SVG
+creates `Scalable Vector Graphics <http://www.w3.org/Graphics/SVG/>`_
+hardcopy, Agg creates PNG output using the high quality `Anti-Grain
+Geometry <http://www.antigrain.com>`_ library that ships with
+matplotlib, GTK embeds matplotlib in a `Gtk+ <http://www.gtk.org/>`_
+application, GTKAgg uses the Anti-Grain renderer to create a figure
+and embed it a Gtk+ application, and so on for `PDF
+<http://www.adobe.com/products/acrobat/adobepdf.html>`_, `WxWidgets
+<http://www.wxpython.org/>`_, `Tkinter
+<http://docs.python.org/lib/module-Tkinter.html>`_ etc.
+
+matplotlib is used by many people in many different contexts. Some
+people want to automatically generate PostScript® files to send
+to a printer or publishers. Others deploy matplotlib on a web
+application server to generate PNG output for inclusion in
+dynamically-generated web pages. Some use matplotlib interactively
+from the Python shell in Tkinter on Windows™. My primary use is to
+embed matplotlib in a Gtk+ EEG application that runs on Windows, Linux
+and Macintosh OS X.
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-02 21:01:55
|
Revision: 5367
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5367&view=rev
Author: jdh2358
Date: 2008-06-02 14:01:47 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
some more doc updates
Modified Paths:
--------------
trunk/matplotlib/doc/devel/add_new_projection.rst
trunk/matplotlib/doc/devel/coding_guide.rst
trunk/matplotlib/doc/devel/documenting_mpl.rst
trunk/matplotlib/doc/devel/index.rst
trunk/matplotlib/doc/faq/howto_faq.rst
trunk/matplotlib/doc/faq/index.rst
trunk/matplotlib/doc/faq/installing_faq.rst
trunk/matplotlib/doc/faq/troubleshooting_faq.rst
trunk/matplotlib/doc/users/artists.rst
trunk/matplotlib/doc/users/customizing.rst
trunk/matplotlib/doc/users/event_handling.rst
trunk/matplotlib/doc/users/index.rst
trunk/matplotlib/doc/users/mathtext.rst
trunk/matplotlib/doc/users/navigation_toolbar.rst
trunk/matplotlib/doc/users/pyplot_tutorial.rst
Modified: trunk/matplotlib/doc/devel/add_new_projection.rst
===================================================================
--- trunk/matplotlib/doc/devel/add_new_projection.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/devel/add_new_projection.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _adding-new-scales:
+
***********************************************
Adding new scales and projections to matplotlib
***********************************************
@@ -28,6 +30,7 @@
within a plot script, in third-party code, or in the matplotlib source
tree itself.
+.. _creating-new-scale:
Creating a new scale
====================
@@ -63,6 +66,8 @@
in :mod:`matplotlib.scale` that may be used as starting points.
+.. _creating-new-projection:
+
Creating a new projection
=========================
Modified: trunk/matplotlib/doc/devel/coding_guide.rst
===================================================================
--- trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,9 +1,16 @@
-***************
+.. _coding-guide:
+
+************
+Coding Guide
+************
+
+.. _version-control:
+
Version Control
-***************
+===============
svn checkouts
-=============
+-------------
Checking out everything in the trunk (matplotlib and toolkits)::
@@ -21,7 +28,7 @@
v0_91_maint mpl91 --username=youruser --password=yourpass
Committing changes
-==================
+------------------
When committing changes to matplotlib, there are a few things to bear
in mind.
@@ -74,12 +81,14 @@
> svn commit -F svnmerge-commit-message.txt
-***********
+
+.. _style-guide:
+
Style Guide
-***********
+===========
Importing and name spaces
-=========================
+-------------------------
For `numpy <http://www.numpy.org>`_, use::
@@ -115,7 +124,7 @@
you are importing a module or package.
Naming, spacing, and formatting conventions
-===========================================
+-------------------------------------------
In general, we want to hew as closely as possible to the standard
coding guidelines for python written by Guido in `PEP 0008
@@ -172,7 +181,7 @@
(add-hook 'local-write-file-hooks 'delete-trailing-whitespace)))
Keyword argument processing
-===========================
+---------------------------
Matplotlib makes extensive use of ``**kwargs`` for pass through
customizations from one function to another. A typical example is in
@@ -255,6 +264,8 @@
elif len(args) == 1:
...etc...
+.. _docstrings:
+
Documentation and Docstrings
============================
@@ -327,9 +338,11 @@
point" requirement above; hopefully we'll find a more elegant solution
before too long.
-********
+
+.. _licenses:
+
Licenses
-********
+========
Matplotlib only uses BSD compatible code. If you bring in code from
another project make sure it has a PSF, BSD, MIT or compatible
Modified: trunk/matplotlib/doc/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _documenting-matplotlib:
+
**********************
Documenting Matplotlib
**********************
@@ -56,6 +58,8 @@
.. _documentation: http://sphinx.pocoo.org/contents.html
+.. _referring-to-mpl-docs:
+
Referring to mpl documents
==========================
@@ -78,6 +82,8 @@
.. literalinclude:: ../mpl_data/matplotlibrc
+.. _internal-section-refs:
+
Internal section references
===========================
@@ -103,4 +109,39 @@
In addition, since underscores are widely used by Sphinx itself, let's prefer hyphens to separate words.
+.. _emacs-helpers:
+Emacs helpers
+=============
+
+There is an emacs mode `rst.el
+<http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_ which
+automates many important ReST tasks like building and updateing
+table-of-contents, and promoting or demoting section headings. Here
+is the basic ``.emacs`` configuration::
+
+ (require 'rst)
+ (setq auto-mode-alist
+ (append '(("\\.txt$" . rst-mode)
+ ("\\.rst$" . rst-mode)
+ ("\\.rest$" . rst-mode)) auto-mode-alist))
+
+
+Some helpful functions::
+
+ C-c TAB - rst-toc-insert
+
+ Insert table of contents at point
+
+ C-c C-u - rst-toc-update
+
+ Update the table of contents at point
+
+ C-c C-l rst-shift-region-left
+
+ Shift region to the left
+
+ C-c C-r rst-shift-region-right
+
+ Shift region to the right
+
Modified: trunk/matplotlib/doc/devel/index.rst
===================================================================
--- trunk/matplotlib/doc/devel/index.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/devel/index.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -7,8 +7,6 @@
:Release: |version|
:Date: |today|
-Introduction to developer's guide here **TODO**.
-
.. toctree::
coding_guide.rst
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.._ howto-faq:
+
*****
HOWTO
*****
@@ -25,7 +27,7 @@
The other properties that control the tick marker, and all markers,
are ``markerfacecolor``, ``markeredgecolor``, ``markeredgewidth``,
``markersize``. For more information on configuring ticks, see
-:ref:`artist-tut-axis` and :ref:`artist-tut-tick`.
+:ref:`axis-container` and :ref:`tick-container`.
.. _howto-webapp:
Modified: trunk/matplotlib/doc/faq/index.rst
===================================================================
--- trunk/matplotlib/doc/faq/index.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/faq/index.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,4 +1,4 @@
-.. _api-index:
+.. _faq-index:
####################
The Matplotlib FAQ
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _installing-faq:
+
==================
Installation FAQ
==================
@@ -2,4 +4,2 @@
-
-
How do I report a compilation problem?
@@ -22,7 +22,13 @@
* delete the ``build`` directory in the source tree
* delete ``site-packages/matplotlib`` directory in the Python
installation. The location of ``site-packages`` is
- platform-specific.
+ platform-specific. You can find out where matplotlib is installed by doing::
+
+ > python -c 'import matplotlib; print matplotlib.__file__'
+
+ and then making sure you remove the matplotlib directory (and
+ any matplotlib*.egg files) you find there.
+
* you may also want to clear some of the cache data that
matplotlib stores in your ``.matplotlib`` directory. You can
find the location of this directory by doing::
@@ -55,7 +61,7 @@
There are a two primary ways to configure your backend. One is to set
the ``backend`` parameter in you ``matplotlibrc`` file (see
-link:Configuring)::
+:ref:`customizing-matplotlib`)::
backend : WXAgg # use wxpython with antigrain (agg) rendering
Modified: trunk/matplotlib/doc/faq/troubleshooting_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _troubleshooting-faq:
+
===================
Troubleshooting FAQ
===================
@@ -2,2 +4,3 @@
+
.. _reporting-problems:
@@ -16,17 +19,27 @@
<http://lists.sourceforge.net/mailman/listinfo/matplotlib-users>`_:
* your operating system; on Linux/UNIX post the output of ``uname -a``
- * matplotlib version : ``import matplotlib; print matplotlib.__version__``
+
+ * matplotlib version::
+
+ python -c `import matplotlib; print matplotlib.__version__`
+
* where you obtained matplotlib (e.g. your Linux distribution's
packages or the matplotlib Sourceforge site)
- * any customizations to your ``matplotlibrc`` file
+
+ * any customizations to your ``matplotlibrc`` file (see
+ :ref:`customizing-matplotlib`).
+
* if the problem is reproducible, please try to provide a *minimal*,
standalone Python script that demonstrates the problem
+
* you can get very helpful debugging output from matlotlib by
running your script with a ``verbose-helpful`` or
``--verbose-debug`` flags and posting the verbose output the
- lists.
+ lists::
+ > python simple_plot.py --verbose-helpful > output.txt
+
If you compiled matplotlib yourself, please also provide
* any changes you have made to ``setup.py`` or ``setupext.py``
Modified: trunk/matplotlib/doc/users/artists.rst
===================================================================
--- trunk/matplotlib/doc/users/artists.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/artists.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _artist-tutorial:
+
***************
Artist tutorial
***************
@@ -136,6 +138,8 @@
.. image:: figures/fig_axes_labels_simple.png
:scale: 75
+.. _customizing-artists:
+
Customizing your objects
========================
@@ -231,6 +235,8 @@
at http://matplotlib.sourceforge.net/api.pdf for a listing of
properties for a give object.
+.. _object-containers:
+
Object containers
=================
Modified: trunk/matplotlib/doc/users/customizing.rst
===================================================================
--- trunk/matplotlib/doc/users/customizing.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/customizing.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _customizing-matplotlib:
+
Customizing matplotlib
======================
@@ -20,6 +22,8 @@
matplotlib.rc('lines', linewidth=2, color='r')
+.. _matplotlibrc-sample:
+
A sample matplotlibrc file
--------------------------
Modified: trunk/matplotlib/doc/users/event_handling.rst
===================================================================
--- trunk/matplotlib/doc/users/event_handling.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/event_handling.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _event-handling-tutorial:
+
***********************************
Event Handling and Picking Tutorial
***********************************
@@ -15,6 +17,7 @@
The events also understand the matplotlib coordinate system, and
report event locations in both pixel and data coordinates.
+.. _event-connections:
Event connections
=================
@@ -58,6 +61,7 @@
scroll_event MouseEvent mouse scroll wheel is rolled
===================== =========== ===================================
+.. _event-attributes:
Event attributes
================
@@ -316,6 +320,8 @@
plt.show()
+.. _object-picking:
+
Object Picking
==============
Modified: trunk/matplotlib/doc/users/index.rst
===================================================================
--- trunk/matplotlib/doc/users/index.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/index.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -7,6 +7,16 @@
:Release: |version|
:Date: |today|
+.. toctree::
+
+ pyplot_tutorial.rst
+ mathtext.rst
+ navigation_toolbar.rst
+ customizing.rst
+ artists.rst
+ event_handling.rst
+
+
matplotlib is a library for making 2D plots of arrays in `Python
<http://www.python.org>`_. Although it has its origins in emulating
the `MATLAB™ <http://www.mathworks.com>`_ graphics commands, it does
@@ -90,12 +100,3 @@
embed matplotlib in a Gtk+ EEG application that runs on Windows, Linux
and Macintosh OS X.
-.. toctree::
-
- pyplot_tutorial.rst
- mathtext.rst
- navigation_toolbar.rst
- customizing.rst
- artists.rst
- event_handling.rst
-
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,6 +1,9 @@
+.. _mathtext-tutorial:
+
Writing mathematical expressions
================================
+
You can use TeX markup in any matplotlib text string; see the
:mod:`matplotlib.mathtext` module documentation for details. Note
that you do not need to have TeX installed, since matplotlib ships its
@@ -35,6 +38,7 @@
.. TODO: Include a complete list here
+
Subscripts and superscripts
---------------------------
Modified: trunk/matplotlib/doc/users/navigation_toolbar.rst
===================================================================
--- trunk/matplotlib/doc/users/navigation_toolbar.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/navigation_toolbar.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _navigation-toolbar:
+
Interactive navigation
======================
Modified: trunk/matplotlib/doc/users/pyplot_tutorial.rst
===================================================================
--- trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-02 18:52:09 UTC (rev 5366)
+++ trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-02 21:01:47 UTC (rev 5367)
@@ -1,3 +1,5 @@
+.. _pyplot-tutorial:
+
***************
pyplot tutorial
***************
@@ -62,6 +64,8 @@
+.. _controlling-line-properties:
+
Controlling line properties
===========================
@@ -147,6 +151,8 @@
antialiased or aa: [True | False]
...snip
+.. _multiple-figs-axes:
+
Working with multiple figure and axes
=====================================
@@ -202,6 +208,8 @@
You can clear the current figure with :func:`~matplotlib.pyplot.clf`
and the current axes with :func:`~matplotlib.pyplot.cla`.
+.. _working-with-text:
+
Working with text
=================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-02 18:53:14
|
Revision: 5366
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5366&view=rev
Author: jdh2358
Date: 2008-06-02 11:52:09 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
a couple of FAQs
Modified Paths:
--------------
trunk/matplotlib/doc/devel/documenting_mpl.rst
trunk/matplotlib/doc/devel/index.rst
trunk/matplotlib/doc/faq/howto_faq.rst
trunk/matplotlib/doc/faq/installing_faq.rst
trunk/matplotlib/doc/faq/troubleshooting_faq.rst
trunk/matplotlib/doc/users/artists.rst
trunk/matplotlib/doc/users/index.rst
Modified: trunk/matplotlib/doc/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -77,3 +77,30 @@
.. literalinclude:: ../mpl_data/matplotlibrc
+
+Internal section references
+===========================
+
+To maximize internal consistency in section labeling and references,
+use hypen separated, descriptive labels for section references, eg::
+
+ .. _howto-webapp:
+
+and refer to it using the standard reference syntax::
+
+ See :ref:`howto-webapp`
+
+Keep in mind that we may want to reorganize the contents later, so
+let's avoid top level names in references like ``user`` or ``devel``
+or ``faq`` unless necesssary, because for example the FAQ "what is a
+backend?" could later become part of the users guide, so the label::
+
+ .. _what-is-a-backend
+
+is better than::
+
+ .. _faq-backend
+
+In addition, since underscores are widely used by Sphinx itself, let's prefer hyphens to separate words.
+
+
Modified: trunk/matplotlib/doc/devel/index.rst
===================================================================
--- trunk/matplotlib/doc/devel/index.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/devel/index.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -1,4 +1,4 @@
-.. _developers_guide-index:
+.. _developers-guide-index:
###################################
The Matplotlib Developers's Guide
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -2,6 +2,33 @@
HOWTO
*****
+.. _howto-ticks:
+
+How do I configure the tick linewidths?
+=======================================
+
+In matplotlib, the ticks are *markers*. All
+:class:`~matplotlib.lines.Line2D` objects support a line (solid,
+dashed, etc) and a marker (circle, square, tick). The tick linewidth
+is controlled by the "markeredgewidth" property::
+
+ import matplotlib.pyplot as plt
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ ax.plot(range(10))
+
+ for line in ax.get_xticklines() + ax.get_yticklines():
+ line.set_markersize(10)
+
+ plt.show()
+
+The other properties that control the tick marker, and all markers,
+are ``markerfacecolor``, ``markeredgecolor``, ``markeredgewidth``,
+``markersize``. For more information on configuring ticks, see
+:ref:`artist-tut-axis` and :ref:`artist-tut-tick`.
+
+.. _howto-webapp:
+
How do I use matplotlib in a web application server?
====================================================
@@ -24,6 +51,9 @@
matplotlib.use('Agg')
import matplotlib.pyplot as plt
+For more on configuring your backend, see
+:ref:`what-is-a-backend`.
+
Alternatively, you can avoid pylab/pyplot altogeher, which will give
you a little more control, by calling the API directly as shown in
`agg_oo.py <http://matplotlib.sf.net/examples/api/agg_oo.py>`_ .
@@ -50,7 +80,7 @@
TODO
-How do I use matplotlib with dhango?
+How do I use matplotlib with django?
------------------------------------
TODO
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -2,10 +2,12 @@
Installation FAQ
==================
+
+
How do I report a compilation problem?
======================================
-See :ref:`reporting_problems`.
+See :ref:`reporting-problems`.
How do I cleanly rebuild and reinstall everything?
==================================================
@@ -26,4 +28,98 @@
find the location of this directory by doing::
import matplotlib
- print matplotlib.get_configdir()
\ No newline at end of file
+ print matplotlib.get_configdir()
+
+.. _what-is-a-backend:
+
+What is a backend?
+==================
+
+A lot of documentation on the website and in the mailing lists refers
+to the "backend" and many new users are confused by this term.
+matplotlib targets many different use cases and output formats. Some
+people use matplotlib interactively from the python shell and have
+plotting windows pop up when they type commands. Some people embed
+matplotlib into graphical user interfaces like wxpython or pygtk to
+build rich applications. Others use matplotlib in batch scripts, to
+generate postscript images from some numerical simulations, and still
+others in web application servers to dynamically serve up graphs.
+
+To support all of these use cases, matplotlib can target different
+outputs, and each of these capabililities is called a backend (the
+"frontend" is the user facing code, ie the plotting code, whereas the
+"backend" does all the dirty work behind the scenes to make the
+figure. There are two types of backends: user interface backends (for
+use in pygtk, wxpython, tkinter, qt or fltk) and hardcopy backends to
+make image files (PNG, SVG, PDF, PS).
+
+There are a two primary ways to configure your backend. One is to set
+the ``backend`` parameter in you ``matplotlibrc`` file (see
+link:Configuring)::
+
+ backend : WXAgg # use wxpython with antigrain (agg) rendering
+
+The other is to use the matplotlib :func:`~matplotlib.use` directive::
+
+ import matplotlib
+ matplotlib.use('PS') # generate postscript output by default
+
+If you use the ``use`` directive, this must be done before importing
+:mod:`matplotlib.pyplot` or :mod:`matplotlib.pylab`.
+
+If you are unsure what to do, and just want to get cranking, just set
+your backend to `TkAgg`. This will do the right thing for 95% of the
+users. It gives you the option of running your scripts in batch or
+working interactively from the python shell, with the least amount of
+hassles, and is smart enough to do the right thing when you ask for
+postscript, or pdf, or other image formats.
+
+If however, you want to write graphical user interfaces, or a web
+application server (:ref:`howto-webapp`), or need a better
+understanding of what is going on, read on. To make things a little
+more customizable for graphical user interfaces, matplotlib separates
+the concept of the renderer (the thing that actually does the drawing)
+from the canvas (the place where the drawing goes). The canonical
+renderer for user interfaces is ``Agg`` which uses the `antigrain
+<http://antigrain.html>`_ C++ library to make a raster (pixel) image
+of the figure. All of the user interfaces can be used with agg
+rendering, eg ``WXAgg``, ``GTKAgg``, ``QTAgg``, ``TkAgg``. In
+addition, some of the user interfaces support other rendering engines.
+For example, with GTK, you can also select GDK rendering (backend
+``GTK``) or Cairo rendering (backend ``GTKCairo``).
+
+For the rendering engines, one can also distinguish between vector or
+raster renderers. Vector issue drawing commands like "draw a line
+from this point to this point" and hence are scale free, and raster
+backends generate a pixel represenation of the line whose accuracy
+depends on a DPI setting.
+
+Here is a summary of the matplotlib rendering backends:
+
+=============================== =====================================================================================
+Renderer (Filetypes) Description
+=============================== =====================================================================================
+Agg (png) raster - high quality images using the `antigrain <http://antigrain.html>`_ engine
+PS (ps, eps) vector - postscript output
+PDF (pdf) vector - portable document format
+SVG (svg) vector - scalar vector graphics
+Cairo (png, ps, pdf, svn, ...) vector - `cairo graphics <http://cairographics.org>`_
+GDK (png, jpg, tiff..) raster - the GDK drawing API for GTK
+=============================== =====================================================================================
+
+And here are the user interfaces and renderer combinations supported:
+
+============ ===================================================================================================
+Backend Description
+============ ===================================================================================================
+GTKAgg Agg rendering to a GTK canvas (`pygtk <http://www.pygtk.org>`_)
+GTK GDK rendering to a GTK canvas (not recommended) (`pygtk <http://www.pygtk.org>`_)
+GTKCairo Cairo rendering to a GTK Canvas (`pygtk <http://www.pygtk.org>`_)
+WXAgg Agg rendering to to a WX canvas (`wxpython <http://www.wxpython.org>`_)
+WX Native WX drawing to a WX Canvas (not recommended) (`wxpython <http://www.wxpython.org>`_)
+TkAgg Agg rendering to a Tkinter canvas (`tkinter <http://wiki.python.org/moin/TkInter>`_)
+QtAgg Agg rendering to a Qt canvas (`pyqt <http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_)
+Qt4Agg Agg rendering to a Qt4 canvas (`pyqt <http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_)
+FLTKAgg Agg rendering to a FLTK canvas (`pyfltk <http://pyfltk.sourceforge.net>`)_
+============ ===================================================================================================
+
Modified: trunk/matplotlib/doc/faq/troubleshooting_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -2,7 +2,7 @@
Troubleshooting FAQ
===================
-.. _reporting_problems:
+.. _reporting-problems:
How do I report a problem?
==========================
Modified: trunk/matplotlib/doc/users/artists.rst
===================================================================
--- trunk/matplotlib/doc/users/artists.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/users/artists.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -247,6 +247,8 @@
'linear' or 'log'. In this section we'll review where the various
container objects store the ``Artists`` that you want to get at.
+.. _figure-container:
+
Figure container
----------------
@@ -338,6 +340,7 @@
texts A list Figure Text instances
================ ===============================================================
+.. _axes-container:
Axes container
--------------
@@ -515,6 +518,8 @@
yaxis matplotlib.axis.YAxis instance
============== ======================================
+.. _axis-container:
+
Axis containers
---------------
@@ -599,6 +604,7 @@
:scale: 75
+.. _tick-container:
Tick containers
---------------
Modified: trunk/matplotlib/doc/users/index.rst
===================================================================
--- trunk/matplotlib/doc/users/index.rst 2008-06-02 18:26:43 UTC (rev 5365)
+++ trunk/matplotlib/doc/users/index.rst 2008-06-02 18:52:09 UTC (rev 5366)
@@ -1,4 +1,4 @@
-.. _users_guide-index:
+.. _users-guide-index:
#############################
The Matplotlib User's Guide
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-02 18:28:13
|
Revision: 5365
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5365&view=rev
Author: mdboom
Date: 2008-06-02 11:26:43 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
Include our own XML escaping function for micro-Python installs that
don't include xml.sax (such as that on the maemo platform)
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/pyparsing.py
Modified: trunk/matplotlib/lib/matplotlib/pyparsing.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-02 17:57:28 UTC (rev 5364)
+++ trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-02 18:26:43 UTC (rev 5365)
@@ -27,18 +27,18 @@
"""
pyparsing module - Classes and methods to define and execute parsing grammars
-The pyparsing module is an alternative approach to creating and executing simple grammars,
+The pyparsing module is an alternative approach to creating and executing simple grammars,
vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
-don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
+don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
provides a library of classes that you use to construct the grammar directly in Python.
Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
from pyparsing import Word, alphas
-
+
# define grammar of a greeting
- greet = Word( alphas ) + "," + Word( alphas ) + "!"
-
+ greet = Word( alphas ) + "," + Word( alphas ) + "!"
+
hello = "Hello, World!"
print hello, "->", greet.parseString( hello )
@@ -46,10 +46,10 @@
Hello, World! -> ['Hello', ',', 'World', '!']
-The Python representation of the grammar is quite readable, owing to the self-explanatory
+The Python representation of the grammar is quite readable, owing to the self-explanatory
class names, and the use of '+', '|' and '^' operators.
-The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an
+The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an
object with named attributes.
The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
@@ -68,7 +68,25 @@
import warnings
import re
import sre_constants
-import xml.sax.saxutils
+try:
+ from xml.sax.saxutils import escape as xml_escape
+except ImportError:
+ def xml_escape(data, entities={}):
+ """Escape &, <, and > in a string of data.
+
+ You can escape other strings of data by passing a dictionary as
+ the optional entities parameter. The keys and values must all be
+ strings; each key will be replaced with its corresponding value.
+ """
+
+ # must do ampersand first
+ data = data.replace("&", "&")
+ data = data.replace(">", ">")
+ data = data.replace("<", "<")
+ if entities:
+ data = __dict_replace(data, entities)
+ return data
+
#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
def _ustr(obj):
@@ -80,7 +98,7 @@
# If this works, then _ustr(obj) has the same behaviour as str(obj), so
# it won't break any existing code.
return str(obj)
-
+
except UnicodeEncodeError, e:
# The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
# state that "The return value must be a string object". However, does a
@@ -101,17 +119,17 @@
class _Constants(object):
pass
-
+
alphas = string.lowercase + string.uppercase
nums = string.digits
hexnums = nums + "ABCDEFabcdef"
-alphanums = alphas + nums
+alphanums = alphas + nums
class ParseBaseException(Exception):
"""base exception class for all parsing runtime exceptions"""
__slots__ = ( "loc","msg","pstr","parserElement" )
# Performance tuning: we construct a *lot* of these, so keep this
- # constructor as small and fast as possible
+ # constructor as small and fast as possible
def __init__( self, pstr, loc=0, msg=None, elem=None ):
self.loc = loc
if msg is None:
@@ -143,7 +161,7 @@
def __repr__( self ):
return _ustr(self)
def markInputline( self, markerString = ">!<" ):
- """Extracts the exception line from the input string, and marks
+ """Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
@@ -161,7 +179,7 @@
- line - returns the line containing the exception text
"""
pass
-
+
class ParseFatalException(ParseBaseException):
"""user-throwable exception thrown when inconsistent parse content
is found; stops all parsing immediately"""
@@ -184,7 +202,7 @@
"""exception thrown by validate() if the grammar could be improperly recursive"""
def __init__( self, parseElementList ):
self.parseElementTrace = parseElementList
-
+
def __str__( self ):
return "RecursiveGrammarException: %s" % self.parseElementTrace
@@ -209,7 +227,7 @@
retobj = object.__new__(cls)
retobj.__doinit = True
return retobj
-
+
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, toklist, name=None, asList=True, modal=True ):
@@ -226,7 +244,7 @@
# this line is related to debugging the asXML bug
#~ asList = False
-
+
if name:
if not modal:
self.__accumNames[name] = 0
@@ -234,7 +252,7 @@
name = _ustr(name) # will always return a str, but use _ustr for consistency
self.__name = name
if not toklist in (None,'',[]):
- if isinstance(toklist,basestring):
+ if isinstance(toklist,basestring):
toklist = [ toklist ]
if asList:
if isinstance(toklist,ParseResults):
@@ -269,7 +287,7 @@
sub = v
if isinstance(sub,ParseResults):
sub.__parent = wkref(self)
-
+
def __delitem__( self, i ):
if isinstance(i,(int,slice)):
del self.__toklist[i]
@@ -278,20 +296,20 @@
def __contains__( self, k ):
return self.__tokdict.has_key(k)
-
+
def __len__( self ): return len( self.__toklist )
def __bool__(self): return len( self.__toklist ) > 0
def __nonzero__( self ): return self.__bool__()
def __iter__( self ): return iter( self.__toklist )
- def keys( self ):
+ def keys( self ):
"""Returns all named result keys."""
return self.__tokdict.keys()
-
- def items( self ):
+
+ def items( self ):
"""Returns all named result keys and values as a list of tuples."""
return [(k,self[k]) for k in self.__tokdict.keys()]
-
- def values( self ):
+
+ def values( self ):
"""Returns all named result values."""
return [ v[-1][0] for v in self.__tokdict.values() ]
@@ -310,7 +328,7 @@
ret = self.copy()
ret += other
return ret
-
+
def __iadd__( self, other ):
if other.__tokdict:
offset = len(self.__toklist)
@@ -326,7 +344,7 @@
self.__accumNames.update( other.__accumNames )
del other
return self
-
+
def __repr__( self ):
return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
@@ -375,7 +393,7 @@
ret.__accumNames.update( self.__accumNames )
ret.__name = self.__name
return ret
-
+
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
"""Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
nl = "\n"
@@ -383,28 +401,28 @@
namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist ] )
nextLevelIndent = indent + " "
-
+
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
-
+
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
-
+
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
-
+
out += [ nl, indent, "<", selfTag, ">" ]
-
+
worklist = self.__toklist
for i,res in enumerate(worklist):
if isinstance(res,ParseResults):
@@ -428,11 +446,11 @@
continue
else:
resTag = "ITEM"
- xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
+ xmlBodyText = xml_escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
-
+
out += [ nl, indent, "</", selfTag, ">" ]
return "".join(out)
@@ -442,7 +460,7 @@
if sub is v:
return k
return None
-
+
def getName(self):
"""Returns the results name for this token expression."""
if self.__name:
@@ -453,13 +471,13 @@
return par.__lookup(self)
else:
return None
- elif (len(self) == 1 and
+ elif (len(self) == 1 and
len(self.__tokdict) == 1 and
self.__tokdict.values()[0][0][1] in (0,-1)):
return self.__tokdict.keys()[0]
else:
return None
-
+
def dump(self,indent='',depth=0):
"""Diagnostic method for listing out the contents of a ParseResults.
Accepts an optional indent argument so that this string can be embedded
@@ -491,7 +509,7 @@
self.__parent is not None and self.__parent() or None,
self.__accumNames,
self.__name ) )
-
+
def __setstate__(self,state):
self.__toklist = state[0]
self.__tokdict, \
@@ -521,7 +539,7 @@
def lineno(loc,strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
-
+
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing <TAB>s, and suggested methods to maintain a
@@ -545,7 +563,7 @@
def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
print "Matched",_ustr(expr),"->",toks.asList()
-
+
def _defaultExceptionDebugAction( instring, loc, expr, exc ):
print "Exception raised:", _ustr(exc)
@@ -556,13 +574,13 @@
class ParserElement(object):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS = " \n\t\r"
-
+
def setDefaultWhitespaceChars( chars ):
"""Overrides the default whitespace chars
"""
ParserElement.DEFAULT_WHITE_CHARS = chars
setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
-
+
def __init__( self, savelist=False ):
self.parseAction = list()
self.failAction = None
@@ -605,7 +623,7 @@
return self
def setResultsName( self, name, listAllMatches=False ):
- """Define name for referencing matching tokens as a nested attribute
+ """Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original ParserElement object;
this is so that the client can define a basic element, such as an
@@ -698,7 +716,7 @@
pass
return tmp
normalizeParseActionArgs = staticmethod(normalizeParseActionArgs)
-
+
def setParseAction( self, *fns, **kwargs ):
"""Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
@@ -709,7 +727,7 @@
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
-
+
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing <TAB>s, and suggested methods to maintain a
@@ -727,8 +745,8 @@
return self
def setFailAction( self, fn ):
- """Define action to perform if parsing fails at this expression.
- Fail acton fn is a callable function that takes the arguments
+ """Define action to perform if parsing fails at this expression.
+ Fail acton fn is a callable function that takes the arguments
fn(s,loc,expr,err) where:
- s = string being parsed
- loc = location where expression match was attempted and failed
@@ -738,7 +756,7 @@
if it is desired to stop parsing immediately."""
self.failAction = fn
return self
-
+
def skipIgnorables( self, instring, loc ):
exprsFound = True
while exprsFound:
@@ -755,13 +773,13 @@
def preParse( self, instring, loc ):
if self.ignoreExprs:
loc = self.skipIgnorables( instring, loc )
-
+
if self.skipWhitespace:
wt = self.whiteChars
instrlen = len(instring)
while loc < instrlen and instring[loc] in wt:
loc += 1
-
+
return loc
def parseImpl( self, instring, loc, doActions=True ):
@@ -808,7 +826,7 @@
raise ParseException( instring, len(instring), self.errmsg, self )
else:
loc,tokens = self.parseImpl( instring, preloc, doActions )
-
+
tokens = self.postParse( instring, loc, tokens )
retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
@@ -818,9 +836,9 @@
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
+ retTokens = ParseResults( tokens,
+ self.resultsName,
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
except ParseException, err:
#~ print "Exception raised in user parse action:", err
@@ -831,9 +849,9 @@
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
+ retTokens = ParseResults( tokens,
+ self.resultsName,
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
if debugging:
@@ -845,7 +863,7 @@
def tryParse( self, instring, loc ):
return self._parse( instring, loc, doActions=False )[0]
-
+
# this method gets repeatedly called during backtracking with the same arguments -
# we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
@@ -873,20 +891,20 @@
def resetCache():
ParserElement._exprArgCache.clear()
resetCache = staticmethod(resetCache)
-
+
_packratEnabled = False
def enablePackrat():
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
- Repeated parse attempts at the same string location (which happens
- often in many complex grammars) can immediately return a cached value,
+ Repeated parse attempts at the same string location (which happens
+ often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
-
- This speedup may break existing programs that use parse actions that
+
+ This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method ParserElement.enablePackrat(). If
- your program uses psyco to "compile as you go", you must call
+ your program uses psyco to "compile as you go", you must call
enablePackrat before calling psyco.full(). If you do not do this,
Python will crash. For best results, call enablePackrat() immediately
after importing pyparsing.
@@ -898,21 +916,21 @@
def parseString( self, instring ):
"""Execute the parse expression with the given string.
- This is the main interface to the client code, once the complete
+ This is the main interface to the client code, once the complete
expression has been built.
-
+
Note: parseString implicitly calls expandtabs() on the input string,
- in order to report proper column numbers in parse actions.
+ in order to report proper column numbers in parse actions.
If the input string contains tabs and
- the grammar uses parse actions that use the loc argument to index into the
- string being parsed, you can ensure you have a consistent view of the input
+ the grammar uses parse actions that use the loc argument to index into the
+ string being parsed, you can ensure you have a consistent view of the input
string by:
- calling parseWithTabs on your grammar before calling parseString
(see L{I{parseWithTabs}<parseWithTabs>})
- - define your parse action using the full (s,loc,toks) signature, and
+ - define your parse action using the full (s,loc,toks) signature, and
reference the input string using the parse action's s argument
- - explictly expand the tabs in your input string before calling
- parseString
+ - explictly expand the tabs in your input string before calling
+ parseString
"""
ParserElement.resetCache()
if not self.streamlined:
@@ -927,18 +945,18 @@
return tokens
def scanString( self, instring, maxMatches=sys.maxint ):
- """Scan the input string for expression matches. Each match will return the
+ """Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
maxMatches argument, to clip scanning after 'n' matches are found.
-
+
Note that the start and end locations are reported relative to the string
- being parsed. See L{I{parseString}<parseString>} for more information on parsing
+ being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs."""
if not self.streamlined:
self.streamline()
for e in self.ignoreExprs:
e.streamline()
-
+
if not self.keepTabs:
instring = _ustr(instring).expandtabs()
instrlen = len(instring)
@@ -957,13 +975,13 @@
matches += 1
yield tokens, preloc, nextLoc
loc = nextLoc
-
+
def transformString( self, instring ):
"""Extension to scanString, to modify matching text with modified tokens that may
- be returned from a parse action. To use transformString, define a grammar and
- attach a parse action to it that modifies the returned token list.
- Invoking transformString() on a target string will then scan for matches,
- and replace the matched text patterns according to the logic in the parse
+ be returned from a parse action. To use transformString, define a grammar and
+ attach a parse action to it that modifies the returned token list.
+ Invoking transformString() on a target string will then scan for matches,
+ and replace the matched text patterns according to the logic in the parse
action. transformString() returns the resulting transformed string."""
out = []
lastE = 0
@@ -989,7 +1007,7 @@
maxMatches argument, to clip searching after 'n' matches are found.
"""
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
-
+
def __add__(self, other ):
"""Implementation of + operator - returns And"""
if isinstance( other, basestring ):
@@ -1081,7 +1099,7 @@
return Suppress( self )
def leaveWhitespace( self ):
- """Disables the skipping of whitespace before matching the characters in the
+ """Disables the skipping of whitespace before matching the characters in the
ParserElement's defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
@@ -1095,16 +1113,16 @@
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self
-
+
def parseWithTabs( self ):
"""Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
- Must be called before parseString when the input grammar contains elements that
+ Must be called before parseString when the input grammar contains elements that
match <TAB> characters."""
self.keepTabs = True
return self
-
+
def ignore( self, other ):
- """Define expression to be ignored (e.g., comments) while doing pattern
+ """Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
"""
@@ -1117,8 +1135,8 @@
def setDebugActions( self, startAction, successAction, exceptionAction ):
"""Enable display of debugging messages while doing pattern matching."""
- self.debugActions = (startAction or _defaultStartDebugAction,
- successAction or _defaultSuccessDebugAction,
+ self.debugActions = (startAction or _defaultStartDebugAction,
+ successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self
@@ -1137,15 +1155,15 @@
def __repr__( self ):
return _ustr(self)
-
+
def streamline( self ):
self.streamlined = True
self.strRepr = None
return self
-
+
def checkRecursion( self, parseElementList ):
pass
-
+
def validate( self, validateTrace=[] ):
"""Check defined expressions for valid structure, check for infinite recursive definitions."""
self.checkRecursion( [] )
@@ -1165,7 +1183,7 @@
def getException(self):
return ParseException("",0,self.errmsg,self)
-
+
def __getattr__(self,aname):
if aname == "myException":
self.myException = ret = self.getException();
@@ -1184,8 +1202,8 @@
self.errmsg = "Expected " + self.name
#s.myException.msg = self.errmsg
return s
-
+
class Empty(Token):
"""An empty token, will always match."""
def __init__( self ):
@@ -1204,7 +1222,7 @@
self.mayIndexError = False
self.errmsg = "Unmatchable token"
#self.myException.msg = self.errmsg
-
+
def parseImpl( self, instring, loc, doActions=True ):
exc = self.myException
exc.loc = loc
@@ -1221,7 +1239,7 @@
try:
self.firstMatchChar = matchString[0]
except IndexError:
- warnings.warn("null string passed to Literal; use Empty() instead",
+ warnings.warn("null string passed to Literal; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.__class__ = Empty
self.name = '"%s"' % _ustr(self.match)
@@ -1245,7 +1263,7 @@
raise exc
class Keyword(Token):
- """Token to exactly match a specified string as a keyword, that is, it must be
+ """Token to exactly match a specified string as a keyword, that is, it must be
immediately followed by a non-keyword character. Compare with Literal::
Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
@@ -1255,7 +1273,7 @@
matching, default is False.
"""
DEFAULT_KEYWORD_CHARS = alphanums+"_$"
-
+
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
super(Keyword,self).__init__()
self.match = matchString
@@ -1263,7 +1281,7 @@
try:
self.firstMatchChar = matchString[0]
except IndexError:
- warnings.warn("null string passed to Keyword; use Empty() instead",
+ warnings.warn("null string passed to Keyword; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.name = '"%s"' % self.match
self.errmsg = "Expected " + self.name
@@ -1293,17 +1311,17 @@
exc.loc = loc
exc.pstr = instring
raise exc
-
+
def copy(self):
c = super(Keyword,self).copy()
c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
return c
-
+
def setDefaultKeywordChars( chars ):
"""Overrides the default Keyword chars
"""
Keyword.DEFAULT_KEYWORD_CHARS = chars
- setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
+ setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
class CaselessLiteral(Literal):
@@ -1361,9 +1379,9 @@
else:
self.bodyCharsOrig = initChars
self.bodyChars = _str2dict(initChars)
-
+
self.maxSpecified = max > 0
-
+
if min < 1:
raise ValueError, "cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted"
@@ -1383,7 +1401,7 @@
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.asKeyword = asKeyword
-
+
if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
if self.bodyCharsOrig == self.initCharsOrig:
self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
@@ -1401,7 +1419,7 @@
self.re = re.compile( self.reString )
except:
self.re = None
-
+
def parseImpl( self, instring, loc, doActions=True ):
if self.re:
result = self.re.match(instring,loc)
@@ -1410,10 +1428,10 @@
exc.loc = loc
exc.pstr = instring
raise exc
-
+
loc = result.end()
return loc,result.group()
-
+
if not(instring[ loc ] in self.initChars):
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
@@ -1428,7 +1446,7 @@
maxloc = min( maxloc, instrlen )
while loc < maxloc and instring[loc] in bodychars:
loc += 1
-
+
throwException = False
if loc - start < self.minLen:
throwException = True
@@ -1453,15 +1471,15 @@
except:
pass
-
+
if self.strRepr is None:
-
+
def charsAsStr(s):
if len(s)>4:
return s[:4]+"..."
else:
return s
-
+
if ( self.initCharsOrig != self.bodyCharsOrig ):
self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
else:
@@ -1477,19 +1495,19 @@
def __init__( self, pattern, flags=0):
"""The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags."""
super(Regex,self).__init__()
-
+
if len(pattern) == 0:
- warnings.warn("null string passed to Regex; use Empty() instead",
+ warnings.warn("null string passed to Regex; use Empty() instead",
SyntaxWarning, stacklevel=2)
-
+
self.pattern = pattern
self.flags = flags
-
+
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error,e:
- warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
+ warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
SyntaxWarning, stacklevel=2)
raise
@@ -1498,7 +1516,7 @@
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.mayReturnEmpty = True
-
+
def parseImpl( self, instring, loc, doActions=True ):
result = self.re.match(instring,loc)
if not result:
@@ -1506,7 +1524,7 @@
exc.loc = loc
exc.pstr = instring
raise exc
-
+
loc = result.end()
d = result.groupdict()
ret = ParseResults(result.group())
@@ -1514,16 +1532,16 @@
for k in d.keys():
ret[k] = d[k]
return loc,ret
-
+
def __str__( self ):
try:
return super(Regex,self).__str__()
except:
pass
-
+
if self.strRepr is None:
self.strRepr = "Re:(%s)" % repr(self.pattern)
-
+
return self.strRepr
@@ -1541,13 +1559,13 @@
- endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
"""
super(QuotedString,self).__init__()
-
+
# remove white space from quote chars - wont work anyway
quoteChar = quoteChar.strip()
if len(quoteChar) == 0:
warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
-
+
if endQuoteChar is None:
endQuoteChar = quoteChar
else:
@@ -1555,7 +1573,7 @@
if len(endQuoteChar) == 0:
warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
-
+
self.quoteChar = quoteChar
self.quoteCharLen = len(quoteChar)
self.firstQuoteChar = quoteChar[0]
@@ -1564,7 +1582,7 @@
self.escChar = escChar
self.escQuote = escQuote
self.unquoteResults = unquoteResults
-
+
if multiline:
self.flags = re.MULTILINE | re.DOTALL
self.pattern = r'%s(?:[^%s%s]' % \
@@ -1580,7 +1598,7 @@
if len(self.endQuoteChar) > 1:
self.pattern += (
'|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
- _escapeRegexRangeChars(self.endQuoteChar[i]))
+ _escapeRegexRangeChars(self.endQuoteChar[i]))
for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
)
if escQuote:
@@ -1589,12 +1607,12 @@
self.pattern += (r'|(?:%s.)' % re.escape(escChar))
self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
-
+
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error,e:
- warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
+ warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
SyntaxWarning, stacklevel=2)
raise
@@ -1603,7 +1621,7 @@
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.mayReturnEmpty = True
-
+
def parseImpl( self, instring, loc, doActions=True ):
result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
if not result:
@@ -1611,15 +1629,15 @@
exc.loc = loc
exc.pstr = instring
raise exc
-
+
loc = result.end()
ret = result.group()
-
+
if self.unquoteResults:
-
+
# strip off quotes
ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
-
+
if isinstance(ret,basestring):
# replace escaped characters
if self.escChar:
@@ -1630,22 +1648,22 @@
ret = ret.replace(self.escQuote, self.endQuoteChar)
return loc, ret
-
+
def __str__( self ):
try:
return super(QuotedString,self).__str__()
except:
pass
-
+
if self.strRepr is None:
self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
-
+
return self.strRepr
class CharsNotIn(Token):
"""Token for matching words composed of characters *not* in a given set.
- Defined with string containing all disallowed characters, and an optional
+ Defined with string containing all disallowed characters, and an optional
minimum, maximum, and/or exact length. The default value for min is 1 (a
minimum value < 1 is not valid); the default values for max and exact
are 0, meaning no maximum or exact length restriction.
@@ -1654,7 +1672,7 @@
super(CharsNotIn,self).__init__()
self.skipWhitespace = False
self.notChars = notChars
-
+
if min < 1:
raise ValueError, "cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted"
@@ -1668,7 +1686,7 @@
if exact > 0:
self.maxLen = exact
self.minLen = exact
-
+
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = ( self.minLen == 0 )
@@ -1682,7 +1700,7 @@
exc.loc = loc
exc.pstr = instring
raise exc
-
+
start = loc
loc += 1
notchars = self.notChars
@@ -1711,7 +1729,7 @@
self.strRepr = "!W:(%s...)" % self.notChars[:4]
else:
self.strRepr = "!W:(%s)" % self.notChars
-
+
return self.strRepr
class White(Token):
@@ -1747,7 +1765,7 @@
if exact > 0:
self.maxLen = exact
self.minLen = exact
-
+
def parseImpl( self, instring, loc, doActions=True ):
if not(instring[ loc ] in self.matchWhite):
#~ raise ParseException( instring, loc, self.errmsg )
@@ -1834,7 +1852,7 @@
self.setWhitespaceChars( " \t" )
self.errmsg = "Expected end of line"
#self.myException.msg = self.errmsg
-
+
def parseImpl( self, instring, loc, doActions=True ):
if loc<len(instring):
if instring[loc] == "\n":
@@ -1859,7 +1877,7 @@
super(StringStart,self).__init__()
self.errmsg = "Expected start of text"
#self.myException.msg = self.errmsg
-
+
def parseImpl( self, instring, loc, doActions=True ):
if loc != 0:
# see if entire string up to here is just whitespace and ignoreables
@@ -1877,7 +1895,7 @@
super(StringEnd,self).__init__()
self.errmsg = "Expected end of text"
#self.myException.msg = self.errmsg
-
+
def parseImpl( self, instring, loc, doActions=True ):
if loc < len(instring):
#~ raise ParseException( instring, loc, "Expected end of text" )
@@ -1942,7 +1960,7 @@
return super(ParseExpression,self).__str__()
except:
pass
-
+
if self.strRepr is None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
return self.strRepr
@@ -1982,7 +2000,7 @@
def setResultsName( self, name, listAllMatches=False ):
ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
return ret
-
+
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
for e in self.exprs:
@@ -2019,24 +2037,24 @@
if isinstance( other, basestring ):
other = Literal( other )
return self.append( other ) #And( [ self, other ] )
-
+
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
if not e.mayReturnEmpty:
break
-
+
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-
+
return self.strRepr
-
+
class Or(ParseExpression):
"""Requires that at least one ParseExpression is found.
If two expressions match, the expression that matches the longest string will be used.
@@ -2049,7 +2067,7 @@
if e.mayReturnEmpty:
self.mayReturnEmpty = True
break
-
+
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxMatchLoc = -1
@@ -2068,7 +2086,7 @@
if loc2 > maxMatchLoc:
maxMatchLoc = loc2
maxMatchExp = e
-
+
if maxMatchLoc < 0:
if self.exprs:
raise maxException
@@ -2085,12 +2103,12 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-
+
return self.strRepr
-
+
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
@@ -2112,7 +2130,7 @@
break
else:
self.mayReturnEmpty = True
-
+
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
for e in self.exprs:
@@ -2143,12 +2161,12 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-
+
return self.strRepr
-
+
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
@@ -2197,7 +2215,7 @@
tmpOpt.remove(e)
if len(failed) == len(tmpExprs):
keepMatching = False
-
+
if tmpReqd:
missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
@@ -2206,7 +2224,7 @@
for e in matchOrder:
loc,results = e._parse(instring,loc,doActions)
resultlist.append(results)
-
+
finalResults = ParseResults([])
for r in resultlist:
dups = {}
@@ -2223,12 +2241,12 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-
+
return self.strRepr
-
+
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
@@ -2256,7 +2274,7 @@
return self.expr._parse( instring, loc, doActions, callPreParse=False )
else:
raise ParseException("",loc,self.errmsg,self)
-
+
def leaveWhitespace( self ):
self.skipWhitespace = False
self.expr = self.expr.copy()
@@ -2288,19 +2306,19 @@
subRecCheckList = parseElementList[:] + [ self ]
if self.expr is not None:
self.expr.checkRecursion( subRecCheckList )
-
+
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
if self.expr is not None:
self.expr.validate(tmp)
self.checkRecursion( [] )
-
+
def __str__( self ):
try:
return super(ParseElementEnhance,self).__str__()
except:
pass
-
+
if self.strRepr is None and self.expr is not None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
return self.strRepr
@@ -2308,13 +2326,13 @@
class FollowedBy(ParseElementEnhance):
"""Lookahead matching of the given parse expression. FollowedBy
- does *not* advance the parsing position within the input string, it only
- verifies that the specified parse expression matches at the current
+ does *not* advance the parsing position within the input string, it only
+ verifies that the specified parse expression matches at the current
position. FollowedBy always returns a null token list."""
def __init__( self, expr ):
super(FollowedBy,self).__init__(expr)
self.mayReturnEmpty = True
-
+
def parseImpl( self, instring, loc, doActions=True ):
self.expr.tryParse( instring, loc )
return loc, []
@@ -2322,9 +2340,9 @@
class NotAny(ParseElementEnhance):
"""Lookahead to disallow matching with the given parse expression. NotAny
- does *not* advance the parsing position within the input string, it only
- verifies that the specified parse expression does *not* match at the current
- position. Also, NotAny does *not* skip over leading whitespace. NotAny
+ does *not* advance the parsing position within the input string, it only
+ verifies that the specified parse expression does *not* match at the current
+ position. Also, NotAny does *not* skip over leading whitespace. NotAny
always returns a null token list. May be constructed using the '~' operator."""
def __init__( self, expr ):
super(NotAny,self).__init__(expr)
@@ -2333,7 +2351,7 @@
self.mayReturnEmpty = True
self.errmsg = "Found unwanted token, "+_ustr(self.expr)
#self.myException = ParseException("",0,self.errmsg,self)
-
+
def parseImpl( self, instring, loc, doActions=True ):
try:
self.expr.tryParse( instring, loc )
@@ -2350,10 +2368,10 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "~{" + _ustr(self.expr) + "}"
-
+
return self.strRepr
@@ -2362,7 +2380,7 @@
def __init__( self, expr ):
super(ZeroOrMore,self).__init__(expr)
self.mayReturnEmpty = True
-
+
def parseImpl( self, instring, loc, doActions=True ):
tokens = []
try:
@@ -2384,18 +2402,18 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]..."
-
+
return self.strRepr
-
+
def setResultsName( self, name, listAllMatches=False ):
ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
ret.saveAsList = True
return ret
-
+
class OneOrMore(ParseElementEnhance):
"""Repetition of one or more of the given expression."""
def parseImpl( self, instring, loc, doActions=True ):
@@ -2419,12 +2437,12 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "{" + _ustr(self.expr) + "}..."
-
+
return self.strRepr
-
+
def setResultsName( self, name, listAllMatches=False ):
ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
ret.saveAsList = True
@@ -2460,17 +2478,17 @@
def __str__( self ):
if hasattr(self,"name"):
return self.name
-
+
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]"
-
+
return self.strRepr
class SkipTo(ParseElementEnhance):
"""Token for skipping over all undefined text until the matched expression is found.
If include is set to true, the matched expression is also consumed. The ignore
- argument is used to define grammars (typically quoted strings and comments) that
+ argument is used to define grammars (typically quoted strings and comments) that
might contain false matches.
"""
def __init__( self, other, include=False, ignore=None ):
@@ -2515,7 +2533,7 @@
"""Forward declaration of an expression to be defined later -
used for recursive grammars, such as algebraic infix notation.
When the expression is known, it is assigned to the Forward variable using the '<<' operator.
-
+
Note: take care when assigning to Forward not to overlook precedence of operators.
Specifically, '|' has a lower precedence than '<<', so that::
fwdExpr << a | b | c
@@ -2538,7 +2556,7 @@
self.mayReturnEmpty = self.expr.mayReturnEmpty
self.setWhitespaceChars( self.expr.whiteChars )
self.skipWhitespace = self.expr.skipWhitespace
- self.saveAsList = self.expr.saveAsList
+ self.saveAsList = self.expr.saveAsList
return self
def leaveWhitespace( self ):
@@ -2548,31 +2566,31 @@
def streamline( self ):
if not self.streamlined:
self.streamlined = True
- if self.expr is not None:
+ if self.expr is not None:
self.expr.streamline()
return self
def validate( self, validateTrace=[] ):
if self not in validateTrace:
tmp = validateTrace[:]+[self]
- if self.expr is not None:
+ if self.expr is not None:
self.expr.validate(tmp)
- self.checkRecursion([])
-
+ self.checkRecursion([])
+
def __str__( self ):
if hasattr(self,"name"):
return self.name
self.__class__ = _ForwardNoRecurse
try:
- if self.expr is not None:
+ if self.expr is not None:
retString = _ustr(self.expr)
else:
retString = "None"
finally:
self.__class__ = Forward
return "Forward: "+retString
-
+
def copy(self):
if self.expr is not None:
return super(Forward,self).copy()
@@ -2584,7 +2602,7 @@
class _ForwardNoRecurse(Forward):
def __str__( self ):
return "..."
-
+
class TokenConverter(ParseElementEnhance):
"""Abstract subclass of ParseExpression, for converting parsed results."""
def __init__( self, expr, savelist=False ):
@@ -2595,9 +2613,9 @@
"""Converter to upper case all matching tokens."""
def __init__(self, *args):
super(Upcase,self).__init__(*args)
- warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
+ warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
DeprecationWarning,stacklevel=2)
-
+
def postParse( self, instring, loc, tokenlist ):
return map( string.upper, tokenlist )
@@ -2641,7 +2659,7 @@
def postParse( self, instring, loc, tokenlist ):
return [ tokenlist ]
-
+
class Dict(TokenConverter):
"""Converter to return a repetitive expression as a list, but also as a dictionary.
Each element can also be referenced using the first token in the expression as its key.
@@ -2653,7 +2671,7 @@
def postParse( self, instring, loc, tokenlist ):
for i,tok in enumerate(tokenlist):
- if len(tok) == 0:
+ if len(tok) == 0:
continue
ikey = tok[0]
if isinstance(ikey,int):
@@ -2680,7 +2698,7 @@
"""Converter for ignoring the results of a parsed expression."""
def postParse( self, instring, loc, tokenlist ):
return []
-
+
def suppress( self ):
return self
@@ -2720,13 +2738,13 @@
except AttributeError:
pass
return z
-
+
#
# global helpers
#
def delimitedList( expr, delim=",", combine=False ):
"""Helper to define a delimited list of expressions - the delimiter defaults to ','.
- By default, the list elements and delimiters can have intervening whitespace, and
+ By default, the list elements and delimiters can have intervening whitespace, and
comments, but this can be overridden by passing 'combine=True' in the constructor.
If combine is set to True, the matching tokens are returned as a single token
string, with the delimiters included; otherwise, the matching tokens are returned
@@ -2764,8 +2782,8 @@
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
- will match "1:1", but not "1:2". Because this matches a
- previous literal, will also match the leading "1:1" in "1:10".
+ will match "1:1", but not "1:2". Because this matches a
+ previous literal, will also match the leading "1:1" in "1:10".
If this is not desired, use matchPreviousExpr.
Do *not* use with packrat parsing enabled.
"""
@@ -2782,7 +2800,7 @@
rep << Empty()
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
return rep
-
+
def matchPreviousExpr(expr):
"""Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
@@ -2808,7 +2826,7 @@
rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
return rep
-
+
def _escapeRegexRangeChars(s):
#~ escape these chars: ^-]
for c in r"\^-]":
@@ -2816,12 +2834,12 @@
s = s.replace("\n",r"\n")
s = s.replace("\t",r"\t")
return _ustr(s)
-
+
def oneOf( strs, caseless=False, useRegex=True ):
- """Helper to quickly define a set of alternative Literals, and makes sure to do
- longest-first testing when there is a conflict, regardless of the input order,
- but returns a MatchFirst for best performance.
-
+ """Helper to quickly define a set of alternative Literals, and makes sure to do
+ longest-first testing when there is a conflict, regardless of the input order,
+ but returns a MatchFirst for best performance.
+
Parameters:
- strs - a string of space-delimited literals, or a list of string literals
- caseless - (default=False) - treat all literals as caseless
@@ -2837,7 +2855,7 @@
isequal = ( lambda a,b: a == b )
masks = ( lambda a,b: b.startswith(a) )
parseElementClass = Literal
-
+
if isinstance(strs,(list,tuple)):
symbols = strs[:]
elif isinstance(strs,basestring):
@@ -2860,7 +2878,7 @@
else:
break
i += 1
-
+
if not caseless and useRegex:
#~ print strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )
try:
@@ -2881,7 +2899,7 @@
for the key and value. Takes care of defining the Dict, ZeroOrMore, and Group tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
- pattern can include named results, so that the Dict results can include named token
+ pattern can include named results, so that the Dict results can include named token
fields.
"""
return Dict( ZeroOrMore( Group ( key + value ) ) )
@@ -2905,14 +2923,14 @@
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
-
+
def srange(s):
r"""Helper to easily define string ranges for use in Word construction. Borrows
syntax from regexp '[]' string range definitions::
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
- The input string must be enclosed in []'s, and the returned string is the expanded
+ The input string must be enclosed in []'s, and the returned string is the expanded
character set joined into a single string.
The values enclosed in the []'s may be::
a single character
@@ -2928,7 +2946,7 @@
return ""
def replaceWith(replStr):
- """Helper method for common parse actions that simply return a literal value. Especially
+ """Helper method for common parse actions that simply return a literal value. Especially
useful when used with transformString().
"""
def _replFunc(*args):
@@ -2962,7 +2980,7 @@
return t
def getTokensEndLoc():
- """Method to be called from within a parse action to determine the end
+ """Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
@@ -2984,7 +3002,7 @@
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
-
+
tagAttrName = Word(alphas,alphanums+"_-:")
if (xml):
tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
@@ -2999,10 +3017,10 @@
Optional( Suppress("=") + tagAttrValue ) ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
closeTag = Combine("</" + tagStr + ">")
-
+
openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
-
+
return openTag, closeTag
def makeHTMLTags(tagStr):
@@ -3014,12 +3032,12 @@
return _makeTags( tagStr, True )
def withAttribute(*args,**attrDict):
- """Helper to create a validating parse action to be used with start tags created
- with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
- with a required attribute value, to avoid false matches on common tags such as
+ """Helper to create a validating parse action to be used with start tags created
+ with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
+ with a required attribute value, to avoid false matches on common tags such as
<TD> or <DIV>.
- Call withAttribute with a series of attribute names and values. Specify the list
+ Call withAttribute with a series of attribute names and values. Specify the list
of filter attributes names and values as:
- keyword arguments, as in (class="Customer",align="right"), or
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
@@ -3036,7 +3054,7 @@
if attrName not in tokens:
raise ParseException(s,l,"no matching attribute " + attrName)
if tokens[attrName] != attrValue:
- raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
+ raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
(attrName, tokens[attrName], attrValue))
return pa
@@ -3053,16 +3071,16 @@
return tokens[0]
return map(_flattenOpPrecTokens,tokens)
return tokens
-
+
def operatorPrecedence( baseExpr, opList ):
- """Helper method for constructing grammars of expressions made up of
+ """Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.
-
+
Parameters:
- - baseExpr - expression representing the most basic element for the nested
- - opList - list of tuples, one for each operator precedence level in the
+ - baseExpr - expression representing the most basic element for the nested
+ - opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
@@ -3072,7 +3090,7 @@
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants opAssoc.RIGHT and opAssoc.LEFT.
- - parseAction is the parse action to be associated with
+ - parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
"""
@@ -3093,7 +3111,7 @@
# try to avoid LR...
[truncated message content] |
|
From: <md...@us...> - 2008-06-02 17:58:07
|
Revision: 5364
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5364&view=rev
Author: mdboom
Date: 2008-06-02 10:57:28 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
Add examples of different mathtext font sets.
Modified Paths:
--------------
trunk/matplotlib/doc/users/mathtext.rst
Added Paths:
-----------
trunk/matplotlib/doc/_static/cm_fontset.png
trunk/matplotlib/doc/_static/stix_fontset.png
trunk/matplotlib/doc/_static/stixsans_fontset.png
Added: trunk/matplotlib/doc/_static/cm_fontset.png
===================================================================
(Binary files differ)
Property changes on: trunk/matplotlib/doc/_static/cm_fontset.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/matplotlib/doc/_static/stix_fontset.png
===================================================================
(Binary files differ)
Property changes on: trunk/matplotlib/doc/_static/stix_fontset.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/matplotlib/doc/_static/stixsans_fontset.png
===================================================================
(Binary files differ)
Property changes on: trunk/matplotlib/doc/_static/stixsans_fontset.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-02 17:40:19 UTC (rev 5363)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-02 17:57:28 UTC (rev 5364)
@@ -160,7 +160,21 @@
.. image:: ../_static/stix_fonts.png
+There are also three global "font sets" to choose from, which are
+selected using the ``mathtext.fontset`` parameter in ``matplotibrc``.
+``cm``: **Computer Modern (TeX)**
+
+.. image:: ../_static/cm_fontset.png
+
+``stix``: **STIX** (designed to blend well with Times)
+
+.. image:: ../_static/stix_fontset.png
+
+``stixsans``: **STIX sans-serif**
+
+.. image:: ../_static/stixsans_fontset.png
+
Accents
-------
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-02 17:40:41
|
Revision: 5363
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5363&view=rev
Author: jswhit
Date: 2008-06-02 10:40:19 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
require python 2.4
Modified Paths:
--------------
trunk/toolkits/basemap/setup.py
Modified: trunk/toolkits/basemap/setup.py
===================================================================
--- trunk/toolkits/basemap/setup.py 2008-06-02 17:36:29 UTC (rev 5362)
+++ trunk/toolkits/basemap/setup.py 2008-06-02 17:40:19 UTC (rev 5363)
@@ -2,18 +2,8 @@
# setup.cfg for more information.
import sys, glob, os, numpy
major, minor1, minor2, s, tmp = sys.version_info
-if major==2 and minor1<=3:
- # setuptools monkeypatches distutils.core.Distribution to support
- # package_data
- try: import setuptools
- except ImportError:
- raise SystemExit("""
-matplotlib requires setuptools for installation. Please download
-http://peak.telecommunity.com/dist/ez_setup.py and run it (as su if
-you are doing a system wide install) to install the proper version of
-setuptools for your system""")
-#from distutils.core import setup
-#from distutils.core import Extension
+if major==2 and minor1<4 or major<2:
+ raise SystemExit("""matplotlib and the basemap toolkit require Python 2.4 or later.""")
from numpy.distutils.core import setup, Extension
from distutils.util import convert_path
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-02 17:36:50
|
Revision: 5362
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5362&view=rev
Author: jswhit
Date: 2008-06-02 10:36:29 -0700 (Mon, 02 Jun 2008)
Log Message:
-----------
add a more helpful error message if libgeos not found.
Modified Paths:
--------------
trunk/toolkits/basemap/setup.py
Modified: trunk/toolkits/basemap/setup.py
===================================================================
--- trunk/toolkits/basemap/setup.py 2008-06-02 17:13:01 UTC (rev 5361)
+++ trunk/toolkits/basemap/setup.py 2008-06-02 17:36:29 UTC (rev 5362)
@@ -67,19 +67,20 @@
break
else:
geos_version = checkversion(GEOS_dir)
-#if geos_version != '"2.2.3"':
-# raise SystemExit("""
-#Can't find geos library version 2.2.3. Please set the
-#environment variable GEOS_DIR to point to the location
-#where geos 2.2.3 is installed (for example, if geos_c.h
-#is in /usr/local/include, and libgeos_c is in /usr/local/lib,
-#set GEOS_DIR to /usr/local), or edit the setup.py script
-#manually and set the variable GEOS_dir (right after the line
-#that says "set GEOS_dir manually here".""")
-#else:
-geos_include_dirs=[os.path.join(GEOS_dir,'include'),numpy.get_include()]
-geos_library_dirs=[os.path.join(GEOS_dir,'lib'),os.path.join(GEOS_dir,'lib64')]
+if geos_version != '"2.2.3"' or GEOS_dir is None:
+ raise SystemExit("""
+Can't find geos library version 2.2.3. Please set the
+environment variable GEOS_DIR to point to the location
+where geos 2.2.3 is installed (for example, if geos_c.h
+is in /usr/local/include, and libgeos_c is in /usr/local/lib,
+set GEOS_DIR to /usr/local), or edit the setup.py script
+manually and set the variable GEOS_dir (right after the line
+that says "set GEOS_dir manually here".""")
+else:
+ geos_include_dirs=[os.path.join(GEOS_dir,'include'),numpy.get_include()]
+ geos_library_dirs=[os.path.join(GEOS_dir,'lib'),os.path.join(GEOS_dir,'lib64')]
+
# proj4 and geos extensions.
deps = glob.glob('src/*.c')
deps.remove(os.path.join('src','_proj.c'))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|