Python System.Array() Examples

The following are 30 code examples of System.Array(). 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: test_method_signature.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_one_array(self):
        import System
        from Merlin.Testing.BaseClass import IInterface600
        f = IInterface600.m_c

        def checkEqual(first, second):
            self.assertEqual(first, second)
        
        class C(IInterface600):
            def m_c(self, arg):
                if arg:
                    checkEqual(sum(arg), expected)
                    arg[0] = 10

        x = C()
        a = System.Array[int]([1,2])
        expected = 3
        f(x, a)
        self.assertEqual(a[0], 10)
        
        f(x, None) 
Example #2
Source File: test_cliclass.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_interface_inheritance(self):
        """Verify we can inherit from a class that inherits from an interface"""

        class MyComparer(System.Collections.IComparer):
            def Compare(self, x, y): return 0
        
        class MyDerivedComparer(MyComparer): pass
        
        class MyFurtherDerivedComparer(MyDerivedComparer): pass

        # Check that MyDerivedComparer and MyFurtherDerivedComparer can be used as an IComparer
        array = System.Array[int](range(10))
        
        System.Array.Sort(array, 0, 10, MyComparer())
        System.Array.Sort(array, 0, 10, MyDerivedComparer())
        System.Array.Sort(array, 0, 10, MyFurtherDerivedComparer()) 
Example #3
Source File: test_isinstance.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_int_minvalue(self):
        # Test for type of System.Int32.MinValue
        self.assertEqual(type(-2147483648), int)
        self.assertEqual(type(-(2147483648)), long)
        self.assertEqual(type(-long(2147483648)), long)
        self.assertEqual(type(-0x80000000), int)

        self.assertEqual(type(int('-2147483648')), int)
        self.assertEqual(type(int('-80000000', 16)), int)
        self.assertEqual(type(int('-2147483649')), long)
        self.assertEqual(type(int('-80000001', 16)), long)


        if is_cli:
            import clr
            import System

            # verify our str.split doesn't replace CLR's String.Split
            chars = System.Array[str]([' '])
            res = 'a b  c'.Split(chars, System.StringSplitOptions.RemoveEmptyEntries)
            self.assertEqual(res[0], 'a')
            self.assertEqual(res[1], 'b')
            self.assertEqual(res[2], 'c') 
Example #4
Source File: test_reachtype.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_type_from_reflection_emit(self):
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Reflection.Emit")

        sr = System.Reflection
        sre = System.Reflection.Emit
        array = System.Array
        cab = array[sre.CustomAttributeBuilder]([sre.CustomAttributeBuilder(clr.GetClrType(System.Security.SecurityTransparentAttribute).GetConstructor(System.Type.EmptyTypes), array[object]([]))])
        if is_netcoreapp: # no System.AppDomain.DefineDynamicAssembly
            ab = sre.AssemblyBuilder.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.Run, cab)  # tracking: 291888
        else:
            ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.RunAndSave, "temp", None, None, None, None, True, cab)  # tracking: 291888

        mb = ab.DefineDynamicModule("temp", "temp.dll")
        tb = mb.DefineType("EmittedNS.EmittedType", sr.TypeAttributes.Public)
        tb.CreateType()

        clr.AddReference(ab)
        import EmittedNS
        EmittedNS.EmittedType() 
Example #5
Source File: test_exceptions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_str2(self):
        # verify we can assign to sys.exc_*
        sys.exc_traceback = None
        sys.exc_value = None
        sys.exc_type = None

        self.assertEqual(str(Exception()), '')


        @skipUnlessIronPython()
        def test_array(self):
            import System
            try:
                a = System.Array()
            except Exception, e:
                self.assertEqual(e.__class__, TypeError)
            else: 
Example #6
Source File: test_isinstance.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_int_minvalue(self):
        # Test for type of System.Int32.MinValue
        self.assertEqual(type(-2147483648), int)
        self.assertEqual(type(-(2147483648)), long)
        self.assertEqual(type(-2147483648L), long)
        self.assertEqual(type(-0x80000000), int)
        
        self.assertEqual(type(int('-2147483648')), int)
        self.assertEqual(type(int('-80000000', 16)), int)
        self.assertEqual(type(int('-2147483649')), long)
        self.assertEqual(type(int('-80000001', 16)), long)
        
        
        if is_cli:
            import clr
            import System
            
            # verify our str.split doesn't replace CLR's String.Split
            chars = System.Array[str]([' '])
            res = 'a b  c'.Split(chars, System.StringSplitOptions.RemoveEmptyEntries)
            self.assertEqual(res[0], 'a')
            self.assertEqual(res[1], 'b')
            self.assertEqual(res[2], 'c') 
