Python array.array() Examples

The following are code examples for showing how to use array.array(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fs_image   Author: facebookincubator   File: common.py    MIT License 6 votes vote down vote up
def recv_fds(sock, msglen, maxfds, inheritable=False):
    '''
    Receives via a Unix domain socket a message of at most `msglen` bytes,
    with at most `maxfds` file descriptors in the ancillary data.  The file
    descriptors will be marked O_CLOEXEC unless inheritable is set to False.
    '''
    fds = array.array('i')
    msg, ancdata, msg_flags, _addr = sock.recvmsg(
        msglen, maxfds * socket.CMSG_SPACE(fds.itemsize),
        0 if inheritable else socket.MSG_CMSG_CLOEXEC,
    )
    assert not (msg_flags & socket.MSG_TRUNC), msg_flags
    assert not (msg_flags & socket.MSG_CTRUNC), msg_flags
    assert not (msg_flags & socket.MSG_ERRQUEUE), msg_flags
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        assert cmsg_level == socket.SOL_SOCKET, cmsg_level
        assert cmsg_type == socket.SCM_RIGHTS, cmsg_type
        assert len(cmsg_data) % fds.itemsize == 0, cmsg_data
        fds.frombytes(cmsg_data)
    return msg, list(fds)


# Don't wait forever if the `send_fds` side crashes.  This is 2.5 minutes so
# we still make progress on overloaded hosts. 
Example 2
Project: pyblish-win   Author: pyblish   File: httplib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def send(self, data):
        """Send `data' to the server."""
        if self.sock is None:
            if self.auto_open:
                self.connect()
            else:
                raise NotConnected()

        if self.debuglevel > 0:
            print "send:", repr(data)
        blocksize = 8192
        if hasattr(data,'read') and not isinstance(data, array):
            if self.debuglevel > 0: print "sendIng a read()able"
            datablock = data.read(blocksize)
            while datablock:
                self.sock.sendall(datablock)
                datablock = data.read(blocksize)
        else:
            self.sock.sendall(data) 
Example 3
Project: pyblish-win   Author: pyblish   File: wave.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def writeframesraw(self, data):
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth in (2, 4) and sys.byteorder == 'big':
            import array
            a = array.array(_array_fmts[self._sampwidth])
            a.fromstring(data)
            data = a
            assert data.itemsize == self._sampwidth
            data.byteswap()
            data.tofile(self._file)
            self._datawritten = self._datawritten + len(data) * self._sampwidth
        else:
            if self._sampwidth == 3 and sys.byteorder == 'big':
                data = _byteswap3(data)
            self._file.write(data)
            self._datawritten = self._datawritten + len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example 4
Project: pyblish-win   Author: pyblish   File: test_frombuffer.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_fom_buffer(self):
        a = array.array("i", range(16))
        x = (c_int * 16).from_buffer(a)

        y = X.from_buffer(a)
        self.assertEqual(y.c_int, a[0])
        self.assertFalse(y.init_called)

        self.assertEqual(x[:], a.tolist())

        a[0], a[-1] = 200, -200
        self.assertEqual(x[:], a.tolist())

        self.assertIn(a, x._objects.values())

        self.assertRaises(ValueError,
                          c_int.from_buffer, a, -1)

        expected = x[:]
        del a; gc.collect(); gc.collect(); gc.collect()
        self.assertEqual(x[:], expected)

        self.assertRaises(TypeError,
                          (c_char * 16).from_buffer, "a" * 16) 
Example 5
Project: pyblish-win   Author: pyblish   File: _pyio.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def read(self, n=None):
        """Read and return up to n bytes.

        If the argument is omitted, None, or negative, reads and
        returns all data until EOF.

        If the argument is positive, and the underlying raw stream is
        not 'interactive', multiple raw reads may be issued to satisfy
        the byte count (unless EOF is reached first).  But for
        interactive raw streams (XXX and for pipes?), at most one raw
        read will be issued, and a short result does not imply that
        EOF is imminent.

        Returns an empty bytes array on EOF.

        Raises BlockingIOError if the underlying raw stream has no
        data at the moment.
        """
        self._unsupported("read") 
Example 6
Project: pyblish-win   Author: pyblish   File: _pyio.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def readinto(self, b):
        """Read up to len(b) bytes into b.

        Like read(), this may issue multiple reads to the underlying raw
        stream, unless the latter is 'interactive'.

        Returns the number of bytes read (0 for EOF).

        Raises BlockingIOError if the underlying raw stream has no
        data at the moment.
        """
        # XXX This ought to work with anything that supports the buffer API
        data = self.read(len(b))
        n = len(data)
        try:
            b[:n] = data
        except TypeError as err:
            import array
            if not isinstance(b, array.array):
                raise err
            b[:n] = array.array(b'b', data)
        return n 
Example 7
Project: pyblish-win   Author: pyblish   File: test_ioctl.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _check_ioctl_mutate_len(self, nbytes=None):
        buf = array.array('i')
        intsize = buf.itemsize
        ids = (os.getpgrp(), os.getsid(0))
        # A fill value unlikely to be in `ids`
        fill = -12345
        if nbytes is not None:
            # Extend the buffer so that it is exactly `nbytes` bytes long
            buf.extend([fill] * (nbytes // intsize))
            self.assertEqual(len(buf) * intsize, nbytes)   # sanity check
        else:
            buf.append(fill)
        with open("/dev/tty", "r") as tty:
            r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
        rpgrp = buf[0]
        self.assertEqual(r, 0)
        self.assertIn(rpgrp, ids) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_memoryview.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_constructor(self):
        for tp in self._types:
            ob = tp(self._source)
            self.assertTrue(memoryview(ob))
            self.assertTrue(memoryview(object=ob))
            self.assertRaises(TypeError, memoryview)
            self.assertRaises(TypeError, memoryview, ob, ob)
            self.assertRaises(TypeError, memoryview, argument=ob)
            self.assertRaises(TypeError, memoryview, ob, argument=True)

#class ArrayMemoryviewTest(unittest.TestCase,
    #BaseMemoryviewTests, BaseArrayMemoryTests):

    #def test_array_assign(self):
        ## Issue #4569: segfault when mutating a memoryview with itemsize != 1
        #a = array.array('i', range(10))
        #m = memoryview(a)
        #new_a = array.array('i', range(9, -1, -1))
        #m[:] = new_a
        #self.assertEqual(a, new_a) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_struct.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_pack_into_fn(self):
        test_string = 'Reykjavik rocks, eow!'
        writable_buf = array.array('c', ' '*100)
        fmt = '21s'
        pack_into = lambda *args: struct.pack_into(fmt, *args)

        # Test without offset.
        pack_into(writable_buf, 0, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)]
        self.assertEqual(from_buf, test_string)

        # Test with offset.
        pack_into(writable_buf, 10, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)+10]
        self.assertEqual(from_buf, test_string[:10] + test_string)

        # Go beyond boundaries.
        small_buf = array.array('c', ' '*10)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
                          test_string)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
                          test_string) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_filewrite(self):
        a = array.array(self.typecode, 2*self.example)
        f = open(test_support.TESTFN, 'wb')
        try:
            f.write(a)
            f.close()
            b = array.array(self.typecode)
            f = open(test_support.TESTFN, 'rb')
            b.fromfile(f, len(self.example))
            self.assertEqual(b, array.array(self.typecode, self.example))
            self.assertNotEqual(a, b)
            b.fromfile(f, len(self.example))
            self.assertEqual(a, b)
            f.close()
        finally:
            if not f.closed:
                f.close()
            test_support.unlink(test_support.TESTFN) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_iadd(self):
        a = array.array(self.typecode, self.example[::-1])
        b = a
        a += array.array(self.typecode, 2*self.example)
        self.assertIs(a, b)
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[::-1]+2*self.example)
        )
        a = array.array(self.typecode, self.example)
        a += a
        self.assertEqual(
            a,
            array.array(self.typecode, self.example + self.example)
        )

        b = array.array(self.badtypecode())
        self.assertRaises(TypeError, a.__add__, b)

        self.assertRaises(TypeError, a.__iadd__, "bad") 
