Python System.Array.CreateInstance() Examples

The following are 16 code examples of System.Array.CreateInstance(). 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.Array , 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: mesh.py    From dhitools with MIT License 6 votes vote down vote up
def _dfsu_element_coordinates(dfsu_object):
    """ Use MIKE SDK method to calc element coords from dfsu_object """

    element_coordinates = np.zeros(shape=(dfsu_object.NumberOfElements, 3))

    # Convert nodes to .NET System double to input to method
    xtemp = Array.CreateInstance(System.Double, 0)
    ytemp = Array.CreateInstance(System.Double, 0)
    ztemp = Array.CreateInstance(System.Double, 0)

    # Get element coords
    elemts_temp = dfs.dfsu.DfsuUtil.CalculateElementCenterCoordinates(dfsu_object, xtemp, ytemp, ztemp)

    # Place in array; need to get from .NET Array to numpy array
    for n in range(3):
        ele_coords_temp = []
        for ele in elemts_temp[n+1]:
            ele_coords_temp.append(ele)
        element_coordinates[:, n] = ele_coords_temp

    return element_coordinates 
Example #3
Source File: __init__.py    From PyESAPI with MIT License 6 votes vote down vote up
def set_fluence_nparray(beam, shaped_fluence, beamlet_size_mm=2.5):
    """sets optimal fluence in beam given numpy array and beamlet size (asserts square fluence, and zero collimator rotation)."""
    # assumes all fluence is square with isocenter at center of image
    # TODO: implement functionality below to remove assertions
    assert beamlet_size_mm == 2.5, "beamlet sizes of other than 2.5 mm are not implemented"
    assert shaped_fluence.shape[0] == shaped_fluence.shape[1], "non-square fluence not implemented"
    assert beam.ControlPoints[0].CollimatorAngle == 0.0, "non-zero collimator angle not implemented"

    _buffer = Array.CreateInstance(System.Single, shaped_fluence.shape[0], shaped_fluence.shape[1])

    # note: the shape -1, then divide by 2.0 gives desired center of corner beamlet (half pixel shift)
    x_origin = - float(shaped_fluence.shape[0] - 1) * beamlet_size_mm / 2.0
    y_origin = + float(shaped_fluence.shape[1] - 1) * beamlet_size_mm / 2.0

    for i in range(shaped_fluence.shape[0]):
        for j in range(shaped_fluence.shape[1]):
            _buffer[i, j] = shaped_fluence[i, j]

    fluence = Fluence(_buffer, x_origin, y_origin)
    beam.SetOptimalFluence(fluence)


## where the magic happens ##

# add Lot accessors to objects with IEnumerable childeren 
Example #4
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_cp11971(self):
        import os
        old_syspath = [x for x in sys.path]
        try:
            sys.path.append(self.temporary_dir)
            
            #Module using System
            self.write_to_file(os.path.join(self.temporary_dir, "cp11971_module.py"), 
                      """def a():
    from System import Array
    return Array.CreateInstance(int, 2, 2)""")

            #Module which doesn't use System directly
            self.write_to_file(os.path.join(self.temporary_dir, "cp11971_caller.py"), 
                      """import cp11971_module
A = cp11971_module.a()
if not hasattr(A, 'Rank'):
    raise 'CodePlex 11971'
    """)
    
            #Validations
            import cp11971_caller
            self.assertTrue(hasattr(cp11971_caller.A, 'Rank'))
            self.assertTrue(hasattr(cp11971_caller.cp11971_module.a(), 'Rank'))
        
        finally:
            sys.path = old_syspath 
Example #5
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_struct_assign(self):
        from IronPythonTest.BinderTest import ValueTypeWithFields
        from System import Array

        def noWarnMethod():
            arr = Array.CreateInstance(ValueTypeWithFields, 10)
            ValueTypeWithFields.X.SetValue(arr[0], 42)

        def warnMethod():
            arr = Array.CreateInstance(ValueTypeWithFields, 10)
            arr[0].X = 42

        self.assertNotWarns(RuntimeWarning, noWarnMethod)
        self.assertWarns(RuntimeWarning, warnMethod) 
Example #6
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 #7
Source File: test_cliclass.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp11971(self):
        import os
        old_syspath = [x for x in sys.path]
        try:
            sys.path.append(self.temporary_dir)
            
            #Module using System
            self.write_to_file(os.path.join(self.temporary_dir, "cp11971_module.py"), 
                      """def a():
    from System import Array
    return Array.CreateInstance(int, 2, 2)""")

            #Module which doesn't use System directly
            self.write_to_file(os.path.join(self.temporary_dir, "cp11971_caller.py"), 
                      """import cp11971_module
A = cp11971_module.a()
if not hasattr(A, 'Rank'):
    raise 'CodePlex 11971'
    """)
    
            #Validations
            import cp11971_caller
            self.assertTrue(hasattr(cp11971_caller.A, 'Rank'))
            self.assertTrue(hasattr(cp11971_caller.cp11971_module.a(), 'Rank'))
        
        finally:
            sys.path = old_syspath 
Example #8
Source File: test_cliclass.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_struct_assign(self):
        from IronPythonTest.BinderTest import ValueTypeWithFields
        from System import Array

        def noWarnMethod():
            arr = Array.CreateInstance(ValueTypeWithFields, 10)
            ValueTypeWithFields.X.SetValue(arr[0], 42)

        def warnMethod():
            arr = Array.CreateInstance(ValueTypeWithFields, 10)
            arr[0].X = 42

        self.assertNotWarns(RuntimeWarning, noWarnMethod)
        self.assertWarns(RuntimeWarning, warnMethod) 