Example #7
Source File: test_reachtype.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_type_from_reflection_emit(self):
        import clr
        import System
        if is_netcoreapp:
            clr.AddReference("System.Reflection.Emit")
        
        sr = System.Reflection
        sre = System.Reflection.Emit
        array = System.Array
        cab = array[sre.CustomAttributeBuilder]([sre.CustomAttributeBuilder(clr.GetClrType(System.Security.SecurityTransparentAttribute).GetConstructor(System.Type.EmptyTypes), array[object]([]))])
        if is_netcoreapp: # no System.AppDomain.DefineDynamicAssembly
            ab = sre.AssemblyBuilder.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.Run, cab)  # tracking: 291888
        else:
            ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(sr.AssemblyName("temp"), sre.AssemblyBuilderAccess.RunAndSave, "temp", None, None, None, None, True, cab)  # tracking: 291888

        mb = ab.DefineDynamicModule("temp", "temp.dll")
        tb = mb.DefineType("EmittedNS.EmittedType", sr.TypeAttributes.Public)
        tb.CreateType()
            
        clr.AddReference(ab)
        import EmittedNS
        EmittedNS.EmittedType() 
Example #8
Source File: test_cliclass.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_interface_inheritance(self):
        """Verify we can inherit from a class that inherits from an interface"""

        class MyComparer(System.Collections.IComparer):
            def Compare(self, x, y): return 0
        
        class MyDerivedComparer(MyComparer): pass
        
        class MyFurtherDerivedComparer(MyDerivedComparer): pass

        # Check that MyDerivedComparer and MyFurtherDerivedComparer can be used as an IComparer
        array = System.Array[int](list(range(10)))
        
        System.Array.Sort(array, 0, 10, MyComparer())
        System.Array.Sort(array, 0, 10, MyDerivedComparer())
        System.Array.Sort(array, 0, 10, MyFurtherDerivedComparer()) 
Example #9
Source File: test_simplederive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_system_type_cs0644(self):
        # http://msdn2.microsoft.com/en-us/library/hxds244y(VS.80).aspx
        # bug 363984
        import System
        def inheritDelegate():
            class C(System.Delegate): pass

        def inheritArray():
            class C(System.Array): pass

        def inheritValueType():
            class C(System.ValueType): pass

        def inheritEnum():
            class C(System.Enum): pass

        self.assertRaises(TypeError, inheritDelegate)
        self.assertRaises(TypeError, inheritArray)
        self.assertRaises(TypeError, inheritValueType)
        self.assertRaises(TypeError, inheritEnum) 
Example #10
Source File: test_simplederive.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_system_type_cs0644(self):
        # http://msdn2.microsoft.com/en-us/library/hxds244y(VS.80).aspx
        # bug 363984
        import System
        def inheritDelegate():
            class C(System.Delegate): pass

        def inheritArray():
            class C(System.Array): pass

        def inheritValueType():
            class C(System.ValueType): pass

        def inheritEnum():
            class C(System.Enum): pass

        self.assertRaises(TypeError, inheritDelegate)
        self.assertRaises(TypeError, inheritArray)
        self.assertRaises(TypeError, inheritValueType)
        self.assertRaises(TypeError, inheritEnum) 
Example #11
Source File: run_interactive.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def InitializePath(self):
        searchPath = []
        currentDir = Directory.GetCurrentDirectory()
        searchPath.append(currentDir)
        filePathDir = Path.GetDirectoryName(Path.Combine(currentDir, self.fileName))
        searchPath.append(filePathDir)
        entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
        searchPath.append(entryDir)
        siteDir = Path.Combine(entryDir, "Lib")
        searchPath.append(siteDir)
        devStdLibDir = Path.Combine(entryDir, '../../External.LCA_RESTRICTED/Languages/IronPython/27/Lib')
        searchPath.append(devStdLibDir)
        dllsDir = Path.Combine(entryDir, "DLLs")
        if Directory.Exists(dllsDir):
            searchPath.append(dllsDir)

        self.engine.SetSearchPaths(Array[str](searchPath)) 