Example 12
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extended_set_del_slice(self):
        indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
        for start in indices:
            for stop in indices:
                # Everything except the initial 0 (invalid step)
                for step in indices[1:]:
                    a = array.array(self.typecode, self.example)
                    L = list(a)
                    # Make sure we have a slice of exactly the right length,
                    # but with (hopefully) different data.
                    data = L[start:stop:step]
                    data.reverse()
                    L[start:stop:step] = data
                    a[start:stop:step] = array.array(self.typecode, data)
                    self.assertEqual(a, array.array(self.typecode, L))

                    del L[start:stop:step]
                    del a[start:stop:step]
                    self.assertEqual(a, array.array(self.typecode, L)) 
Example 13
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extend(self):
        a = array.array(self.typecode, self.example)
        self.assertRaises(TypeError, a.extend)
        a.extend(array.array(self.typecode, self.example[::-1]))
        self.assertEqual(
            a,
            array.array(self.typecode, self.example+self.example[::-1])
        )

        a = array.array(self.typecode, self.example)
        a.extend(a)
        self.assertEqual(
            a,
            array.array(self.typecode, self.example+self.example)
        )

        b = array.array(self.badtypecode())
        self.assertRaises(TypeError, a.extend, b)

        a = array.array(self.typecode, self.example)
        a.extend(self.example[::-1])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example+self.example[::-1])
        ) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_constructor_with_iterable_argument(self):
        a = array.array(self.typecode, iter(self.example))
        b = array.array(self.typecode, self.example)
        self.assertEqual(a, b)

        # non-iterable argument
        self.assertRaises(TypeError, array.array, self.typecode, 10)

        # pass through errors raised in __iter__
        class A:
            def __iter__(self):
                raise UnicodeError
        self.assertRaises(UnicodeError, array.array, self.typecode, A())

        # pass through errors raised in next()
        def B():
            raise UnicodeError
            yield None
        self.assertRaises(UnicodeError, array.array, self.typecode, B()) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_subbclassing(self):
        class EditableString(array.array):
            def __new__(cls, s, *args, **kwargs):
                return array.array.__new__(cls, 'c', s)

            def __init__(self, s, color='blue'):
                self.color = color

            def strip(self):
                self[:] = array.array('c', self.tostring().strip())

            def __repr__(self):
                return 'EditableString(%r)' % self.tostring()

        s = EditableString("\ttest\r\n")
        s.strip()
        self.assertEqual(s.tostring(), "test")

        self.assertEqual(s.color, "blue")
        s.color = "red"
        self.assertEqual(s.color, "red")
        self.assertEqual(s.__dict__.keys(), ["color"]) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_unicode(self):
            self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii'))

            a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape'))
            a.fromunicode(unicode(' ', 'ascii'))
            a.fromunicode(unicode('', 'ascii'))
            a.fromunicode(unicode('', 'ascii'))
            a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape'))
            s = a.tounicode()
            self.assertEqual(
                s,
                unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape')
            )

            s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape')
            a = array.array('u', s)
            self.assertEqual(
                repr(a),
                r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')"""
            )

            self.assertRaises(TypeError, a.fromunicode) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_delslice(self):
        a = array.array(self.typecode, range(5))
        del a[::2]
        self.assertEqual(a, array.array(self.typecode, [1,3]))
        a = array.array(self.typecode, range(5))
        del a[1::2]
        self.assertEqual(a, array.array(self.typecode, [0,2,4]))
        a = array.array(self.typecode, range(5))
        del a[1::-2]
        self.assertEqual(a, array.array(self.typecode, [0,2,3,4]))
        a = array.array(self.typecode, range(10))
        del a[::1000]
        self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9]))
        # test issue7788
        a = array.array(self.typecode, range(10))
        del a[9::1<<333] 
