Commits

Maciej Fijalkowski committed 3142ec6 Merge

merge

Comments (0)

Files changed (51)

     LineBreak-*.txt
     UnicodeData-*.txt
     UnihanNumeric-*.txt
+
+License for 'dotviewer/font/'
+=============================
+
+Copyright (C) 2008 The Android Open Source Project
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+  
+     http://www.apache.org/licenses/LICENSE-2.0
+  
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+Detailled license information is contained in the NOTICE file in the
+directory.
+

dotviewer/VeraMoBd.ttf

Binary file removed.

dotviewer/cyrvetic.ttf

Binary file removed.

dotviewer/drawgraph.py

 from pygame.locals import *
 
 
+RAW_ENCODING = "utf-8"
 this_dir = os.path.dirname(os.path.abspath(__file__))
-FONT = os.path.join(this_dir, 'cyrvetic.ttf')
-FIXEDFONT = os.path.join(this_dir, 'VeraMoBd.ttf')
+FONT = os.path.join(this_dir, 'font', 'DroidSans.ttf')
+FIXEDFONT = os.path.join(this_dir, 'font', 'DroidSansMono.ttf')
 COLOR = {
     'black': (0,0,0),
     'white': (255,255,255),
     else:
         return default
 
+def forceunicode(name):
+    return name if isinstance(name, unicode) else name.decode(RAW_ENCODING)
+
+def forcestr(name):
+    return name if isinstance(name, str) else name.encode(RAW_ENCODING)
+
 
 class GraphLayout:
     fixedfont = False
 
 class Node:
     def __init__(self, name, x, y, w, h, label, style, shape, color, fillcolor):
-        self.name = name
+        self.name = forceunicode(name)
         self.x = float(x)
         self.y = float(y)
         self.w = float(w)
         self.h = float(h)
-        self.label = label
+        self.label = forceunicode(label)
         self.style = style
         self.shape = shape
         self.color = color
     label = None
     
     def __init__(self, nodes, tail, head, cnt, *rest):
-        self.tail = nodes[tail]
-        self.head = nodes[head]
+        self.tail = nodes[forceunicode(tail)]
+        self.head = nodes[forceunicode(head)]
         cnt = int(cnt)
         self.points = [(float(rest[i]), float(rest[i+1]))
                        for i in range(0, cnt*2, 2)]
             part = parts[i]
             word = part[0]
             try:
-                try:
-                    img = font.render(word, False, *part[1:])
-                except pygame.error, e:
-                    # Try *with* anti-aliasing to work around a bug in SDL
-                    img = font.render(word, True, *part[1:])
+                img = font.render(word, True, *part[1:])
             except pygame.error:
                 del parts[i]   # Text has zero width
             else:

dotviewer/font/DroidSans-Bold.ttf

Binary file added.

dotviewer/font/DroidSans.ttf

Binary file added.

dotviewer/font/DroidSansMono.ttf

Binary file added.

dotviewer/font/NOTICE

+
+   Copyright (c) 2005-2008, The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+

dotviewer/font/README.txt

+Copyright (C) 2008 The Android Open Source Project
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+  
+     http://www.apache.org/licenses/LICENSE-2.0
+  
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+##########
+
+This directory contains the fonts for the platform. They are licensed
+under the Apache 2 license.

dotviewer/graphclient.py

     def reload(graph_id):
         page = getpage(graph_id)
         if save_tmp_file:
+            from drawgraph import forcestr
             f = open(save_tmp_file, 'w')
-            f.write(page.source)
+            f.write(forcestr(page.source))
             f.close()
         messages.extend(page_messages(page, graph_id))
         send_graph_messages(io, messages)
 
 def page_messages(page, graph_id):
     import graphparse
-    return graphparse.parse_dot(graph_id, page.source, page.links,
+    from drawgraph import forcestr
+    return graphparse.parse_dot(graph_id, forcestr(page.source), page.links,
                                 getattr(page, 'fixedfont', False))
 
 def send_graph_messages(io, messages):

dotviewer/graphdisplay.py

 from pygame.locals import *
 from drawgraph import GraphRenderer, FIXEDFONT
 from drawgraph import Node, Edge
-from drawgraph import EventQueue, wait_for_events
+from drawgraph import EventQueue, wait_for_events, forceunicode, forcestr
 
 
 METAKEYS = dict([
                     if e.key == K_ESCAPE:
                         return None
                     elif e.key == K_RETURN:
-                        return text.encode('latin-1')   # XXX do better
+                        return forcestr(text) # return encoded unicode
                     elif e.key == K_BACKSPACE:
                         text = text[:-1]
                     elif e.unicode and ord(e.unicode) >= ord(' '):
         self.layout.request_reload()
 
     def setstatusbar(self, text, fgcolor=None, bgcolor=None):
-        info = (text, fgcolor or self.STATUSBAR_FGCOLOR, bgcolor or self.STATUSBAR_BGCOLOR)
+        info = (forceunicode(text), fgcolor or self.STATUSBAR_FGCOLOR, bgcolor or self.STATUSBAR_BGCOLOR)
         if info != self.statusbarinfo:
             self.statusbarinfo = info
             self.must_redraw = True
     lines = []
     while words:
         line = words.pop(0)
-        img = font.render(line or ' ', 1, fgcolor)
+        img = font.render(line or ' ', True, fgcolor)
         while words:
             longerline = line + ' ' + words[0]
             longerimg = font.render(longerline, 1, fgcolor)
             img = longerimg
         w, h = img.get_size()
         if h > maxheight:
-            img = font.render('...', 1, overflowcolor)
+            img = font.render('...', True, overflowcolor)
             w, h = img.get_size()
             while lines and h > maxheight:
                 maxheight += lines.pop().get_size()[1]

dotviewer/graphpage.py

 
 class DotFileGraphPage(GraphPage):
     def compute(self, dotfile):
-        f = open(dotfile, 'r')
+        import codecs
+        from drawgraph import RAW_ENCODING
+        f = codecs.open(dotfile, 'r', RAW_ENCODING)
         self.source = f.read()
         f.close()

dotviewer/test/test_interactive_unicode.py

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+import py
+import sys, os, signal, thread, time, codecs
+from dotviewer.conftest import option
+from dotviewer.drawgraph import RAW_ENCODING
+
+SOURCE1 = u"""digraph G{
+λ -> b
+b -> μ
+}
+"""
+
+FILENAME = 'graph1.dot'
+
+def setup_module(mod):
+    if not option.pygame:
+        py.test.skip("--pygame not enabled")
+    udir = py.path.local.make_numbered_dir(prefix='usession-dot-', keep=3)
+    f = codecs.open(str(udir.join(FILENAME)), 'wb', RAW_ENCODING)
+    f.write(SOURCE1)
+    f.close()
+
+    from dotviewer import graphclient
+    mod.pkgdir = py.path.local(graphclient.this_dir)
+    mod.udir = udir
+
+    try:
+        del os.environ['GRAPHSERVER']
+    except KeyError:
+        pass
+
+
+def test_dotviewer():
+    print "=== dotviewer.py %s" % FILENAME
+    err = os.system('"%s" "%s"' % (pkgdir.join('dotviewer.py'),
+                                   udir.join(FILENAME)))
+    assert err == 0
+
+    plain_name = FILENAME.replace('.dot','.plain')
+    
+    os.system('dot -Tplain "%s" > "%s"' % (udir.join(FILENAME),
+                                           udir.join(plain_name)))
+    print "=== dotviewer.py %s" % plain_name
+    err = os.system('"%s" "%s"' % (pkgdir.join('dotviewer.py'),
+                                   udir.join(plain_name)))
+    assert err == 0
+
+def test_display_dot_file():
+    from dotviewer.graphclient import display_dot_file
+    print "=== display_dot_file(%s) with GRAPHSERVER=%s" % (
+        FILENAME, os.environ.get('GRAPHSERVER', ''),)
+    display_dot_file(udir.join(FILENAME))
+    print "=== display_dot_file finished"
+
+
+def test_graphserver():
+    import socket
+    s = socket.socket()
+    s.listen(1)
+    host, port = s.getsockname()     # pick a random free port
+    s.close()
+
+    if hasattr(sys, 'pypy_objspaceclass'):
+        python = 'python'
+    else:
+        python = sys.executable
+
+    cmdargs = [python, str(pkgdir.join('graphserver.py')),
+               str(port)]
+    print '* starting:', ' '.join(cmdargs)
+    pid = os.spawnv(os.P_NOWAIT, cmdargs[0], cmdargs)
+    try:
+        time.sleep(1)    # hack - wait a bit to make sure the server is up
+        os.environ['GRAPHSERVER'] = '%s:%d' % (host, port)
+        try:
+            test_display_dot_file()
+        finally:
+            del os.environ['GRAPHSERVER']
+    finally:
+        os.kill(pid, signal.SIGTERM)
+
+def test_colors():
+    from dotviewer import graphpage, graphclient
+    class MyPage(graphpage.DotFileGraphPage):
+        def compute(self, dotfile):
+            super(MyPage, self).compute(dotfile)
+            self.links = {'v2721': 'Hello world',
+                          'v2720': ('Something green', (0, 192, 0)),
+                          }
+    dotfile = str(udir.join(FILENAME))
+    page = MyPage(dotfile)
+    graphclient.display_page(page)
+
+def test_fixedfont():
+    from dotviewer import graphpage, graphclient
+    class MyPage(graphpage.DotFileGraphPage):
+        fixedfont = True
+    dotfile = str(udir.join(FILENAME))
+    page = MyPage(dotfile)
+    page.fixedfont = True
+    graphclient.display_page(page)

dotviewer/test/test_translator.py

 
 def test_annotated():
     from rpython.translator.interactive import Translation
-    t = Translation(is_prime)
-    t.annotate([int])
+    t = Translation(is_prime, [int])
+    t.annotate()
     t.viewcg()

dotviewer/test/test_unicode_util.py

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+import py
+import codecs
+from dotviewer.drawgraph import RAW_ENCODING, forcestr, forceunicode
+
+SOURCE1 = u"""digraph G{
+λ -> b
+b -> μ
+}
+"""
+
+FILENAME = 'test.dot'
+
+class TestUnicodeUtil(object):
+
+    def test_idempotent(self):
+        x = u"a"
+        assert forceunicode(forcestr(x)) == x
+        
+        x = u"λ"
+        assert forceunicode(forcestr(x)) == x
+
+        assert forceunicode(forcestr(SOURCE1)) == SOURCE1
+
+        x = "a"
+        assert forcestr(forceunicode(x)) == x
+
+        # utf-8 encoded.
+        # fragile, does not consider RAW_ENCODING
+        # x = "\xef\xbb\xbf\xce\xbb"
+        # assert forcestr(forceunicode(x)) == x
+
+    def test_does_not_double_encode(self):
+        x = u"λ"
+        x_e = forcestr(x)
+        assert forcestr(x_e) == x_e
+
+        x_u = forceunicode(x_e)
+        assert forceunicode(x_u) == x_u
+
+    def test_file(self):       
+        udir = py.path.local.make_numbered_dir(prefix='usession-dot-', keep=3)
+        full_filename = str(udir.join(FILENAME))
+        f = codecs.open(full_filename, 'wb', RAW_ENCODING)
+        f.write(SOURCE1)
+        f.close()
+
+        with open(full_filename) as f1:
+            assert forceunicode(f1.read()) == SOURCE1
+
+        f3 = codecs.open(full_filename, 'r', RAW_ENCODING)
+        c = f3.read()
+        f3.close()
+        result = (c == SOURCE1)
+        assert result

lib_pypy/conftest.py

-
-from pypy.conftest import *

lib_pypy/ctypes_config_cache/test/test_cache.py

-import py
-import sys, os
-from rpython.tool.udir import udir
-
-dirpath = py.path.local(__file__).dirpath().dirpath()
-
-
-def run(filename, outputname):
-    filepath = dirpath.join(filename)
-    tmpdir = udir.ensure('testcache-' + os.path.splitext(filename)[0],
-                         dir=True)
-    tmpdir.join('dumpcache.py').write(dirpath.join('dumpcache.py').read())
-    path = sys.path[:]
-    sys.modules.pop('dumpcache', None)
-    try:
-        sys.path.insert(0, str(tmpdir))
-        execfile(str(filepath), {})
-    finally:
-        sys.path[:] = path
-        sys.modules.pop('dumpcache', None)
-    #
-    outputpath = tmpdir.join(outputname)
-    assert outputpath.check(exists=1)
-    modname = os.path.splitext(outputname)[0]
-    try:
-        sys.path.insert(0, str(tmpdir))
-        d = {}
-        execfile(str(outputpath), d)
-    finally:
-        sys.path[:] = path
-    return d
-
-
-def test_syslog():
-    d = run('syslog.ctc.py', '_syslog_cache.py')
-    assert 'LOG_NOTICE' in d
-
-def test_resource():
-    d = run('resource.ctc.py', '_resource_cache.py')
-    assert 'RLIM_NLIMITS' in d
-
-def test_locale():
-    d = run('locale.ctc.py', '_locale_cache.py')
-    assert 'LC_ALL' in d
-    assert 'CHAR_MAX' in d
-from ctypes import Structure, c_char_p, c_int, c_void_p, CDLL
+from ctypes import Structure, c_char_p, c_int, c_void_p, CDLL, POINTER, c_char
 import ctypes.util
 import os, sys
 
 
 class datum(Structure):
     _fields_ = [
-    ('dptr', c_char_p),
+    ('dptr', POINTER(c_char)),
     ('dsize', c_int),
     ]
 
     libpath = ctypes.util.find_library('db')
     if not libpath:
         # XXX this is hopeless...
-        for c in '56789':
-            libpath = ctypes.util.find_library('db-4.%s' % c)
+        for c in ['5.3', '5.2', '5.1', '5.0', '4.9', '4.8', '4.7', '4.6', '4.5']:
+            libpath = ctypes.util.find_library('db-%s' % c)
             if libpath:
                 break
         else:

lib_pypy/numpypy/core/__init__.py

 from .fromnumeric import *
 from .numeric import *
+from .shape_base import *

lib_pypy/numpypy/core/numeric.py

 True_ = bool_(True)
 e = math.e
 pi = math.pi
+
+def outer(a,b):
+    """
+    Compute the outer product of two vectors.
+
+    Given two vectors, ``a = [a0, a1, ..., aM]`` and
+    ``b = [b0, b1, ..., bN]``,
+    the outer product [1]_ is::
+
+      [[a0*b0  a0*b1 ... a0*bN ]
+       [a1*b0    .
+       [ ...          .
+       [aM*b0            aM*bN ]]
+
+    Parameters
+    ----------
+    a, b : array_like, shape (M,), (N,)
+        First and second input vectors.  Inputs are flattened if they
+        are not already 1-dimensional.
+
+    Returns
+    -------
+    out : ndarray, shape (M, N)
+        ``out[i, j] = a[i] * b[j]``
+
+    See also
+    --------
+    inner, einsum
+
+    References
+    ----------
+    .. [1] : G. H. Golub and C. F. van Loan, *Matrix Computations*, 3rd
+             ed., Baltimore, MD, Johns Hopkins University Press, 1996,
+             pg. 8.
+
+    Examples
+    --------
+    Make a (*very* coarse) grid for computing a Mandelbrot set:
+
+    >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
+    >>> rl
+    array([[-2., -1.,  0.,  1.,  2.],
+           [-2., -1.,  0.,  1.,  2.],
+           [-2., -1.,  0.,  1.,  2.],
+           [-2., -1.,  0.,  1.,  2.],
+           [-2., -1.,  0.,  1.,  2.]])
+    >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
+    >>> im
+    array([[ 0.+2.j,  0.+2.j,  0.+2.j,  0.+2.j,  0.+2.j],
+           [ 0.+1.j,  0.+1.j,  0.+1.j,  0.+1.j,  0.+1.j],
+           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
+           [ 0.-1.j,  0.-1.j,  0.-1.j,  0.-1.j,  0.-1.j],
+           [ 0.-2.j,  0.-2.j,  0.-2.j,  0.-2.j,  0.-2.j]])
+    >>> grid = rl + im
+    >>> grid
+    array([[-2.+2.j, -1.+2.j,  0.+2.j,  1.+2.j,  2.+2.j],
+           [-2.+1.j, -1.+1.j,  0.+1.j,  1.+1.j,  2.+1.j],
+           [-2.+0.j, -1.+0.j,  0.+0.j,  1.+0.j,  2.+0.j],
+           [-2.-1.j, -1.-1.j,  0.-1.j,  1.-1.j,  2.-1.j],
+           [-2.-2.j, -1.-2.j,  0.-2.j,  1.-2.j,  2.-2.j]])
+
+    An example using a "vector" of letters:
+
+    >>> x = np.array(['a', 'b', 'c'], dtype=object)
+    >>> np.outer(x, [1, 2, 3])
+    array([[a, aa, aaa],
+           [b, bb, bbb],
+           [c, cc, ccc]], dtype=object)
+
+    """
+    a = asarray(a)
+    b = asarray(b)
+    return a.ravel()[:,newaxis]*b.ravel()[newaxis,:]

lib_pypy/numpypy/core/shape_base.py

+import _numpypy
+from numeric import array, asanyarray, newaxis
+
+def atleast_1d(*arys):
+    """
+    Convert inputs to arrays with at least one dimension.
+
+    Scalar inputs are converted to 1-dimensional arrays, whilst
+    higher-dimensional inputs are preserved.
+
+    Parameters
+    ----------
+    arys1, arys2, ... : array_like
+        One or more input arrays.
+
+    Returns
+    -------
+    ret : ndarray
+        An array, or sequence of arrays, each with ``a.ndim >= 1``.
+        Copies are made only if necessary.
+
+    See Also
+    --------
+    atleast_2d, atleast_3d
+
+    Examples
+    --------
+    >>> np.atleast_1d(1.0)
+    array([ 1.])
+
+    >>> x = np.arange(9.0).reshape(3,3)
+    >>> np.atleast_1d(x)
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4.,  5.],
+           [ 6.,  7.,  8.]])
+    >>> np.atleast_1d(x) is x
+    True
+
+    >>> np.atleast_1d(1, [3, 4])
+    [array([1]), array([3, 4])]
+
+    """
+    res = []
+    for ary in arys:
+        ary = asanyarray(ary)
+        if len(ary.shape) == 0 :
+            result = ary.reshape(1)
+        else :
+            result = ary
+        res.append(result)
+    if len(res) == 1:
+        return res[0]
+    else:
+        return res
+
+
+def atleast_2d(*arys):
+    """
+    View inputs as arrays with at least two dimensions.
+
+    Parameters
+    ----------
+    arys1, arys2, ... : array_like
+        One or more array-like sequences.  Non-array inputs are converted
+        to arrays.  Arrays that already have two or more dimensions are
+        preserved.
+
+    Returns
+    -------
+    res, res2, ... : ndarray
+        An array, or tuple of arrays, each with ``a.ndim >= 2``.
+        Copies are avoided where possible, and views with two or more
+        dimensions are returned.
+
+    See Also
+    --------
+    atleast_1d, atleast_3d
+
+    Examples
+    --------
+    >>> np.atleast_2d(3.0)
+    array([[ 3.]])
+
+    >>> x = np.arange(3.0)
+    >>> np.atleast_2d(x)
+    array([[ 0.,  1.,  2.]])
+    >>> np.atleast_2d(x).base is x
+    True
+
+    >>> np.atleast_2d(1, [1, 2], [[1, 2]])
+    [array([[1]]), array([[1, 2]]), array([[1, 2]])]
+
+    """
+    res = []
+    for ary in arys:
+        ary = asanyarray(ary)
+        if len(ary.shape) == 0 :
+            result = ary.reshape(1, 1)
+        elif len(ary.shape) == 1 :
+            result = ary[newaxis, :]
+        else :
+            result = ary
+        res.append(result)
+    if len(res) == 1:
+        return res[0]
+    else:
+        return res
+
+def atleast_3d(*arys):
+    """
+    View inputs as arrays with at least three dimensions.
+
+    Parameters
+    ----------
+    arys1, arys2, ... : array_like
+        One or more array-like sequences.  Non-array inputs are converted to
+        arrays.  Arrays that already have three or more dimensions are
+        preserved.
+
+    Returns
+    -------
+    res1, res2, ... : ndarray
+        An array, or tuple of arrays, each with ``a.ndim >= 3``.  Copies are
+        avoided where possible, and views with three or more dimensions are
+        returned.  For example, a 1-D array of shape ``(N,)`` becomes a view
+        of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
+        view of shape ``(M, N, 1)``.
+
+    See Also
+    --------
+    atleast_1d, atleast_2d
+
+    Examples
+    --------
+    >>> np.atleast_3d(3.0)
+    array([[[ 3.]]])
+
+    >>> x = np.arange(3.0)
+    >>> np.atleast_3d(x).shape
+    (1, 3, 1)
+
+    >>> x = np.arange(12.0).reshape(4,3)
+    >>> np.atleast_3d(x).shape
+    (4, 3, 1)
+    >>> np.atleast_3d(x).base is x
+    True
+
+    >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
+    ...     print arr, arr.shape
+    ...
+    [[[1]
+      [2]]] (1, 2, 1)
+    [[[1]
+      [2]]] (1, 2, 1)
+    [[[1 2]]] (1, 1, 2)
+
+    """
+    res = []
+    for ary in arys:
+        ary = asanyarray(ary)
+        if len(ary.shape) == 0:
+            result = ary.reshape(1,1,1)
+        elif len(ary.shape) == 1:
+            result = ary[newaxis,:,newaxis]
+        elif len(ary.shape) == 2:
+            result = ary[:,:,newaxis]
+        else:
+            result = ary
+        res.append(result)
+    if len(res) == 1:
+        return res[0]
+    else:
+        return res
+
+def vstack(tup):
+    """
+    Stack arrays in sequence vertically (row wise).
+
+    Take a sequence of arrays and stack them vertically to make a single
+    array. Rebuild arrays divided by `vsplit`.
+
+    Parameters
+    ----------
+    tup : sequence of ndarrays
+        Tuple containing arrays to be stacked. The arrays must have the same
+        shape along all but the first axis.
+
+    Returns
+    -------
+    stacked : ndarray
+        The array formed by stacking the given arrays.
+
+    See Also
+    --------
+    hstack : Stack arrays in sequence horizontally (column wise).
+    dstack : Stack arrays in sequence depth wise (along third dimension).
+    concatenate : Join a sequence of arrays together.
+    vsplit : Split array into a list of multiple sub-arrays vertically.
+
+    Notes
+    -----
+    Equivalent to ``np.concatenate(tup, axis=0)`` if `tup` contains arrays that
+    are at least 2-dimensional.
+
+    Examples
+    --------
+    >>> a = np.array([1, 2, 3])
+    >>> b = np.array([2, 3, 4])
+    >>> np.vstack((a,b))
+    array([[1, 2, 3],
+           [2, 3, 4]])
+
+    >>> a = np.array([[1], [2], [3]])
+    >>> b = np.array([[2], [3], [4]])
+    >>> np.vstack((a,b))
+    array([[1],
+           [2],
+           [3],
+           [2],
+           [3],
+           [4]])
+
+    """
+    return _numpypy.concatenate(map(atleast_2d,tup),0)
+
+def hstack(tup):
+    """
+    Stack arrays in sequence horizontally (column wise).
+
+    Take a sequence of arrays and stack them horizontally to make
+    a single array. Rebuild arrays divided by `hsplit`.
+
+    Parameters
+    ----------
+    tup : sequence of ndarrays
+        All arrays must have the same shape along all but the second axis.
+
+    Returns
+    -------
+    stacked : ndarray
+        The array formed by stacking the given arrays.
+
+    See Also
+    --------
+    vstack : Stack arrays in sequence vertically (row wise).
+    dstack : Stack arrays in sequence depth wise (along third axis).
+    concatenate : Join a sequence of arrays together.
+    hsplit : Split array along second axis.
+
+    Notes
+    -----
+    Equivalent to ``np.concatenate(tup, axis=1)``
+
+    Examples
+    --------
+    >>> a = np.array((1,2,3))
+    >>> b = np.array((2,3,4))
+    >>> np.hstack((a,b))
+    array([1, 2, 3, 2, 3, 4])
+    >>> a = np.array([[1],[2],[3]])
+    >>> b = np.array([[2],[3],[4]])
+    >>> np.hstack((a,b))
+    array([[1, 2],
+           [2, 3],
+           [3, 4]])
+
+    """
+    arrs = map(atleast_1d,tup)
+    # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
+    if arrs[0].ndim == 1:
+        return _numpypy.concatenate(arrs, 0)
+    else:
+        return _numpypy.concatenate(arrs, 1)
+
+def dstack(tup):
+    """
+    Stack arrays in sequence depth wise (along third axis).
+
+    Takes a sequence of arrays and stack them along the third axis
+    to make a single array. Rebuilds arrays divided by `dsplit`.
+    This is a simple way to stack 2D arrays (images) into a single
+    3D array for processing.
+
+    Parameters
+    ----------
+    tup : sequence of arrays
+        Arrays to stack. All of them must have the same shape along all
+        but the third axis.
+
+    Returns
+    -------
+    stacked : ndarray
+        The array formed by stacking the given arrays.
+
+    See Also
+    --------
+    vstack : Stack along first axis.
+    hstack : Stack along second axis.
+    concatenate : Join arrays.
+    dsplit : Split array along third axis.
+
+    Notes
+    -----
+    Equivalent to ``np.concatenate(tup, axis=2)``.
+
+    Examples
+    --------
+    >>> a = np.array((1,2,3))
+    >>> b = np.array((2,3,4))
+    >>> np.dstack((a,b))
+    array([[[1, 2],
+            [2, 3],
+            [3, 4]]])
+
+    >>> a = np.array([[1],[2],[3]])
+    >>> b = np.array([[2],[3],[4]])
+    >>> np.dstack((a,b))
+    array([[[1, 2]],
+           [[2, 3]],
+           [[3, 4]]])
+
+    """
+    return _numpypy.concatenate(map(atleast_3d,tup),2)

lib_pypy/pyrepl/cmdrepl.py

     def get_completions(self, stem):
         if len(stem) != self.pos:
             return []
-        return cr.uniqify([s for s in self.completions
-                           if s.startswith(stem)])
+        return sorted(set(s for s in self.completions
+                           if s.startswith(stem)))
 
 def replize(klass, history_across_invocations=1):
 

lib_pypy/pyrepl/completing_reader.py

 from pyrepl import commands, reader
 from pyrepl.reader import Reader
 
-def uniqify(l):
-    d = {}
-    for i in l:
-        d[i] = 1
-    r = d.keys()
-    r.sort()
-    return r
 
 def prefix(wordlist, j = 0):
     d = {}

lib_pypy/pyrepl/module_lister.py

 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
-from pyrepl.completing_reader import uniqify
 import os, sys
 
 # for the completion support.
             l.append( prefix + fname )
             _packages[prefix + fname] = _make_module_list_dir(
                 file, suffs, prefix + fname + '.' )
-    l = uniqify(l)
-    l.sort()
-    return l
+    return sorted(set(l))
 
 def _make_module_list():
     import imp
     suffs = [x[0] for x in imp.get_suffixes() if x[0] != '.pyc']
-    def compare(x, y):
-        c = -cmp(len(x), len(y))
-        if c:
-            return c
-        else:
-            return -cmp(x, y)
-    suffs.sort(compare)
+    suffs.sort(reverse=True)
     _packages[''] = list(sys.builtin_module_names)
     for dir in sys.path:
         if dir == '':

lib_pypy/pyrepl/python_reader.py

                 return [x[len(mod) + 1:]
                         for x in l if x.startswith(mod + '.' + name)]
         try:
-            l = completing_reader.uniqify(self.completer.complete(stem))
+            l = sorted(set(self.completer.complete(stem)))
             return l
         except (NameError, AttributeError):
             return []
             self.showsyntaxerror("<input>")
         else:
             self.runcode(code)
-            sys.stdout.flush()
+            if sys.stdout and not sys.stdout.closed:
+                sys.stdout.flush()
 
     def interact(self):
         while 1:
                         encoding = None
                 else:
                     encoding = None # so you get ASCII...
-            con = UnixConsole(0, 1, None, encoding)
+            con = UnixConsole(os.dup(0), os.dup(1), None, encoding)
         if print_banner:
             print "Python", sys.version, "on", sys.platform
             print 'Type "help", "copyright", "credits" or "license" '\

lib_pypy/pyrepl/reader.py

             if not event: # can only happen if we're not blocking
                 return None
 
+            translate = True
+
             if event.evt == 'key':
                 self.input_trans.push(event)
             elif event.evt == 'scroll':
             elif event.evt == 'resize':
                 self.refresh()
             else:
-                pass
+                translate = False
 
-            cmd = self.input_trans.get()
+            if translate:
+                cmd = self.input_trans.get()
+            else:
+                cmd = event.evt, event.data
 
             if cmd is None:
                 if block:

lib_pypy/pyrepl/readline.py

 # ____________________________________________________________
 
 class _ReadlineWrapper(object):
-    f_in = 0
-    f_out = 1
     reader = None
     saved_history_length = -1
     startup_hook = None
     config = ReadlineConfig()
 
+    def __init__(self, f_in=None, f_out=None):
+        self.f_in = f_in if f_in is not None else os.dup(0)
+        self.f_out = f_out if f_out is not None else os.dup(1)
+
     def get_reader(self):
         if self.reader is None:
             console = UnixConsole(self.f_in, self.f_out, encoding=ENCODING)

lib_pypy/pyrepl/test/test_functional.py

-#   Copyright 2000-2007 Michael Hudson-Doyle <micahel@gmail.com>
-#                       Maciek Fijalkowski
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-# some functional tests, to see if this is really working
-
-import py
-import sys
-
-class TestTerminal(object):
-    def _spawn(self, *args, **kwds):
-        try:
-            import pexpect
-        except ImportError, e:
-            py.test.skip(str(e))
-        kwds.setdefault('timeout', 10)
-        child = pexpect.spawn(*args, **kwds)
-        child.logfile = sys.stdout
-        return child
-
-    def spawn(self, argv=[]):
-        # avoid running start.py, cause it might contain
-        # things like readline or rlcompleter(2) included
-        child = self._spawn(sys.executable, ['-S'] + argv)
-        child.sendline('from pyrepl.python_reader import main')
-        child.sendline('main()')
-        return child
-
-    def test_basic(self):
-        child = self.spawn()
-        child.sendline('a = 3')
-        child.sendline('a')
-        child.expect('3')
-        

lib_pypy/pyrepl/tests/__init__.py

-#   Copyright 2000-2004 Michael Hudson-Doyle <micahel@gmail.com>
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-# moo

lib_pypy/pyrepl/tests/basic.py

-#   Copyright 2000-2004 Michael Hudson-Doyle <micahel@gmail.com>
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-from pyrepl.console import Event
-from pyrepl.tests.infrastructure import ReaderTestCase, EA, run_testcase
-
-class SimpleTestCase(ReaderTestCase):
-
-    def test_basic(self):
-        self.run_test([(('self-insert', 'a'), ['a']),
-                       ( 'accept',            ['a'])])
-
-    def test_repeat(self):
-        self.run_test([(('digit-arg', '3'),   ['']),
-                       (('self-insert', 'a'), ['aaa']),
-                       ( 'accept',            ['aaa'])])
-
-    def test_kill_line(self):
-        self.run_test([(('self-insert', 'abc'), ['abc']),
-                       ( 'left',                None),
-                       ( 'kill-line',           ['ab']),
-                       ( 'accept',              ['ab'])])
-
-    def test_unix_line_discard(self):
-        self.run_test([(('self-insert', 'abc'), ['abc']),
-                       ( 'left',                None),
-                       ( 'unix-word-rubout',    ['c']),
-                       ( 'accept',              ['c'])])
-
-    def test_kill_word(self):
-        self.run_test([(('self-insert', 'ab cd'), ['ab cd']),
-                       ( 'beginning-of-line',     ['ab cd']),
-                       ( 'kill-word',             [' cd']),
-                       ( 'accept',                [' cd'])])
-
-    def test_backward_kill_word(self):
-        self.run_test([(('self-insert', 'ab cd'), ['ab cd']),
-                       ( 'backward-kill-word',    ['ab ']),
-                       ( 'accept',                ['ab '])])
-
-    def test_yank(self):
-        self.run_test([(('self-insert', 'ab cd'), ['ab cd']),
-                       ( 'backward-kill-word',    ['ab ']),
-                       ( 'beginning-of-line',     ['ab ']),
-                       ( 'yank',                  ['cdab ']),
-                       ( 'accept',                ['cdab '])])
-        
-    def test_yank_pop(self):
-        self.run_test([(('self-insert', 'ab cd'), ['ab cd']),
-                       ( 'backward-kill-word',    ['ab ']),
-                       ( 'left',                  ['ab ']),
-                       ( 'backward-kill-word',    [' ']),
-                       ( 'yank',                  ['ab ']),
-                       ( 'yank-pop',              ['cd ']),
-                       ( 'accept',                ['cd '])])
-
-    def test_interrupt(self):
-        try:
-            self.run_test([( 'interrupt',  [''])])
-        except KeyboardInterrupt:
-            pass
-        else:
-            self.fail('KeyboardInterrupt got lost')
-
-    # test_suspend -- hah
-
-    def test_up(self):
-        self.run_test([(('self-insert', 'ab\ncd'), ['ab', 'cd']),
-                       ( 'up',                     ['ab', 'cd']),
-                       (('self-insert', 'e'),      ['abe', 'cd']),
-                       ( 'accept',                 ['abe', 'cd'])])
-
-    def test_down(self):
-        self.run_test([(('self-insert', 'ab\ncd'), ['ab', 'cd']),
-                       ( 'up',                     ['ab', 'cd']),
-                       (('self-insert', 'e'),      ['abe', 'cd']),
-                       ( 'down',                   ['abe', 'cd']),
-                       (('self-insert', 'f'),      ['abe', 'cdf']),
-                       ( 'accept',                 ['abe', 'cdf'])])
-
-    def test_left(self):
-        self.run_test([(('self-insert', 'ab'), ['ab']),
-                       ( 'left',               ['ab']),
-                       (('self-insert', 'c'),  ['acb']),
-                       ( 'accept',             ['acb'])])
-
-    def test_right(self):
-        self.run_test([(('self-insert', 'ab'), ['ab']),
-                       ( 'left',               ['ab']),
-                       (('self-insert', 'c'),  ['acb']),
-                       ( 'right',              ['acb']),
-                       (('self-insert', 'd'),  ['acbd']),
-                       ( 'accept',             ['acbd'])])
-        
-def test():
-    run_testcase(SimpleTestCase)
-
-if __name__ == '__main__':
-    test()

lib_pypy/pyrepl/tests/bugs.py

-#   Copyright 2000-2004 Michael Hudson-Doyle <micahel@gmail.com>
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-from pyrepl.console import Event
-from pyrepl.tests.infrastructure import ReaderTestCase, EA, run_testcase
-
-# this test case should contain as-verbatim-as-possible versions of
-# (applicable) bug reports
-
-class BugsTestCase(ReaderTestCase):
-
-    def test_transpose_at_start(self):
-        self.run_test([( 'transpose', [EA, '']),
-                       ( 'accept',    [''])])
-
-def test():
-    run_testcase(BugsTestCase)
-
-if __name__ == '__main__':
-    test()

lib_pypy/pyrepl/tests/infrastructure.py

-#   Copyright 2000-2004 Michael Hudson-Doyle <micahel@gmail.com>
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-from pyrepl.reader import Reader
-from pyrepl.console import Console, Event
-import unittest
-import sys
-
-class EqualsAnything(object):
-    def __eq__(self, other):
-        return True
-EA = EqualsAnything()
-
-class TestConsole(Console):
-    height = 24
-    width = 80
-    encoding = 'utf-8'
-
-    def __init__(self, events, testcase, verbose=False):
-        self.events = events
-        self.next_screen = None
-        self.verbose = verbose
-        self.testcase = testcase
-
-    def refresh(self, screen, xy):
-        if self.next_screen is not None:
-            self.testcase.assertEqual(
-                screen, self.next_screen,
-                "[ %s != %s after %r ]"%(screen, self.next_screen,
-                                         self.last_event_name))
-
-    def get_event(self, block=1):
-        ev, sc = self.events.pop(0)
-        self.next_screen = sc
-        if not isinstance(ev, tuple):
-            ev = (ev,)
-        self.last_event_name = ev[0]
-        if self.verbose:
-            print "event", ev
-        return Event(*ev)
-
-class TestReader(Reader):
-    def get_prompt(self, lineno, cursor_on_line):
-        return ''
-    def refresh(self):
-        Reader.refresh(self)
-        self.dirty = True
-
-class ReaderTestCase(unittest.TestCase):
-    def run_test(self, test_spec, reader_class=TestReader):
-        # remember to finish your test_spec with 'accept' or similar!
-        con = TestConsole(test_spec, self)
-        reader = reader_class(con)
-        reader.readline()
-
-class BasicTestRunner:
-    def run(self, test):
-        result = unittest.TestResult()
-        test(result)
-        return result
-
-def run_testcase(testclass):
-    suite = unittest.makeSuite(testclass)
-    runner = unittest.TextTestRunner(sys.stdout, verbosity=1)
-    result = runner.run(suite)
-    

lib_pypy/pyrepl/tests/wishes.py

-#   Copyright 2000-2004 Michael Hudson-Doyle <micahel@gmail.com>
-#
-#                        All Rights Reserved
-#
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose is hereby granted without fee,
-# provided that the above copyright notice appear in all copies and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation.
-#
-# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
-# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
-# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
-# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-from pyrepl.console import Event
-from pyrepl.tests.infrastructure import ReaderTestCase, EA, run_testcase
-
-# this test case should contain as-verbatim-as-possible versions of
-# (applicable) feature requests
-
-class WishesTestCase(ReaderTestCase):
-
-    def test_quoted_insert_repeat(self):
-        self.run_test([(('digit-arg', '3'),      ['']),
-                       ( 'quoted-insert',        ['']),
-                       (('self-insert', '\033'), ['^[^[^[']),
-                       ( 'accept',               None)])
-
-def test():
-    run_testcase(WishesTestCase)
-
-if __name__ == '__main__':
-    test()

lib_pypy/pyrepl/unix_console.py

         old_offset = offset = self.__offset
         height = self.height
 
-        if 0:
-            global counter
-            try:
-                counter
-            except NameError:
-                counter = 0
-            self.__write_code(curses.tigetstr("setaf"), counter)
-            counter += 1
-            if counter > 8:
-                counter = 0
 
         # we make sure the cursor is on the screen, and that we're
         # using all of the screen if we can

pypy/interpreter/app_main.py

     "warnoptions",
     "unbuffered"), 0)
 
-PYTHON26 = True
-
 def simple_option(options, name, iterargv):
     options[name] += 1
 
 
 cmdline_options = {
     # simple options just increment the counter of the options listed above
+    'b': (simple_option, 'bytes_warning'),
+    'B': (simple_option, 'dont_write_bytecode'),
     'd': (simple_option, 'debug'),
+    'E': (simple_option, 'ignore_environment'),
     'i': (simple_option, 'interactive'),
     'O': (simple_option, 'optimize'),
+    'R': (simple_option, 'hash_randomization'),
+    's': (simple_option, 'no_user_site'),
     'S': (simple_option, 'no_site'),
-    'E': (simple_option, 'ignore_environment'),
     't': (simple_option, 'tabcheck'),
-    'v': (simple_option, 'verbose'),
     'U': (simple_option, 'unicode'),
     'u': (simple_option, 'unbuffered'),
+    'v': (simple_option, 'verbose'),
+    '3': (simple_option, 'py3k_warning'),
     # more complex options
-    'Q':         (div_option,      Ellipsis),
     'c':         (c_option,        Ellipsis),
+    '?':         (print_help,      None),
+    'h':         (print_help,      None),
+    '--help':    (print_help,      None),
     'm':         (m_option,        Ellipsis),
     'W':         (W_option,        Ellipsis),
     'V':         (print_version,   None),
     '--version': (print_version,   None),
+    'Q':         (div_option,      Ellipsis),
     '--info':    (print_info,      None),
-    'h':         (print_help,      None),
-    '--help':    (print_help,      None),
     '--jit':     (set_jit_option,  Ellipsis),
     '--':        (end_options,     None),
     }
 
-if PYTHON26:
-    cmdline_options.update({
-        '3': (simple_option, 'py3k_warning'),
-        'B': (simple_option, 'dont_write_bytecode'),
-        's': (simple_option, 'no_user_site'),
-        'b': (simple_option, 'bytes_warning'),
-        'R': (simple_option, 'hash_randomization'),
-        })
-
 def handle_argument(c, options, iterargv, iterarg=iter(())):
     function, funcarg = cmdline_options[c]
 
     sys.argv[:] = argv
 
     if not options["ignore_environment"]:
+        if os.getenv('PYTHONDEBUG'):
+            options["debug"] = 1
+        if os.getenv('PYTHONDONTWRITEBYTECODE'):
+            options["dont_write_bytecode"] = 1
+        if os.getenv('PYTHONNOUSERSITE'):
+            options["no_user_site"] = 1
         if os.getenv('PYTHONUNBUFFERED'):
             options["unbuffered"] = 1
-        if PYTHON26:
-            if os.getenv('PYTHONNOUSERSITE'):
-                options["no_user_site"] = 1
-            if os.getenv('PYTHONDONTWRITEBYTECODE'):
-                options["dont_write_bytecode"] = 1
+        if os.getenv('PYTHONVERBOSE'):
+            options["verbose"] = 1
 
     if (options["interactive"] or
         (not options["ignore_environment"] and os.getenv('PYTHONINSPECT'))):
 ##        print >> sys.stderr, (
 ##            "Warning: pypy does not implement hash randomization")
 
-    if PYTHON26 and we_are_translated():
+    if we_are_translated():
         flags = [options[flag] for flag in sys_flags]
         sys.flags = type(sys.flags)(flags)
         sys.py3kwarning = bool(sys.flags.py3k_warning)

pypy/interpreter/test2/test_app_main.py

                 assert not value, (
                     "option %r has unexpectedly the value %r" % (key, value))
 
-    def check(self, argv, **expected):
+    def check(self, argv, env, **expected):
         import StringIO
         from pypy.interpreter import app_main
+        saved_env = os.environ.copy()
         saved_sys_argv = sys.argv[:]
         saved_sys_stdout = sys.stdout
         saved_sys_stderr = sys.stdout
         app_main.os = os
         try:
+            os.environ.update(env)
             sys.stdout = sys.stderr = StringIO.StringIO()
             try:
                 options = app_main.parse_command_line(argv)
             else:
                 self.check_options(options, **expected)
         finally:
+            os.environ.clear()
+            os.environ.update(saved_env)
             sys.argv[:] = saved_sys_argv
             sys.stdout = saved_sys_stdout
             sys.stderr = saved_sys_stderr
 
     def test_all_combinations_I_can_think_of(self):
-        self.check([], sys_argv=[''], run_stdin=True)
-        self.check(['-'], sys_argv=['-'], run_stdin=True)
-        self.check(['-S'], sys_argv=[''], run_stdin=True, no_site=1)
-        self.check(['-OO'], sys_argv=[''], run_stdin=True, optimize=2)
-        self.check(['-O', '-O'], sys_argv=[''], run_stdin=True, optimize=2)
-        self.check(['-Qnew'], sys_argv=[''], run_stdin=True, division_new=1)
-        self.check(['-Qold'], sys_argv=[''], run_stdin=True, division_new=0)
-        self.check(['-Qwarn'], sys_argv=[''], run_stdin=True, division_warning=1)
-        self.check(['-Qwarnall'], sys_argv=[''], run_stdin=True,
+        self.check([], {}, sys_argv=[''], run_stdin=True)
+        self.check(['-'], {}, sys_argv=['-'], run_stdin=True)
+        self.check(['-S'], {}, sys_argv=[''], run_stdin=True, no_site=1)
+        self.check(['-OO'], {}, sys_argv=[''], run_stdin=True, optimize=2)
+        self.check(['-O', '-O'], {}, sys_argv=[''], run_stdin=True, optimize=2)
+        self.check(['-Qnew'], {}, sys_argv=[''], run_stdin=True, division_new=1)
+        self.check(['-Qold'], {}, sys_argv=[''], run_stdin=True, division_new=0)
+        self.check(['-Qwarn'], {}, sys_argv=[''], run_stdin=True, division_warning=1)
+        self.check(['-Qwarnall'], {}, sys_argv=[''], run_stdin=True,
                    division_warning=2)
-        self.check(['-Q', 'new'], sys_argv=[''], run_stdin=True, division_new=1)
-        self.check(['-SOQnew'], sys_argv=[''], run_stdin=True,
+        self.check(['-Q', 'new'], {}, sys_argv=[''], run_stdin=True, division_new=1)
+        self.check(['-SOQnew'], {}, sys_argv=[''], run_stdin=True,
                    no_site=1, optimize=1, division_new=1)
-        self.check(['-SOQ', 'new'], sys_argv=[''], run_stdin=True,
+        self.check(['-SOQ', 'new'], {}, sys_argv=[''], run_stdin=True,
                    no_site=1, optimize=1, division_new=1)
-        self.check(['-i'], sys_argv=[''], run_stdin=True,
+        self.check(['-i'], {}, sys_argv=[''], run_stdin=True,
                    interactive=1, inspect=1)
-        self.check(['-h'], output_contains='usage:')
-        self.check(['-S', '-tO', '-h'], output_contains='usage:')
-        self.check(['-S', '-thO'], output_contains='usage:')
-        self.check(['-S', '-tO', '--help'], output_contains='usage:')
-        self.check(['-S', '-tO', '--info'], output_contains='translation')
-        self.check(['-S', '-tO', '--version'], output_contains='Python')
-        self.check(['-S', '-tOV'], output_contains='Python')
-        self.check(['--jit', 'foobar', '-S'], sys_argv=[''],
+        self.check(['-?'], {}, output_contains='usage:')
+        self.check(['-h'], {}, output_contains='usage:')
+        self.check(['-S', '-tO', '-h'], {}, output_contains='usage:')
+        self.check(['-S', '-thO'], {}, output_contains='usage:')
+        self.check(['-S', '-tO', '--help'], {}, output_contains='usage:')
+        self.check(['-S', '-tO', '--info'], {}, output_contains='translation')
+        self.check(['-S', '-tO', '--version'], {}, output_contains='Python')
+        self.check(['-S', '-tOV'], {}, output_contains='Python')
+        self.check(['--jit', 'foobar', '-S'], {}, sys_argv=[''],
                    run_stdin=True, no_site=1)
-        self.check(['-c', 'pass'], sys_argv=['-c'], run_command='pass')
-        self.check(['-cpass'], sys_argv=['-c'], run_command='pass')
-        self.check(['-cpass','x'], sys_argv=['-c','x'], run_command='pass')
-        self.check(['-Sc', 'pass'], sys_argv=['-c'], run_command='pass',
+        self.check(['-c', 'pass'], {}, sys_argv=['-c'], run_command='pass')
+        self.check(['-cpass'], {}, sys_argv=['-c'], run_command='pass')
+        self.check(['-cpass','x'], {}, sys_argv=['-c','x'], run_command='pass')
+        self.check(['-Sc', 'pass'], {}, sys_argv=['-c'], run_command='pass',
                    no_site=1)
-        self.check(['-Scpass'], sys_argv=['-c'], run_command='pass', no_site=1)
-        self.check(['-c', '', ''], sys_argv=['-c', ''], run_command='')
-        self.check(['-mfoo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+        self.check(['-Scpass'], {}, sys_argv=['-c'], run_command='pass', no_site=1)
+        self.check(['-c', '', ''], {}, sys_argv=['-c', ''], run_command='')
+        self.check(['-mfoo', 'bar', 'baz'], {}, sys_argv=['foo', 'bar', 'baz'],
                    run_module=True)
-        self.check(['-m', 'foo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+        self.check(['-m', 'foo', 'bar', 'baz'], {}, sys_argv=['foo', 'bar', 'baz'],
                    run_module=True)
-        self.check(['-Smfoo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+        self.check(['-Smfoo', 'bar', 'baz'], {}, sys_argv=['foo', 'bar', 'baz'],
                    run_module=True, no_site=1)
-        self.check(['-Sm', 'foo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+        self.check(['-Sm', 'foo', 'bar', 'baz'], {}, sys_argv=['foo', 'bar', 'baz'],
                    run_module=True, no_site=1)
-        self.check(['-', 'foo', 'bar'], sys_argv=['-', 'foo', 'bar'],
+        self.check(['-', 'foo', 'bar'], {}, sys_argv=['-', 'foo', 'bar'],
                    run_stdin=True)
-        self.check(['foo', 'bar'], sys_argv=['foo', 'bar'])
-        self.check(['foo', '-i'], sys_argv=['foo', '-i'])
-        self.check(['-i', 'foo'], sys_argv=['foo'], interactive=1, inspect=1)
-        self.check(['--', 'foo'], sys_argv=['foo'])
-        self.check(['--', '-i', 'foo'], sys_argv=['-i', 'foo'])
-        self.check(['--', '-', 'foo'], sys_argv=['-', 'foo'], run_stdin=True)
-        self.check(['-Wbog'], sys_argv=[''], warnoptions=['bog'], run_stdin=True)
-        self.check(['-W', 'ab', '-SWc'], sys_argv=[''], warnoptions=['ab', 'c'],
+        self.check(['foo', 'bar'], {}, sys_argv=['foo', 'bar'])
+        self.check(['foo', '-i'], {}, sys_argv=['foo', '-i'])
+        self.check(['-i', 'foo'], {}, sys_argv=['foo'], interactive=1, inspect=1)
+        self.check(['--', 'foo'], {}, sys_argv=['foo'])
+        self.check(['--', '-i', 'foo'], {}, sys_argv=['-i', 'foo'])
+        self.check(['--', '-', 'foo'], {}, sys_argv=['-', 'foo'], run_stdin=True)
+        self.check(['-Wbog'], {}, sys_argv=[''], warnoptions=['bog'], run_stdin=True)
+        self.check(['-W', 'ab', '-SWc'], {}, sys_argv=[''], warnoptions=['ab', 'c'],
                    run_stdin=True, no_site=1)
 
+        self.check([], {'PYTHONDEBUG': '1'}, sys_argv=[''], run_stdin=True, debug=1)
+        self.check([], {'PYTHONDONTWRITEBYTECODE': '1'}, sys_argv=[''], run_stdin=True, dont_write_bytecode=1)
+        self.check([], {'PYTHONNOUSERSITE': '1'}, sys_argv=[''], run_stdin=True, no_user_site=1)
+        self.check([], {'PYTHONUNBUFFERED': '1'}, sys_argv=[''], run_stdin=True, unbuffered=1)
+        self.check([], {'PYTHONVERBOSE': '1'}, sys_argv=[''], run_stdin=True, verbose=1)
+
     def test_sysflags(self):
         flags = (
             ("debug", "-d", "1"),
                     expected[flag1] = int(value)
             else:
                 expected = {flag: int(value)}
-            self.check([opt, '-c', 'pass'], sys_argv=['-c'],
+            self.check([opt, '-c', 'pass'], {}, sys_argv=['-c'],
                        run_command='pass', **expected)
 
     def test_sysflags_envvar(self, monkeypatch):
         monkeypatch.setenv('PYTHONNOUSERSITE', '1')
         expected = {"no_user_site": True}
-        self.check(['-c', 'pass'], sys_argv=['-c'], run_command='pass', **expected)
+        self.check(['-c', 'pass'], {}, sys_argv=['-c'], run_command='pass', **expected)
 
 
 class TestInteraction:

pypy/module/test_lib_pypy/numpypy/core/test_numeric.py

         assert not array_equal(a, array(b))
         assert not array_equal(array(a), b)
         assert not array_equal(array(a), array(b))
+
+class AppTestNumeric(BaseNumpyAppTest):
+
+    def test_outer(self):
+        from _numpypy import array
+        from numpypy import outer
+        a = [1, 2, 3]
+        b = [4, 5, 6]
+        res = outer(a, b)
+        expected = array([[ 4,  5,  6],
+                          [ 8, 10, 12],
+                          [12, 15, 18]])
+        assert (res == expected).all()
+

pypy/module/test_lib_pypy/numpypy/core/test_shape_base.py

+from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
+
+
+class AppTestShapeBase(BaseNumpyAppTest):
+
+    def test_atleast_1d(self):
+        from numpypy import array, array_equal
+        import numpypy as np
+        a = np.atleast_1d(1.0)
+        assert np.array_equal(a, [1.])
+
+        x = np.arange(9.0).reshape(3, 3)
+        a = np.atleast_1d(x)
+        assert np.array_equal(a, [[0.,  1.,  2.],
+                                  [3.,  4.,  5.],
+                                  [6.,  7.,  8.]])
+        assert np.atleast_1d(x) is x
+
+        a = np.atleast_1d(1, [3, 4])
+        assert len(a) == 2
+        assert array_equal(a[0], [1])
+        assert array_equal(a[1], [3, 4])
+
+    def test_atleast_2d(self):
+        import numpypy as np
+        a = np.atleast_2d(3.0)
+        assert np.array_equal(a, [[3.]])
+
+        x = np.arange(3.0)
+        a = np.atleast_2d(x)
+        assert np.array_equal(a, [[0., 1., 2.]])
+
+        a = np.atleast_2d(1, [1, 2], [[1, 2]])
+        assert len(a) == 3
+        assert np.array_equal(a[0], [[1]])
+        assert np.array_equal(a[1], [[1, 2]])
+        assert np.array_equal(a[2], [[1, 2]])
+
+    def test_atleast_3d(self):
+        import numpypy as np
+
+        a = np.atleast_3d(3.0)
+        assert np.array_equal(a, [[[3.]]])
+
+        x = np.arange(3.0)
+        assert np.atleast_3d(x).shape == (1, 3, 1)
+
+        x = np.arange(12.0).reshape(4, 3)
+        assert np.atleast_3d(x).shape == (4, 3, 1)
+
+        a = np.atleast_3d([1, 2])
+        assert np.array_equal(a, [[[1],
+                                   [2]]])
+        assert a.shape == (1, 2, 1)
+
+        a = np.atleast_3d([[1, 2]])
+        assert np.array_equal(a, [[[1],
+                                   [2]]])
+        assert a.shape == (1, 2, 1)
+
+        a = np.atleast_3d([[[1, 2]]])
+        assert np.array_equal(a, [[[1, 2]]])
+        assert a.shape == (1, 1, 2)
+
+    def test_vstack(self):
+        import numpypy as np
+
+        a = np.array([1, 2, 3])
+        b = np.array([2, 3, 4])
+        c = np.vstack((a, b))
+        assert np.array_equal(c, [[1, 2, 3],
+                                  [2, 3, 4]])
+
+        a = np.array([[1], [2], [3]])
+        b = np.array([[2], [3], [4]])
+        c = np.vstack((a, b))
+        assert np.array_equal(c, [[1],
+                                  [2],
+                                  [3],
+                                  [2],
+                                  [3],
+                                  [4]])
+
+        for shape1, shape2 in [[(2, 1), (3, 1)],
+                               [(2, 4), [3, 4]]]:
+            a, b = np.ones(shape1), np.ones(shape2)
+            assert np.all(np.vstack((a, b)) ==
+                          np.ones((a.shape[0] + b.shape[0],