Example #12
Source File: test_method_signature.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_one_array(self):
        import System
        from Merlin.Testing.BaseClass import IInterface600
        f = IInterface600.m_c

        def checkEqual(first, second):
            self.assertEqual(first, second)
        
        class C(IInterface600):
            def m_c(self, arg):
                if arg:
                    checkEqual(sum(arg), expected)
                    arg[0] = 10

        x = C()
        a = System.Array[int]([1,2])
        expected = 3
        f(x, a)
        self.assertEqual(a[0], 10)
        
        f(x, None) 
Example #13
Source File: sets.py    From compas with MIT License 6 votes vote down vote up
def ghtree_to_list(atree):
    """Returns a list representation of a Grasshopper DataTree

    Examples:
        >>> atree=Tree[object]()
        >>> [atree.Add(str("entry: " + str(i)), Path(Array[int]([i]))) for i in range(3)]
        >>> alist = ghtree_to_list(atree)
    """
    def extend_at(path, index, simple_input, rest_list):
        target = path[index]
        if len(rest_list) <= target:
            rest_list.extend([None]*(target-len(rest_list)+1))
        if index == path.Length - 1:
            rest_list[target] = list(simple_input)
        else:
            if rest_list[target] is None:
                rest_list[target] = []
            extend_at(path, index+1, simple_input, rest_list[target])

    all = []
    for i in range(atree.BranchCount):
        path = atree.Path(i)
        extend_at(path, 0, atree.Branch(path), all)
    return all 
Example #14
Source File: run_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def InitializePath(self):
        searchPath = []
        currentDir = Directory.GetCurrentDirectory()
        searchPath.append(currentDir)
        filePathDir = Path.GetDirectoryName(Path.Combine(currentDir, self.fileName))
        searchPath.append(filePathDir)
        entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
        searchPath.append(entryDir)
        siteDir = Path.Combine(entryDir, "Lib")
        searchPath.append(siteDir)
        devStdLibDir = Path.Combine(entryDir, '../../External.LCA_RESTRICTED/Languages/IronPython/27/Lib')
        searchPath.append(devStdLibDir)
        dllsDir = Path.Combine(entryDir, "DLLs")
        if Directory.Exists(dllsDir):
            searchPath.append(dllsDir)

        self.engine.SetSearchPaths(Array[str](searchPath)) 
Example #15
Source File: client.py    From compas with MIT License 6 votes vote down vote up
def vector_from_array(a):
        """Make a Matlab-compatible vector from a (Numpy) array.

        Parameters
        ----------
        a : ndarray
            The input array.

        Returns
        -------
        System.Array
            The vector.

        Examples
        --------
        >>>

        """
        raise NotImplementedError 
Example #16
Source File: test_buffer.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_pass_in_clrarray(self):
        import System
        a1 = System.Array[int]([1,2])
        arrbuff1 = buffer(a1, 0, 5)
        self.assertEqual(1, arrbuff1[0])
        self.assertEqual(2, arrbuff1[1])

        a2 = System.Array[System.String](["a","b"])
        arrbuff2 = buffer(a2, 0, 2)
        self.assertEqual("a", arrbuff2[0])
        self.assertEqual("b", arrbuff2[1])

        self.assertEqual(len(arrbuff1), len(arrbuff2))

        arrbuff1 = buffer(a1, 1, 1)
        self.assertEqual(2, arrbuff1[0])
        self.assertEqual(len(arrbuff1), 1)
        
        arrbuff1 = buffer(a1, 0, -1)
        self.assertEqual(1, arrbuff1[0])
        self.assertEqual(2, arrbuff1[1])
        self.assertEqual(len(arrbuff1), 2)

        a3 = System.Array[System.Guid]([])
        self.assertRaises(TypeError, buffer, a3) 
Example #17
Source File: dotnet.py    From mikeio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_numpy(src):
    """
    Convert .NET array to numpy array

    Parameters
    ----------
    src : System.Array
        
    Returns
    -------
    np.ndarray
        
    """

    src_hndl = GCHandle.Alloc(src, GCHandleType.Pinned)
    try:
        src_ptr = src_hndl.AddrOfPinnedObject().ToInt64()
        bufType = ctypes.c_float * len(src)
        cbuf = bufType.from_address(src_ptr)
        d = np.frombuffer(cbuf, dtype=cbuf._type_)
    finally:
        if src_hndl.IsAllocated:
            src_hndl.Free()

    return d 
Example #18
Source File: test_cliclass.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp24004(self):
        self.assertTrue("Find" in System.Array.__dict__) 
Example #19
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 #20
Source File: test_cliclass.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp23772(self):
        a = System.Array
        x = a[int]([1, 2, 3])
        f = lambda x: x == 2
        g = a.Find[int]
        self.assertEqual(g.__call__(match=f, array=x), 2) 
