当前位置: 首页>>代码示例>>Python>>正文


Python Array.CreateInstance方法代码示例

本文整理汇总了Python中System.Array.CreateInstance方法的典型用法代码示例。如果您正苦于以下问题:Python Array.CreateInstance方法的具体用法?Python Array.CreateInstance怎么用?Python Array.CreateInstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Array的用法示例。


在下文中一共展示了Array.CreateInstance方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: parse_eventargs

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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
        ) 
开发者ID:hbldh,项目名称:bleak,代码行数:18,代码来源:scanner.py

示例2: _dfsu_element_coordinates

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:robjameswall,项目名称:dhitools,代码行数:23,代码来源:mesh.py

示例3: set_fluence_nparray

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:VarianAPIs,项目名称:PyESAPI,代码行数:27,代码来源:__init__.py

示例4: test_cp11971

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:29,代码来源:test_cliclass.py

示例5: test_struct_assign

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:16,代码来源:test_cliclass.py

示例6: _notification_wrapper

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:hbldh,项目名称:bleak,代码行数:16,代码来源:client.py

示例7: image_to_nparray

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:VarianAPIs,项目名称:PyESAPI,代码行数:13,代码来源:__init__.py

示例8: make_segment_mask_for_structure

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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") 
开发者ID:VarianAPIs,项目名称:PyESAPI,代码行数:11,代码来源:__init__.py

示例9: make_dose_for_grid

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:VarianAPIs,项目名称:PyESAPI,代码行数:14,代码来源:__init__.py

示例10: _string_to_bytearr

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:linuxerwang,项目名称:pdf-quench,代码行数:7,代码来源:filters.py

示例11: _read_bytes

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:linuxerwang,项目名称:pdf-quench,代码行数:14,代码来源:filters.py

示例12: start_listening

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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') 
开发者ID:gramaziokohler,项目名称:roslibpy,代码行数:39,代码来源:comm_cli.py

示例13: draw_mesh

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:compas-dev,项目名称:compas,代码行数:36,代码来源:drawing.py

示例14: read_gatt_descriptor

# 需要导入模块: from System import Array [as 别名]
# 或者: from System.Array import CreateInstance [as 别名]
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 
开发者ID:hbldh,项目名称:bleak,代码行数:55,代码来源:client.py


注:本文中的System.Array.CreateInstance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。