Python System.Byte() Examples

The following are 30 code examples of System.Byte(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module System , or try the search function .
Example #1
Source File: scanner.py    From bleak with MIT License 6 votes vote down vote up
def parse_eventargs(event_args):
        bdaddr = _format_bdaddr(event_args.BluetoothAddress)
        uuids = []
        for u in event_args.Advertisement.ServiceUuids:
            uuids.append(u.ToString())
        data = {}
        for m in event_args.Advertisement.ManufacturerData:
            md = IBuffer(m.Data)
            b = Array.CreateInstance(Byte, md.Length)
            reader = DataReader.FromBuffer(md)
            reader.ReadBytes(b)
            data[m.CompanyId] = bytes(b)
        local_name = event_args.Advertisement.LocalName
        return BLEDevice(
            bdaddr, local_name, event_args, uuids=uuids, manufacturer_data=data
        ) 
Example #2
Source File: test_math.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_byte(self):
        a = Byte()
        self.assertEqual(type(a), Byte)
        self.assertEqual(a, 0)

        b = a + Byte(1)
        self.assertEqual(b, 1)
        self.assertEqual(type(b), Byte)

        bprime = b * Byte(10)
        self.assertEqual(type(bprime), Byte)

        d = a + Byte(255)
        self.assertEqual(type(d), Byte)

        c = b + Byte(255)
        self.assertEqual(c, 256)
        self.assertEqual(type(c), Int16) 
Example #3
Source File: test_math.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_byte(self):
        a = Byte()
        self.assertEqual(type(a), Byte)
        self.assertEqual(a, 0)

        b = a + Byte(1)
        self.assertEqual(b, 1)
        self.assertEqual(type(b), Byte)

        bprime = b * Byte(10)
        self.assertEqual(type(bprime), Byte)

        d = a + Byte(255)
        self.assertEqual(type(d), Byte)

        c = b + Byte(255)
        self.assertEqual(c, 256)
        self.assertEqual(type(c), Int16) 
Example #4
Source File: test_numtypes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def validate_constructors(self, values):
        types = [Byte, UInt16, UInt32, UInt64, SByte, Int16, Int32, Int64]
        total = 0
        for value in values:
            for first in types:
                v1 = first(value)
                for second in types:
                    v2 = first(second((value)))
                total += 1
        return total 
Example #5
Source File: test_methoddispatch.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_io_memorystream(self):
        import System
        s = System.IO.MemoryStream()
        a = System.Array.CreateInstance(System.Byte, 10)
        b = System.Array.CreateInstance(System.Byte, a.Length)
        for i in range(a.Length):
            a[i] = a.Length - i
        s.Write(a, 0, a.Length)
        result = s.Seek(0, System.IO.SeekOrigin.Begin)
        r = s.Read(b, 0, b.Length)
        self.assertTrue(r == b.Length)
        for i in range(a.Length):
            self.assertEqual(a[i], b[i]) 
Example #6
Source File: test_methoddispatch.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_array_error_message(self):
        import System
        from IronPythonTest import BinderTest
        
        x = BinderTest.CNoOverloads()
        self.assertRaisesMessage(TypeError, 'expected Array[int], got Array[Byte]', x.M500, System.Array[System.Byte]([1,2,3])) 
Example #7
Source File: test_methodbinder1.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_bool_asked(self):
        """check the bool conversion result"""
        import System
        from IronPythonTest.BinderTest import Flag

        for arg in ['a', 3, object(), True]:
            self.target.M204(arg)
            self.assertTrue(Flag.BValue, "argument is %s" % arg)
            Flag.BValue = False
            
        for arg in [0, System.Byte.Parse('0'), System.UInt64.Parse('0'), 0.0, 0, False, None, tuple(), list()]:
            self.target.M204(arg)
            self.assertTrue(not Flag.BValue, "argument is %s" % (arg,))
            Flag.BValue = True 
Example #8
Source File: test_methodbinder1.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_out_int(self):
        self._helper(self.target.M701, [], 701, [1, 10, None, System.Byte.Parse('3')], TypeError)    # not allow to pass in anything 
Example #9
Source File: test_methodbinder1.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_ref_bytearr(self):
        from IronPythonTest.BinderTest import COtherConcern, Flag
        import clr
        self.target = COtherConcern()
        
        arr = System.Array[System.Byte]((2,3,4))
        
        res = self.target.M702(arr)
        self.assertEqual(Flag.Value, 702)
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        i, res = self.target.M703(arr)
        self.assertEqual(Flag.Value, 703)
        self.assertEqual(i, 42)
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        i, res = self.target.M704(arr, arr)
        self.assertEqual(Flag.Value, 704)
        self.assertEqual(i, 42)
        self.assertEqual(arr, res)
        
        sarr = clr.StrongBox[System.Array[System.Byte]](arr)
        res = self.target.M702(sarr)
        self.assertEqual(Flag.Value, 702)
        self.assertEqual(res, None)
        res = sarr.Value
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        sarr.Value = arr
        i = self.target.M703(sarr)
        self.assertEqual(Flag.Value, 703)
        self.assertEqual(i, 42)
        self.assertEqual(len(sarr.Value), 0)
        
        i = self.target.M704(arr, sarr)
        self.assertEqual(Flag.Value, 704)
        self.assertEqual(i, 42)
        self.assertEqual(sarr.Value, arr) 
Example #10
Source File: test_stdmodules.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp13401(self):
        import System
        import copy
        
        #A few special cases
        StringSplitOptions_None = getattr(System.StringSplitOptions, "None")
        self.assertEqual(System.Char.MinValue, copy.copy(System.Char.MinValue))
        self.assertTrue(System.Char.MinValue != copy.copy(System.Char.MaxValue))
        self.assertEqual(StringSplitOptions_None, copy.copy(StringSplitOptions_None))
        self.assertEqual(System.StringSplitOptions.RemoveEmptyEntries, copy.copy(System.StringSplitOptions.RemoveEmptyEntries))
        self.assertTrue(StringSplitOptions_None != copy.copy(System.StringSplitOptions.RemoveEmptyEntries))
        
        #Normal cases
        test_dict = {   System.Byte : [System.Byte.MinValue, System.Byte.MinValue+1, System.Byte.MaxValue, System.Byte.MaxValue-1],
                        System.Char : [],
                        System.Boolean : [True, False],
                        System.SByte   : [System.SByte.MinValue, System.SByte.MinValue+1, System.SByte.MaxValue, System.SByte.MaxValue-1],
                        System.UInt32  : [System.UInt32.MinValue, System.UInt32.MinValue+1, System.UInt32.MaxValue, System.UInt32.MaxValue-1],
                        System.Int64   : [System.Int64.MinValue, System.Int64.MinValue+1, System.Int64.MaxValue, System.Int64.MaxValue-1],
                        System.Double  : [0.00, 3.14],
                        }
        
        for key in test_dict.keys():
            temp_type = key
            self.assertTrue(hasattr(temp_type, "__reduce_ex__"), 
                "%s has no attribute '%s'" % (str(temp_type), "__reduce_ex__"))
        
            for temp_value in test_dict[key]:
                x = temp_type(temp_value)
                x_copy = copy.copy(x)
                self.assertEqual(x, x_copy)
                self.assertEqual(x, temp_value) 
Example #11
Source File: test_bytes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_init_interop(self):
        import clr
        clr.AddReference("System.Memory")
        from System import Byte, Array, ArraySegment, ReadOnlyMemory, Memory

        arr = Array[Byte](b"abc")
        ars = ArraySegment[Byte](arr)
        rom = ReadOnlyMemory[Byte](arr)
        mem = Memory[Byte](arr)

        for testType in types:
            self.assertEqual(testType(arr), b"abc")
            self.assertEqual(testType(ars), b"abc")
            self.assertEqual(testType(rom), b"abc")
            self.assertEqual(testType(mem), b"abc") 
Example #12
Source File: common.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def transform(x):
        x = _common_transform(x)
        if isinstance(x, type) and (x == Byte or x == Int64):
            return int
        return x 
Example #13
Source File: test_file.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp27179(self):
        # file.write() accepting Array[Byte]
        from System import Array, Byte
        data_string = 'abcdef\nghijkl\n\n'
        data = Array[Byte](list(map(Byte, list(map(ord, data_string)))))

        with open(self.temp_file, 'w+') as f:
            f.write(data)

        with open(self.temp_file, 'r') as f:
            data_read = f.read()

        self.assertEqual(data_string, data_read)

    # Helper used to format newline characters into a visible format. 
Example #14
Source File: test_numtypes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def get_values(values, itypes, ftypes):
    """
    This will return structure of values converted to variety of types as a list of tuples:
    [ ...
    ( python_value, [ all_values ] ),
    ... ]

    all_values: Byte, UInt16, UInt32, UInt64, SByte, Int16, Int32, Int64, Single, Double, myint, mylong, myfloat
    """
    all = []
    for v in values:
        sv  = str(v)
        py  = int(v)
        clr = get_clr_values(sv, itypes)
        clr.append(long(py))
        clr.append(myint(py))
        clr.append(mylong(py))
        all.append( (py, clr) )

        py  = long(v)
        clr = get_clr_values(sv, itypes)
        clr.append(py)
        clr.append(myint(py))
        clr.append(mylong(py))
        all.append( (py, clr) )

        py  = float(v)
        clr = get_clr_values(sv, ftypes)
        clr.append(myfloat(py))
        all.append( (py, clr) )

        for imag in [0j, 1j, -1j]:
            py = complex(v + imag)
            all.append( (py, [ py, mycomplex(py) ] ) )

    all.append( (True, [ True ] ))
    all.append( (False, [ False ] ))

    return all 
Example #15
Source File: test_methoddispatch.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_io_memorystream(self):
        import System
        s = System.IO.MemoryStream()
        a = System.Array.CreateInstance(System.Byte, 10)
        b = System.Array.CreateInstance(System.Byte, a.Length)
        for i in range(a.Length):
            a[i] = a.Length - i
        s.Write(a, 0, a.Length)
        result = s.Seek(0, System.IO.SeekOrigin.Begin)
        r = s.Read(b, 0, b.Length)
        self.assertTrue(r == b.Length)
        for i in range(a.Length):
            self.assertEqual(a[i], b[i]) 
Example #16
Source File: test_instance_fields.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _test_delete_by_descriptor(self, current_type):
        for x in [
            'Byte',
            'SByte',
            'UInt16',
            'Int16',
            'UInt32',
            'Int32',
            'UInt64',
            'Int64',
            'Double',
            'Single',
            'Decimal',
            'Char',
            'Boolean',
            'String',
            'Object',
            'Enum',
            'DateTime',
            'SimpleStruct',
            'SimpleGenericStruct',
            'NullableStructNotNull',
            'NullableStructNull',
            'SimpleClass',
            'SimpleGenericClass',
            'SimpleInterface',
        ]:
            for o in [None, current_type, current_type()]:
                self.assertRaisesRegex(AttributeError, "cannot delete attribute", lambda: current_type.__dict__['Instance%sField' % x].__delete__(o)) 
Example #17
Source File: test_instance_fields.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_nested(self):
        import System
        from Merlin.Testing.FieldTest import Class2, GenericClass2
        for ct in [ Class2, GenericClass2[System.Byte], GenericClass2[object] ]:
            c = ct()
            self.assertEqual(c.InstanceNextField, None)
            c.InstanceNextField = ct()
            
            self.assertEqual(c.InstanceNextField.InstanceNextField, None)
            c.InstanceNextField.InstanceField = 20
            self.assertEqual(c.InstanceNextField.InstanceField, 20) 
Example #18
Source File: test_static_fields.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_nested(self):
        import System
        from Merlin.Testing.FieldTest import Class2, GenericClass2, GenericStruct2, Struct2
        for s in [ Struct2, GenericStruct2[int], GenericStruct2[str] ]:
            self.assertEqual(s.StaticNextField.StaticNextField.StaticNextField.StaticField, 10)
            s.StaticNextField.StaticNextField.StaticNextField.StaticField = -10
            self.assertEqual(s.StaticNextField.StaticNextField.StaticNextField.StaticField, -10)        

        for c in [ Class2, GenericClass2[System.Byte], GenericClass2[object] ]:
            self.assertEqual(c.StaticNextField, None)
            c.StaticNextField = c()
            self.assertEqual(c.StaticNextField.StaticNextField.StaticNextField.StaticField, 10)
            c.StaticNextField.StaticNextField.StaticNextField.StaticField = 20
            self.assertEqual(c.StaticField, 20) 
Example #19
Source File: test_ironmath.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_big_1(self):
        from System import SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64
        from System.Numerics import BigInteger
        for (a, m, t,x) in [
                            (7, "ToSByte",  SByte,2),
                            (8, "ToByte",   Byte, 0),
                            (15, "ToInt16", Int16,2),
                            (16, "ToUInt16", UInt16,0),
                            (31, "ToInt32", Int32,2),
                            (32, "ToUInt32", UInt32,0),
                            (63, "ToInt64", Int64,2),
                            (64, "ToUInt64", UInt64,0)
                        ]:

            b = BigInteger(-x ** a )
            left = getattr(b, m)(self.p)
            right = t.MinValue
            self.assertEqual(left, right)

            b = BigInteger(2 ** a -1)
            left = getattr(b, m)(self.p)
            right = t.MaxValue
            self.assertEqual(left, right)

            b = BigInteger(long(0))
            left = getattr(b, m)(self.p)
            right = t.MaxValue - t.MaxValue
            self.assertEqual(left, 0)

            self.assertRaises(OverflowError,getattr(BigInteger(2 ** a ), m),self.p)
            self.assertRaises(OverflowError,getattr(BigInteger(-1 - x ** a ), m),self.p) 
Example #20
Source File: test_ironmath.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_byte_conversions(self):
        from System import Array, Byte
        from System.Numerics import BigInteger

        def CheckByteConversions(bigint, bytes):
            self.assertSequenceEqual(bigint.ToByteArray(), bytes)
            self.assertEqual(BigInteger.Create(Array[Byte](bytes)), bigint)

        CheckByteConversions(BigInteger(0x00), [0x00])

        CheckByteConversions(BigInteger(-0x01), [0xff])
        CheckByteConversions(BigInteger(-0x81), [0x7f, 0xff])
        CheckByteConversions(BigInteger(-0x100), [0x00, 0xff])
        CheckByteConversions(BigInteger(-0x1000), [0x00, 0xf0])
        CheckByteConversions(BigInteger(-0x10000), [0x00, 0x00, 0xff])
        CheckByteConversions(BigInteger(-0x100000), [0x00, 0x00, 0xf0])
        CheckByteConversions(BigInteger(-0x10000000), [0x00, 0x00, 0x00, 0xf0])
        CheckByteConversions(BigInteger(-0x100000000), [0x00, 0x00, 0x00, 0x00, 0xff])

        CheckByteConversions(BigInteger(0x7f), [0x7f])
        CheckByteConversions(BigInteger(0xff), [0xff, 0x00])
        CheckByteConversions(BigInteger(0x0201), [0x01, 0x02])
        CheckByteConversions(BigInteger(0xf2f1), [0xf1, 0xf2, 0x00])
        CheckByteConversions(BigInteger(0x03020100), [0x00, 0x01, 0x02, 0x03])
        CheckByteConversions(BigInteger(0x0403020100), [0x00, 0x01, 0x02, 0x03, 0x04])
        CheckByteConversions(BigInteger(0x0706050403020100), [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
        CheckByteConversions(BigInteger(0x080706050403020100), [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) 
Example #21
Source File: filters.py    From pdf-quench with GNU General Public License v2.0 5 votes vote down vote up
def _string_to_bytearr(buf):
        retval = Array.CreateInstance(System.Byte, len(buf))
        for i in range(len(buf)):
            retval[i] = ord(buf[i])
        return retval 
Example #22
Source File: filters.py    From pdf-quench with GNU General Public License v2.0 5 votes vote down vote up
def _read_bytes(stream):
        ms = IO.MemoryStream()
        buf = Array.CreateInstance(System.Byte, 2048)
        while True:
            bytes = stream.Read(buf, 0, buf.Length)
            if bytes == 0:
                break
            else:
                ms.Write(buf, 0, bytes)
        retval = ms.ToArray()
        ms.Close()
        return retval 
Example #23
Source File: comm_cli.py    From roslibpy with MIT License 5 votes vote down vote up
def start_listening(self):
        """Starts listening asynchronously while the socket is open.

        The inter-thread synchronization between this and the async
        reception threads is sync'd with a manual reset event."""
        try:
            LOGGER.debug(
                'About to start listening, socket state: %s', self.socket.State)

            while self.socket and self.socket.State == WebSocketState.Open:
                mre = ManualResetEventSlim(False)
                content = []
                buffer = Array.CreateInstance(Byte, RECEIVE_CHUNK_SIZE)

                self.receive_chunk_async(None, dict(
                    buffer=buffer, content=content, mre=mre))

                LOGGER.debug('Waiting for messages...')
                try:
                    mre.Wait(self.factory.manager.cancellation_token)
                except SystemError:
                    LOGGER.debug('Cancellation detected on listening thread, exiting...')
                    break

                try:
                    message_payload = ''.join(content)
                    LOGGER.debug('Message reception completed|<pre>%s</pre>', message_payload)
                    self.on_message(message_payload)
                except Exception:
                    LOGGER.exception('Exception on start_listening while trying to handle message received.' +
                                     'It could indicate a bug in user code on message handlers. Message skipped.')
        except Exception:
            LOGGER.exception(
                'Exception on start_listening, processing will be aborted')
            raise
        finally:
            LOGGER.debug('Leaving the listening thread') 
Example #24
Source File: comm_cli.py    From roslibpy with MIT License 5 votes vote down vote up
def send_chunk_async(self, task, message_data):
        """Send a message chuck asynchronously."""
        try:
            if not task:
                self.semaphore.Wait(self.factory.manager.cancellation_token)

            message_buffer, message_length, chunks_count, i = message_data

            offset = SEND_CHUNK_SIZE * i
            is_last_message = (i == chunks_count - 1)

            if is_last_message:
                count = message_length - offset
            else:
                count = SEND_CHUNK_SIZE

            message_chunk = ArraySegment[Byte](message_buffer, offset, count)
            LOGGER.debug('Chunk %d of %d|From offset=%d, byte count=%d, Is last=%s',
                         i + 1, chunks_count, offset, count, str(is_last_message))
            task = self.socket.SendAsync(
                message_chunk, WebSocketMessageType.Text, is_last_message, self.factory.manager.cancellation_token)

            if not is_last_message:
                task.ContinueWith(self.send_chunk_async, [
                    message_buffer, message_length, chunks_count, i + 1])
            else:
                # NOTE: If we've reached the last chunk of the message
                # we can release the lock (Semaphore) again.
                task.ContinueWith(lambda _res: self.semaphore.Release())

            return task
        except Exception:
            LOGGER.exception('Exception while on send_chunk_async')
            raise 
Example #25
Source File: pack_util.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def IntsToBase64(ints):
    return System.Convert.ToBase64String([System.Byte(i) for i in ints].ToArray[System.Byte]()) 
Example #26
Source File: client.py    From bleak with MIT License 5 votes vote down vote up
def _notification_wrapper(loop: AbstractEventLoop, func: Callable):
    @wraps(func)
    def dotnet_notification_parser(sender: Any, args: Any):
        # Return only the UUID string representation as sender.
        # Also do a conversion from System.Bytes[] to bytearray.
        reader = DataReader.FromBuffer(args.CharacteristicValue)
        output = Array.CreateInstance(Byte, reader.UnconsumedBufferLength)
        reader.ReadBytes(output)

        return loop.call_soon_threadsafe(
            func, sender.Uuid.ToString(), bytearray(output)
        )

    return dotnet_notification_parser 
Example #27
Source File: test_methoddispatch.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_array_error_message(self):
        import System
        from IronPythonTest import BinderTest
        
        x = BinderTest.CNoOverloads()
        self.assertRaisesMessage(TypeError, 'expected Array[int], got Array[Byte]', x.M500, System.Array[System.Byte]([1,2,3])) 
Example #28
Source File: test_methodbinder1.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_bool_asked(self):
        """check the bool conversion result"""
        import System
        from IronPythonTest.BinderTest import Flag

        for arg in ['a', 3, object(), True]:
            self.target.M204(arg)
            self.assertTrue(Flag.BValue, "argument is %s" % arg)
            Flag.BValue = False
            
        for arg in [0, System.Byte.Parse('0'), System.UInt64.Parse('0'), 0.0, 0L, False, None, tuple(), list()]:
            self.target.M204(arg)
            self.assertTrue(not Flag.BValue, "argument is %s" % (arg,))
            Flag.BValue = True 
Example #29
Source File: test_methodbinder1.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_out_int(self):
        self._helper(self.target.M701, [], 701, [1, 10L, None, System.Byte.Parse('3')], TypeError)    # not allow to pass in anything 
Example #30
Source File: test_methodbinder1.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ref_bytearr(self):
        from IronPythonTest.BinderTest import COtherConcern, Flag
        import clr
        self.target = COtherConcern()
        
        arr = System.Array[System.Byte]((2,3,4))
        
        res = self.target.M702(arr)
        self.assertEqual(Flag.Value, 702)
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        i, res = self.target.M703(arr)
        self.assertEqual(Flag.Value, 703)
        self.assertEqual(i, 42)
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        i, res = self.target.M704(arr, arr)
        self.assertEqual(Flag.Value, 704)
        self.assertEqual(i, 42)
        self.assertEqual(arr, res)
        
        sarr = clr.StrongBox[System.Array[System.Byte]](arr)
        res = self.target.M702(sarr)
        self.assertEqual(Flag.Value, 702)
        self.assertEqual(res, None)
        res = sarr.Value
        self.assertEqual(type(res), System.Array[System.Byte])
        self.assertEqual(len(res), 0)
        
        sarr.Value = arr
        i = self.target.M703(sarr)
        self.assertEqual(Flag.Value, 703)
        self.assertEqual(i, 42)
        self.assertEqual(len(sarr.Value), 0)
        
        i = self.target.M704(arr, sarr)
        self.assertEqual(Flag.Value, 704)
        self.assertEqual(i, 42)
        self.assertEqual(sarr.Value, arr)