Example #21
Source File: test_array.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_creation(self):
        t = System.Array
        ti = type(System.Array.CreateInstance(int, 1))

        self.assertRaises(TypeError, t, [1, 2])
        for x in (ti([1,2]), t[int]([1, 2]), ti([1.5, 2.3])):
            self.assertEqual([i for i in x], [1, 2])
            t.Reverse(x)
            self.assertEqual([i for i in x], [2, 1]) 
Example #22
Source File: sets.py    From compas with MIT License 5 votes vote down vote up
def list_to_ghtree(alist, none_and_holes=False, base_path=[0]):
    """Transforms nestings of lists or tuples to a Grasshopper DataTree.

    Examples:
        >>> mytree = [ [1,2], 3, [],[ 4,[5]] ]
        >>> a = list_to_tree(mytree)
        >>> b = list_to_tree(mytree, none_and_holes=True, base_path=[7,1])
    """
    def process_one_item(alist, tree, track):
        path = Path(Array[int](track))
        if len(alist) == 0 and none_and_holes:
            tree.EnsurePath(path)
            return
        for i, item in enumerate(alist):
            if hasattr(item, '__iter__'):  # if list or tuple
                track.append(i)
                process_one_item(item, tree, track)
                track.pop()
            else:
                if none_and_holes:
                    tree.Insert(item, path, i)
                elif item is not None:
                    tree.Add(item, path)

    tree = Tree[object]()
    if alist is not None:
        process_one_item(alist, tree, base_path[:])
    return tree 
Example #23
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 #24
Source File: test_array.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_slice(self):
        array1 = System.Array.CreateInstance(int, 20)
        for i in range(20): array1[i] = i * i

        # positive
        array1[::2] = [x * 2 for x in range(10)]

        for i in range(0, 20, 2):
            self.assertEqual(array1[i], i)
        for i in range(1, 20, 2):
            self.assertEqual(array1[i], i * i)

        # negative: not-same-length
        def f(): array1[::2] = [x * 2 for x in range(11)]
        self.assertRaises(ValueError, f) 
Example #25
Source File: test_exceptions.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_array(self):
        import System
        try:
            a = System.Array()
        except Exception as e:
            self.assertEqual(e.__class__, TypeError)
        else:
            self.assertTrue(False, "FAILED!") 
Example #26
Source File: test_ctor.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_object_array_as_ctor_args(self):
        from System import Array
        from Merlin.Testing.Call import Ctor104
        Ctor104(Array[object]([1,2])) 
Example #27
Source File: test_method_signature.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_ref_out_normal(self):
        import System
        from Merlin.Testing.BaseClass import IInterface600
        f = IInterface600.m_l
        
        class C(IInterface600):
            def m_l(self, arg1, arg2, arg3): 
                return 1
        
        x = C()
        a = self.box_int(10)
        b = self.box_int(20)
        c = 30
        
        #f(x, a, b, c) # bug 370075
        
        C.m_l = lambda self, arg1, arg2, arg3, *arg4: 2
        #f(x, a, b, c, 1, 2)

        C.m_l = lambda self, arg1, arg2, arg3, arg4, arg5: 3
        #f(x, a, b, c, 1, 2)
        
        f = IInterface600.m_k
        
        class C(IInterface600):
            def m_k(self, arg1, arg2, arg3, arg4):
                arg2.Value = arg1.Value * 3
                arg1.Value = arg3 * 5
                temp = sum(arg4)
                arg4[0] = 100            
                return temp

        x = C()
        a = self.box_int(10)
        b = self.box_int(20)
        c = 3
        d = System.Array[int]([40, 50])
        self.assertEqual(f(x, a, b, c, d), 90)
        self.assertEqual(a.Value, 15)
        self.assertEqual(b.Value, 30)
        self.assertEqual(d[0], 100) 
Example #28
Source File: test_indexervb.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(IndexerVbTest, self).setUp()
        self.add_clr_assemblies("indexerdefinitionsvb", "typesamples")
        import System
        self.array = System.Array[object] 
Example #29
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 #30
Source File: test_clrtype.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _call_typed_method(self):
        """Calling calc_total as a strongly-typed method using Reflection"""
        calc_total = self.p.GetType().GetMethod("calc_total")
        args = System.Array[object]( (1.0,) )
        res = calc_total.Invoke(self.p, args)
        return res

    # these methods are named with numbers because they need to run in a specific order