Example 18
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_assignment(self):
        a = array.array(self.typecode, range(10))
        a[::2] = array.array(self.typecode, [42]*5)
        self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9]))
        a = array.array(self.typecode, range(10))
        a[::-4] = array.array(self.typecode, [10]*3)
        self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
        a = array.array(self.typecode, range(4))
        a[::-1] = a
        self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0]))
        a = array.array(self.typecode, range(10))
        b = a[:]
        c = a[:]
        ins = array.array(self.typecode, range(2))
        a[2:3] = ins
        b[slice(2,3)] = ins
        c[2:3:] = ins 
Example 19
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_subclassing(self):
        typecode = self.typecode
        class ExaggeratingArray(array.array):
            __slots__ = ['offset']

            def __new__(cls, typecode, data, offset):
                return array.array.__new__(cls, typecode, data)

            def __init__(self, typecode, data, offset):
                self.offset = offset

            def __getitem__(self, i):
                return array.array.__getitem__(self, i) + self.offset

        a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4)
        self.assertEntryEqual(a[0], 7)

        self.assertRaises(AttributeError, setattr, a, "color", "blue") 
Example 20
Project: UrsaRobotics_SmartHome   Author: stav98   File: bme280.py    GNU General Public License v3.0 5 votes vote down vote up
def read_raw_data(self, result):
        """ Reads the raw (uncompensated) data from the sensor.

            Args:
                result: array of length 3 or alike where the result will be
                stored, in temperature, pressure, humidity order
            Returns:
                None
        """

        self._l1_barray[0] = self._mode
        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM,
                             self._l1_barray)
        self._l1_barray[0] = self._mode << 5 | self._mode << 2 | 1
        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             self._l1_barray)

        sleep_time = 1250 + 2300 * (1 << self._mode)
        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
        sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
        time.sleep_us(sleep_time)  # Wait the required time

        # burst readout from 0xF7 to 0xFE, recommended by datasheet
        self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
        readout = self._l8_barray
        # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
        # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4
        # humidity(0xFD): (msb << 8) | lsb
        raw_hum = (readout[6] << 8) | readout[7]

        result[0] = raw_temp
        result[1] = raw_press
        result[2] = raw_hum 
Example 21
Project: fs_image   Author: facebookincubator   File: send_fds_and_run.py    MIT License 5 votes vote down vote up
def send_fds(sock, fds):
    msg = b'unused'
    num_sent = sock.sendmsg([msg], [(
        socket.SOL_SOCKET, socket.SCM_RIGHTS,
        array.array('i', fds).tobytes(),
        # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
    )])
    assert len(msg) == num_sent, (msg, num_sent) 
Example 22
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 5 votes vote down vote up
def _make_socket_and_send_via(*, unix_sock_fd):
    '''
    Creates a TCP stream socket and sends it elsewhere via the provided Unix
    domain socket file descriptor.  This is useful for obtaining a socket
    that belongs to a different network namespace (i.e.  creating a socket
    inside a container, but binding it from outside the container).

    IMPORTANT: This code must not write anything to stdout, the fd can be 1.
    '''
    # NB: Some code here is (sort of) copy-pasta'd in `send_fds_and_run.py`,
    # but it's not obviously worthwhile to reuse it here.
    return ['python3', '-c', textwrap.dedent('''\
    import array, socket, sys

    def send_fds(sock, msg: bytes, fds: 'List[int]'):
        num_sent = sock.sendmsg([msg], [(
            socket.SOL_SOCKET, socket.SCM_RIGHTS,
            array.array('i', fds).tobytes(),
            # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
        )])
        assert len(msg) == num_sent, (msg, num_sent)

    # Make a socket in this netns, and send it to the parent.
    with socket.socket(fileno=''' + str(unix_sock_fd) + ''') as lsock:
        print(f'Sending FD to parent', file=sys.stderr)
        lsock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
        with lsock.accept()[0] as csock, socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ) as inet_sock:
            csock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
            send_fds(csock, b'ohai', [inet_sock.fileno()])
    ''')] 
Example 23
Project: pyblish-win   Author: pyblish   File: msgfmt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def generate():
    "Return the generated output."
    global MESSAGES
    keys = MESSAGES.keys()
    # the keys are sorted in the .mo file
    keys.sort()
    offsets = []
    ids = strs = ''
    for id in keys:
        # For each string, we need size and file offset.  Each string is NUL
        # terminated; the NUL does not count into the size.
        offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
        ids += id + '\0'
        strs += MESSAGES[id] + '\0'
    output = ''
    # The header is 7 32-bit unsigned integers.  We don't use hash tables, so
    # the keys start right after the index tables.
    # translated string.
    keystart = 7*4+16*len(keys)
    # and the values start after the keys
    valuestart = keystart + len(ids)
    koffsets = []
    voffsets = []
    # The string table first has the list of keys, then the list of values.
    # Each entry has first the size of the string, then the file offset.
    for o1, l1, o2, l2 in offsets:
        koffsets += [l1, o1+keystart]
        voffsets += [l2, o2+valuestart]
    offsets = koffsets + voffsets
    output = struct.pack("Iiiiiii",
                         0x950412deL,       # Magic
                         0,                 # Version
                         len(keys),         # # of entries
                         7*4,               # start of key index
                         7*4+len(keys)*8,   # start of value index
                         0, 0)              # size and offset of hash table
    output += array.array("i", offsets).tostring()
    output += ids
    output += strs
    return output 