Example #9
Source File: __init__.py    From PyESAPI with MIT License 5 votes vote down vote up
def image_to_nparray(image_like):
    '''returns a 3D numpy.ndarray of floats indexed like [x,y,z]'''
    _shape = (image_like.XSize, image_like.YSize, image_like.ZSize)
    _array = np.zeros(_shape)

    _buffer = Array.CreateInstance(Int32, image_like.XSize, image_like.YSize)
    for z in range(image_like.ZSize):
        image_like.GetVoxels(z, _buffer)
        _array[:, :, z] = to_ndarray(_buffer, dtype=c_int32).reshape((image_like.XSize, image_like.YSize))

    return _array 
Example #10
Source File: __init__.py    From PyESAPI with MIT License 5 votes vote down vote up
def make_segment_mask_for_structure(dose_or_image, structure):
    '''returns a 3D numpy.ndarray of bools matching dose or image grid indexed like [x,y,z]'''
    if (structure.HasSegment):
        pre_buffer = System.Collections.BitArray(dose_or_image.ZSize)
        row_buffer = Array.CreateInstance(bool, dose_or_image.ZSize)

        return fill_in_profiles(dose_or_image, structure.GetSegmentProfile, row_buffer, c_bool, pre_buffer)
    else:
        raise Exception("structure has no segment data") 
Example #11
Source File: __init__.py    From PyESAPI with MIT License 5 votes vote down vote up
def make_dose_for_grid(dose, image=None):
    '''returns a 3D numpy.ndarray of doubles matching dose (default) or image grid indexed like [x,y,z]'''

    if image is not None:
        row_buffer = Array.CreateInstance(Double, image.ZSize)
        dose_array = fill_in_profiles(image, dose.GetDoseProfile, row_buffer, c_double)
    else:
        # default
        dose_array = dose_to_nparray(dose)

    dose_array[np.where(np.isnan(dose_array))] = 0.0
    return dose_array 
Example #12
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 #13
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 #14
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 #15
Source File: drawing.py    From compas with MIT License 5 votes vote down vote up
def draw_mesh(vertices, faces, color=None, vertex_normals=None, texture_coordinates=None):
    """Draw mesh in Grasshopper.
    """
    mesh = Mesh()
    for a, b, c in vertices:
        mesh.Vertices.Add(a, b, c)
    for face in faces:
        if len(face) < 4:
            mesh.Faces.AddFace(face[0], face[1], face[2])
        else:
            mesh.Faces.AddFace(face[0], face[1], face[2], face[3])

    if vertex_normals:
        count = len(vertex_normals)
        normals = CreateInstance(Vector3f, count)
        for i, normal in enumerate(vertex_normals):
            normals[i] = Vector3f(normal[0], normal[1], normal[2])
        mesh.Normals.SetNormals(normals)

    if texture_coordinates:
        count = len(texture_coordinates)
        tcs = CreateInstance(Point2f, count)
        for i, tc in enumerate(texture_coordinates):
            tcs[i] = Point2f(tc[0], tc[1])
        mesh.TextureCoordinates.SetTextureCoordinates(tcs)

    if color:
        count = len(vertices)
        colors = CreateInstance(Color, count)
        for i in range(count):
            colors[i] = rs.coercecolor(color)
        mesh.VertexColors.SetColors(colors)

    return mesh 
Example #16
Source File: client.py    From bleak with MIT License 4 votes vote down vote up
def read_gatt_descriptor(
        self, handle: int, use_cached=False, **kwargs
    ) -> bytearray:
        """Perform read operation on the specified GATT descriptor.

        Args:
            handle (int): The handle of the descriptor to read from.
            use_cached (bool): `False` forces Windows to read the value from the
                device again and not use its own cached value. Defaults to `False`.

        Returns:
            (bytearray) The read data.

        """
        descriptor = self.services.get_descriptor(handle)
        if not descriptor:
            raise BleakError("Descriptor with handle {0} was not found!".format(handle))

        read_result = await wrap_IAsyncOperation(
            IAsyncOperation[GattReadResult](
                descriptor.obj.ReadValueAsync(
                    BluetoothCacheMode.Cached
                    if use_cached
                    else BluetoothCacheMode.Uncached
                )
            ),
            return_type=GattReadResult,
            loop=self.loop,
        )
        if read_result.Status == GattCommunicationStatus.Success:
            reader = DataReader.FromBuffer(IBuffer(read_result.Value))
            output = Array.CreateInstance(Byte, reader.UnconsumedBufferLength)
            reader.ReadBytes(output)
            value = bytearray(output)
            logger.debug("Read Descriptor {0} : {1}".format(handle, value))
        else:
            if read_result.Status == GattCommunicationStatus.ProtocolError:
                raise BleakDotNetTaskError(
                    "Could not get GATT characteristics for {0}: {1} (Error: 0x{2:02X})".format(
                        descriptor.uuid,
                        _communication_statues.get(read_result.Status, ""),
                        read_result.ProtocolError,
                    )
                )
            else:
                raise BleakError(
                    "Could not read Descriptor value for {0}: {1}".format(
                        descriptor.uuid,
                        _communication_statues.get(read_result.Status, ""),
                    )
                )

        return value