Example 24
Project: pyblish-win   Author: pyblish   File: wave.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return ''
        if self._sampwidth in (2, 4) and sys.byteorder == 'big':
            # unfortunately the fromfile() method does not take
            # something that only looks like a file object, so
            # we have to reach into the innards of the chunk object
            import array
            chunk = self._data_chunk
            data = array.array(_array_fmts[self._sampwidth])
            assert data.itemsize == self._sampwidth
            nitems = nframes * self._nchannels
            if nitems * self._sampwidth > chunk.chunksize - chunk.size_read:
                nitems = (chunk.chunksize - chunk.size_read) / self._sampwidth
            data.fromfile(chunk.file.file, nitems)
            # "tell" data chunk how much was read
            chunk.size_read = chunk.size_read + nitems * self._sampwidth
            # do the same for the outermost chunk
            chunk = chunk.file
            chunk.size_read = chunk.size_read + nitems * self._sampwidth
            data.byteswap()
            data = data.tostring()
        else:
            data = self._data_chunk.read(nframes * self._framesize)
            if self._sampwidth == 3 and sys.byteorder == 'big':
                data = _byteswap3(data)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example 25
Project: pyblish-win   Author: pyblish   File: test_pointers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_from_address(self):
        from array import array
        a = array('i', [100, 200, 300, 400, 500])
        addr = a.buffer_info()[0]

        p = POINTER(POINTER(c_int))
##        print dir(p)
##        print p.from_address
##        print p.from_address(addr)[0][0] 
Example 26
Project: pyblish-win   Author: pyblish   File: test_numbers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_float_from_address(self):
        from array import array
        for t in float_types:
            a = array(t._type_, [3.14])
            v = t.from_address(a.buffer_info()[0])
            self.assertEqual(v.value, a[0])
            self.assertIs(type(v), t)
            a[0] = 2.3456e17
            self.assertEqual(v.value, a[0])
            self.assertIs(type(v), t) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_numbers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_char_from_address(self):
        from ctypes import c_char
        from array import array

        a = array('c', 'x')
        v = c_char.from_address(a.buffer_info()[0])
        self.assertEqual(v.value, a[0])
        self.assertIs(type(v), c_char)

        a[0] = '?'
        self.assertEqual(v.value, a[0])

    # array does not support c_bool / 't' 
Example 28
Project: pyblish-win   Author: pyblish   File: test_numbers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bool_from_address(self):
        from ctypes import c_bool
        from array import array
        a = array(c_bool._type_, [True])
        v = t.from_address(a.buffer_info()[0])
        self.assertEqual(v.value, a[0])
        self.assertEqual(type(v) is t)
        a[0] = False
        self.assertEqual(v.value, a[0])
        self.assertEqual(type(v) is t) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_frombuffer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fom_buffer_with_offset(self):
        a = array.array("i", range(16))
        x = (c_int * 15).from_buffer(a, sizeof(c_int))

        self.assertEqual(x[:], a.tolist()[1:])
        self.assertRaises(ValueError, lambda: (c_int * 16).from_buffer(a, sizeof(c_int)))
        self.assertRaises(ValueError, lambda: (c_int * 1).from_buffer(a, 16 * sizeof(c_int))) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_frombuffer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fom_buffer_copy_with_offset(self):
        a = array.array("i", range(16))
        x = (c_int * 15).from_buffer_copy(a, sizeof(c_int))

        self.assertEqual(x[:], a.tolist()[1:])
        self.assertRaises(ValueError,
                          (c_int * 16).from_buffer_copy, a, sizeof(c_int))
        self.assertRaises(ValueError,
                          (c_int * 1).from_buffer_copy, a, 16 * sizeof(c_int)) 
Example 31
Project: pyblish-win   Author: pyblish   File: sre_compile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _bytes_to_codes(b):
    # Convert block indices to word array
    import array
    if _sre.CODESIZE == 2:
        code = 'H'
    else:
        code = 'I'
    a = array.array(code, bytes(b))
    assert a.itemsize == _sre.CODESIZE
    assert len(a) * a.itemsize == len(b)
    return a.tolist() 
Example 32
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testRecvIntoArray(self):
        buf = array.array('c', ' '*1024)
        nbytes = self.cli_conn.recv_into(buf)
        self.assertEqual(nbytes, len(MSG))
        msg = buf.tostring()[:len(MSG)]
        self.assertEqual(msg, MSG) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_io.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_array_writes(self):
        a = array.array(b'i', range(10))
        n = len(a.tostring())
        with self.open(support.TESTFN, "wb", 0) as f:
            self.assertEqual(f.write(a), n)
        with self.open(support.TESTFN, "wb") as f:
            self.assertEqual(f.write(a), n) 
Example 34
Project: pyblish-win   Author: pyblish   File: audiotests.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def byteswap2(data):
    a = array.array('h')
    a.fromstring(data)
    a.byteswap()
    return a.tostring() 
Example 35
Project: pyblish-win   Author: pyblish   File: audiotests.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def byteswap4(data):
    a = array.array('i')
    a.fromstring(data)
    a.byteswap()
    return a.tostring() 
Example 36
Project: pyblish-win   Author: pyblish   File: test_file2k.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testReadinto(self):
        # verify readinto
        self.f.write('12')
        self.f.close()
        a = array('c', 'x'*10)
        self.f = open(TESTFN, 'rb')
        n = self.f.readinto(a)
        self.assertEqual('12', a.tostring()[:n]) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_file2k.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_close_open_readinto(self):
        def io_func():
            a = array('c', 'xxxxx')
            self.f.readinto(a)
        self._test_close_open_io(io_func) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_send(self):
        expected = 'this is a test this is only a test'
        conn = httplib.HTTPConnection('example.com')
        sock = FakeSocket(None)
        conn.sock = sock
        conn.send(expected)
        self.assertEqual(expected, sock.data)
        sock.data = ''
        conn.send(array.array('c', expected))
        self.assertEqual(expected, sock.data)
        sock.data = ''
        conn.send(StringIO.StringIO(expected))
        self.assertEqual(expected, sock.data) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testReadinto(self):
        # verify readinto
        self.f.write(b'12')
        self.f.close()
        a = array('b', b'x'*10)
        self.f = self.open(TESTFN, 'rb')
        n = self.f.readinto(a)
        self.assertEqual(b'12', a.tostring()[:n]) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_StringIO.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_array_support(self):
        # Issue #1730114: cStringIO should accept array objects
        a = array.array('B', [0,1,2])
        f = self.MODULE.StringIO(a)
        self.assertEqual(f.getvalue(), '\x00\x01\x02') 
Example 41
Project: pyblish-win   Author: pyblish   File: test_struct.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pack_into(self):
        test_string = 'Reykjavik rocks, eow!'
        writable_buf = array.array('c', ' '*100)
        fmt = '21s'
        s = struct.Struct(fmt)

        # Test without offset
        s.pack_into(writable_buf, 0, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)]
        self.assertEqual(from_buf, test_string)

        # Test with offset.
        s.pack_into(writable_buf, 10, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)+10]
        self.assertEqual(from_buf, test_string[:10] + test_string)

        # Go beyond boundaries.
        small_buf = array.array('c', ' '*10)
        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
                          test_string)
        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
                          test_string)

        # Test bogus offset (issue 3694)
        sb = small_buf
        self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
                          None) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_struct.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_unpack_with_buffer(self):
        with check_py3k_warnings(("buffer.. not supported in 3.x",
                                  DeprecationWarning)):
            # SF bug 1563759: struct.unpack doesn't support buffer protocol objects
            data1 = array.array('B', '\x12\x34\x56\x78')
            data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
            for data in [data1, data2]:
                value, = struct.unpack('>I', data)
                self.assertEqual(value, 0x12345678)

            self.test_unpack_from(cls=buffer) 
Example 43
Project: pyblish-win   Author: pyblish   File: test_struct.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_sizeof(self, format_str, number_of_codes):
        # The size of 'PyStructObject'
        totalsize = support.calcobjsize('5P')
        # The size taken up by the 'formatcode' dynamic array
        totalsize += struct.calcsize('3P') * (number_of_codes + 1)
        support.check_sizeof(self, struct.Struct(format_str), totalsize) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_constructor(self):
        self.assertRaises(TypeError, array.array)
        self.assertRaises(TypeError, array.array, spam=42)
        self.assertRaises(TypeError, array.array, 'xx')
        self.assertRaises(ValueError, array.array, 'x') 
Example 45
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_constructor(self):
        a = array.array(self.typecode)
        self.assertEqual(a.typecode, self.typecode)
        self.assertGreaterEqual(a.itemsize, self.minitemsize)
        self.assertRaises(TypeError, array.array, self.typecode, None) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_len(self):
        a = array.array(self.typecode)
        a.append(self.example[0])
        self.assertEqual(len(a), 1)

        a = array.array(self.typecode, self.example)
        self.assertEqual(len(a), len(self.example)) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_buffer_info(self):
        a = array.array(self.typecode, self.example)
        self.assertRaises(TypeError, a.buffer_info, 42)
        bi = a.buffer_info()
        self.assertIsInstance(bi, tuple)
        self.assertEqual(len(bi), 2)
        self.assertIsInstance(bi[0], (int, long))
        self.assertIsInstance(bi[1], int)
        self.assertEqual(bi[1], len(a)) 
Example 48
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_byteswap(self):
        a = array.array(self.typecode, self.example)
        self.assertRaises(TypeError, a.byteswap, 42)
        if a.itemsize in (1, 2, 4, 8):
            b = array.array(self.typecode, self.example)
            b.byteswap()
            if a.itemsize==1:
                self.assertEqual(a, b)
            else:
                self.assertNotEqual(a, b)
            b.byteswap()
            self.assertEqual(a, b) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy(self):
        import copy
        a = array.array(self.typecode, self.example)
        b = copy.deepcopy(a)
        self.assertNotEqual(id(a), id(b))
        self.assertEqual(a, b) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pickle(self):
        for protocol in range(HIGHEST_PROTOCOL + 1):
            a = array.array(self.typecode, self.example)
            b = loads(dumps(a, protocol))
            self.assertNotEqual(id(a), id(b))
            self.assertEqual(a, b)

            a = ArraySubclass(self.typecode, self.example)
            a.x = 10
            b = loads(dumps(a, protocol))
            self.assertNotEqual(id(a), id(b))
            self.assertEqual(a, b)
            self.assertEqual(a.x, b.x)
            self.assertEqual(type(a), type(b)) 
Example 51
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pickle_for_empty_array(self):
        for protocol in range(HIGHEST_PROTOCOL + 1):
            a = array.array(self.typecode)
            b = loads(dumps(a, protocol))
            self.assertNotEqual(id(a), id(b))
            self.assertEqual(a, b)

            a = ArraySubclass(self.typecode)
            a.x = 10
            b = loads(dumps(a, protocol))
            self.assertNotEqual(id(a), id(b))
            self.assertEqual(a, b)
            self.assertEqual(a.x, b.x)
            self.assertEqual(type(a), type(b)) 
Example 52
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_insert(self):
        a = array.array(self.typecode, self.example)
        a.insert(0, self.example[0])
        self.assertEqual(len(a), 1+len(self.example))
        self.assertEqual(a[0], a[1])
        self.assertRaises(TypeError, a.insert)
        self.assertRaises(TypeError, a.insert, None)
        self.assertRaises(TypeError, a.insert, 0, None)

        a = array.array(self.typecode, self.example)
        a.insert(-1, self.example[0])
        self.assertEqual(
            a,
            array.array(
                self.typecode,
                self.example[:-1] + self.example[:1] + self.example[-1:]
            )
        )

        a = array.array(self.typecode, self.example)
        a.insert(-1000, self.example[0])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[:1] + self.example)
        )

        a = array.array(self.typecode, self.example)
        a.insert(1000, self.example[0])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example + self.example[:1])
        ) 
Example 53
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tofromfile(self):
        a = array.array(self.typecode, 2*self.example)
        self.assertRaises(TypeError, a.tofile)
        self.assertRaises(TypeError, a.tofile, cStringIO.StringIO())
        test_support.unlink(test_support.TESTFN)
        f = open(test_support.TESTFN, 'wb')
        try:
            a.tofile(f)
            f.close()
            b = array.array(self.typecode)
            f = open(test_support.TESTFN, 'rb')
            self.assertRaises(TypeError, b.fromfile)
            self.assertRaises(
                TypeError,
                b.fromfile,
                cStringIO.StringIO(), len(self.example)
            )
            b.fromfile(f, len(self.example))
            self.assertEqual(b, array.array(self.typecode, self.example))
            self.assertNotEqual(a, b)
            b.fromfile(f, len(self.example))
            self.assertEqual(a, b)
            self.assertRaises(EOFError, b.fromfile, f, 1)
            f.close()
        finally:
            if not f.closed:
                f.close()
            test_support.unlink(test_support.TESTFN) 
Example 54
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tofromlist(self):
        a = array.array(self.typecode, 2*self.example)
        b = array.array(self.typecode)
        self.assertRaises(TypeError, a.tolist, 42)
        self.assertRaises(TypeError, b.fromlist)
        self.assertRaises(TypeError, b.fromlist, 42)
        self.assertRaises(TypeError, b.fromlist, [None])
        b.fromlist(a.tolist())
        self.assertEqual(a, b) 
Example 55
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tofromstring(self):
        a = array.array(self.typecode, 2*self.example)
        b = array.array(self.typecode)
        self.assertRaises(TypeError, a.tostring, 42)
        self.assertRaises(TypeError, b.fromstring)
        self.assertRaises(TypeError, b.fromstring, 42)
        b.fromstring(a.tostring())
        self.assertEqual(a, b)
        if a.itemsize>1:
            self.assertRaises(ValueError, b.fromstring, "x") 
Example 56
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        a = array.array(self.typecode, 2*self.example)
        self.assertEqual(a, eval(repr(a), {"array": array.array}))

        a = array.array(self.typecode)
        self.assertEqual(repr(a), "array('%s')" % self.typecode) 
Example 57
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_str(self):
        a = array.array(self.typecode, 2*self.example)
        str(a) 
Example 58
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_add(self):
        a = array.array(self.typecode, self.example) \
            + array.array(self.typecode, self.example[::-1])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example + self.example[::-1])
        )

        b = array.array(self.badtypecode())
        self.assertRaises(TypeError, a.__add__, b)

        self.assertRaises(TypeError, a.__add__, "bad") 
Example 59
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mul(self):
        a = 5*array.array(self.typecode, self.example)
        self.assertEqual(
            a,
            array.array(self.typecode, 5*self.example)
        )

        a = array.array(self.typecode, self.example)*5
        self.assertEqual(
            a,
            array.array(self.typecode, self.example*5)
        )

        a = 0*array.array(self.typecode, self.example)
        self.assertEqual(
            a,
            array.array(self.typecode)
        )

        a = (-1)*array.array(self.typecode, self.example)
        self.assertEqual(
            a,
            array.array(self.typecode)
        )

        self.assertRaises(TypeError, a.__mul__, "bad") 
Example 60
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_imul(self):
        a = array.array(self.typecode, self.example)
        b = a

        a *= 5
        self.assertIs(a, b)
        self.assertEqual(
            a,
            array.array(self.typecode, 5*self.example)
        )

        a *= 0
        self.assertIs(a, b)
        self.assertEqual(a, array.array(self.typecode))

        a *= 1000
        self.assertIs(a, b)
        self.assertEqual(a, array.array(self.typecode))

        a *= -1
        self.assertIs(a, b)
        self.assertEqual(a, array.array(self.typecode))

        a = array.array(self.typecode, self.example)
        a *= -1
        self.assertEqual(a, array.array(self.typecode))

        self.assertRaises(TypeError, a.__imul__, "bad") 
Example 61
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_getitem(self):
        a = array.array(self.typecode, self.example)
        self.assertEntryEqual(a[0], self.example[0])
        self.assertEntryEqual(a[0L], self.example[0])
        self.assertEntryEqual(a[-1], self.example[-1])
        self.assertEntryEqual(a[-1L], self.example[-1])
        self.assertEntryEqual(a[len(self.example)-1], self.example[-1])
        self.assertEntryEqual(a[-len(self.example)], self.example[0])
        self.assertRaises(TypeError, a.__getitem__)
        self.assertRaises(IndexError, a.__getitem__, len(self.example))
        self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1) 
Example 62
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_delitem(self):
        a = array.array(self.typecode, self.example)
        del a[0]
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[1:])
        )

        a = array.array(self.typecode, self.example)
        del a[-1]
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[:-1])
        )

        a = array.array(self.typecode, self.example)
        del a[len(self.example)-1]
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[:-1])
        )

        a = array.array(self.typecode, self.example)
        del a[-len(self.example)]
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[1:])
        )

        self.assertRaises(TypeError, a.__delitem__)
        self.assertRaises(TypeError, a.__delitem__, None)
        self.assertRaises(IndexError, a.__delitem__, len(self.example))
        self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1) 
Example 63
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_extended_getslice(self):
        # Test extended slicing by comparing with list slicing
        # (Assumes list conversion works correctly, too)
        a = array.array(self.typecode, self.example)
        indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
        for start in indices:
            for stop in indices:
                # Everything except the initial 0 (invalid step)
                for step in indices[1:]:
                    self.assertEqual(list(a[start:stop:step]),
                                     list(a)[start:stop:step]) 
Example 64
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_index(self):
        example = 2*self.example
        a = array.array(self.typecode, example)
        self.assertRaises(TypeError, a.index)
        for x in example:
            self.assertEqual(a.index(x), example.index(x))
        self.assertRaises(ValueError, a.index, None)
        self.assertRaises(ValueError, a.index, self.outside) 
Example 65
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_remove(self):
        for x in self.example:
            example = 2*self.example
            a = array.array(self.typecode, example)
            pos = example.index(x)
            example2 = example[:pos] + example[pos+1:]
            a.remove(x)
            self.assertEqual(a, array.array(self.typecode, example2))

        a = array.array(self.typecode, self.example)
        self.assertRaises(ValueError, a.remove, self.outside)

        self.assertRaises(ValueError, a.remove, None) 
Example 66
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pop(self):
        a = array.array(self.typecode)
        self.assertRaises(IndexError, a.pop)

        a = array.array(self.typecode, 2*self.example)
        self.assertRaises(TypeError, a.pop, 42, 42)
        self.assertRaises(TypeError, a.pop, None)
        self.assertRaises(IndexError, a.pop, len(a))
        self.assertRaises(IndexError, a.pop, -len(a)-1)

        self.assertEntryEqual(a.pop(0), self.example[0])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[1:]+self.example)
        )
        self.assertEntryEqual(a.pop(1), self.example[2])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example)
        )
        self.assertEntryEqual(a.pop(0), self.example[1])
        self.assertEntryEqual(a.pop(), self.example[-1])
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[3:]+self.example[:-1])
        ) 
Example 67
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_reverse(self):
        a = array.array(self.typecode, self.example)
        self.assertRaises(TypeError, a.reverse, 42)
        a.reverse()
        self.assertEqual(
            a,
            array.array(self.typecode, self.example[::-1])
        ) 
Example 68
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_buffer(self):
        a = array.array(self.typecode, self.example)
        with test_support.check_py3k_warnings():
            b = buffer(a)
        self.assertEqual(b[0], a.tostring()[0]) 
Example 69
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_weakref(self):
        s = array.array(self.typecode, self.example)
        p = proxy(s)
        self.assertEqual(p.tostring(), s.tostring())
        s = None
        self.assertRaises(ReferenceError, len, p) 
Example 70
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bug_782369(self):
        for i in range(10):
            b = array.array('B', range(64))
        rc = sys.getrefcount(10)
        for i in range(10):
            b = array.array('B', range(64))
        self.assertEqual(rc, sys.getrefcount(10)) 
Example 71
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setitem(self):
        super(StringTest, self).test_setitem()
        a = array.array(self.typecode, self.example)
        self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2]) 
Example 72
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_extslice(self):
        a = array.array(self.typecode, range(5))
        self.assertEqual(a[::], a)
        self.assertEqual(a[::2], array.array(self.typecode, [0,2,4]))
        self.assertEqual(a[1::2], array.array(self.typecode, [1,3]))
        self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0]))
        self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0]))
        self.assertEqual(a[3::-2], array.array(self.typecode, [3,1]))
        self.assertEqual(a[-100:100:], a)
        self.assertEqual(a[100:-100:-1], a[::-1])
        self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4]))
        self.assertEqual(a[1000:2000:2], array.array(self.typecode, []))
        self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, [])) 
Example 73
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_iterationcontains(self):
        a = array.array(self.typecode, range(10))
        self.assertEqual(list(a), range(10))
        b = array.array(self.typecode, [20])
        self.assertEqual(a[-1] in a, True)
        self.assertEqual(b[0] not in a, True) 
Example 74
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_overflow(self):
        a = array.array(self.typecode)
        lower = -1 * long(pow(2, a.itemsize * 8 - 1))
        upper = long(pow(2, a.itemsize * 8 - 1)) - 1L
        self.check_overflow(lower, upper) 
Example 75
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_overflow(self):
        a = array.array(self.typecode)
        lower = 0
        upper = long(pow(2, a.itemsize * 8)) - 1L
        self.check_overflow(lower, upper) 
Example 76
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_sizeof_with_buffer(self):
        a = array.array(self.typecode, self.example)
        basesize = test_support.calcvobjsize('4P')
        buffer_size = a.buffer_info()[1] * a.itemsize
        test_support.check_sizeof(self, a, basesize + buffer_size) 
Example 77
Project: UrsaRobotics_SmartHome   Author: stav98   File: bme280.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self,
                 mode=BME280_OSAMPLE_1,
                 address=BME280_I2CADDR,
                 i2c=None,
                 **kwargs):
        # Check that mode is valid.
        if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                        BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
                'BME280_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        self.address = address
        if i2c is None:
            raise ValueError('An I2C object is required.')
        self.i2c = i2c

        # load calibration data
        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
            _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]

        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array("i", [0, 0, 0]) 
Example 78
Project: UrsaRobotics_SmartHome   Author: stav98   File: bme280.py    GNU General Public License v3.0 4 votes vote down vote up
def read_compensated_data(self, result=None):
        """ Reads the data from the sensor and returns the compensated data.

            Args:
                result: array of length 3 or alike where the result will be
                stored, in temperature, pressure, humidity order. You may use
                this to read out the sensor without allocating heap memory

            Returns:
                array with temperature, pressure, humidity. Will be the one from
                the result parameter if not None
        """
        self.read_raw_data(self._l3_resultarray)
        raw_temp, raw_press, raw_hum = self._l3_resultarray
        # temperature
        var1 = ((raw_temp >> 3) - (self.dig_T1 << 1)) * (self.dig_T2 >> 11)
        var2 = (((((raw_temp >> 4) - self.dig_T1) *
                  ((raw_temp >> 4) - self.dig_T1)) >> 12) * self.dig_T3) >> 14
        self.t_fine = var1 + var2
        temp = (self.t_fine * 5 + 128) >> 8

        # pressure
        var1 = self.t_fine - 128000
        var2 = var1 * var1 * self.dig_P6
        var2 = var2 + ((var1 * self.dig_P5) << 17)
        var2 = var2 + (self.dig_P4 << 35)
        var1 = (((var1 * var1 * self.dig_P3) >> 8) +
                ((var1 * self.dig_P2) << 12))
        var1 = (((1 << 47) + var1) * self.dig_P1) >> 33
        if var1 == 0:
            pressure = 0
        else:
            p = 1048576 - raw_press
            p = (((p << 31) - var2) * 3125) // var1
            var1 = (self.dig_P9 * (p >> 13) * (p >> 13)) >> 25
            var2 = (self.dig_P8 * p) >> 19
            pressure = ((p + var1 + var2) >> 8) + (self.dig_P7 << 4)

        # humidity
        h = self.t_fine - 76800
        h = (((((raw_hum << 14) - (self.dig_H4 << 20) -
                (self.dig_H5 * h)) + 16384)
              >> 15) * (((((((h * self.dig_H6) >> 10) *
                            (((h * self.dig_H3) >> 11) + 32768)) >> 10) +
                          2097152) * self.dig_H2 + 8192) >> 14))
        h = h - (((((h >> 15) * (h >> 15)) >> 7) * self.dig_H1) >> 4)
        h = 0 if h < 0 else h
        h = 419430400 if h > 419430400 else h
        humidity = h >> 12

        if result:
            result[0] = temp
            result[1] = pressure
            result[2] = humidity
            return result

        return array("i", (temp, pressure, humidity)) 
Example 79
Project: pyblish-win   Author: pyblish   File: test_types.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_buffers(self):
        self.assertRaises(ValueError, buffer, 'asdf', -1)
        cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1

        self.assertRaises(TypeError, buffer, None)

        a = buffer('asdf')
        hash(a)
        b = a * 5
        if a == b:
            self.fail('buffers should not be equal')
        if str(b) != ('asdf' * 5):
            self.fail('repeated buffer has wrong content')
        if str(a * 0) != '':
            self.fail('repeated buffer zero times has wrong content')
        if str(a + buffer('def')) != 'asdfdef':
            self.fail('concatenation of buffers yields wrong content')
        if str(buffer(a)) != 'asdf':
            self.fail('composing buffers failed')
        if str(buffer(a, 2)) != 'df':
            self.fail('specifying buffer offset failed')
        if str(buffer(a, 0, 2)) != 'as':
            self.fail('specifying buffer size failed')
        if str(buffer(a, 1, 2)) != 'sd':
            self.fail('specifying buffer offset and size failed')
        self.assertRaises(ValueError, buffer, buffer('asdf', 1), -1)
        if str(buffer(buffer('asdf', 0, 2), 0)) != 'as':
            self.fail('composing length-specified buffer failed')
        if str(buffer(buffer('asdf', 0, 2), 0, 5000)) != 'as':
            self.fail('composing length-specified buffer failed')
        if str(buffer(buffer('asdf', 0, 2), 0, -1)) != 'as':
            self.fail('composing length-specified buffer failed')
        if str(buffer(buffer('asdf', 0, 2), 1, 2)) != 's':
            self.fail('composing length-specified buffer failed')

        try: a[1] = 'g'
        except TypeError: pass
        else: self.fail("buffer assignment should raise TypeError")

        try: a[0:1] = 'g'
        except TypeError: pass
        else: self.fail("buffer slice assignment should raise TypeError")

        # array.array() returns an object that does not implement a char buffer,
        # something which int() uses for conversion.
        import array
        try: int(buffer(array.array('c')))
        except TypeError: pass
        else: self.fail("char buffer (at C level) not working") 
Example 80
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_getslice(self):
        a = array.array(self.typecode, self.example)
        self.assertEqual(a[:], a)

        self.assertEqual(
            a[1:],
            array.array(self.typecode, self.example[1:])
        )

        self.assertEqual(
            a[:1],
            array.array(self.typecode, self.example[:1])
        )

        self.assertEqual(
            a[:-1],
            array.array(self.typecode, self.example[:-1])
        )

        self.assertEqual(
            a[-1:],
            array.array(self.typecode, self.example[-1:])
        )

        self.assertEqual(
            a[-1:-1],
            array.array(self.typecode)
        )

        self.assertEqual(
            a[2:1],
            array.array(self.typecode)
        )

        self.assertEqual(
            a[1000:],
            array.array(self.typecode)
        )
        self.assertEqual(a[-1000:], a)
        self.assertEqual(a[:1000], a)
        self.assertEqual(
            a[:-1000],
            array.array(self.typecode)
        )
        self.assertEqual(a[-1000:1000], a)
        self.assertEqual(
            a[2000:1000],
            array.array(self.typecode)
        )