예제 #1
0
def test_correct_overload_selection():
    """Test correct overloading selection for common types."""
    from System import (String, Double, Single,
                        Int16, Int32, Int64)
    from System import Math

    substr = String("substring")
    assert substr.Substring(2) == substr.Substring.__overloads__[Int32](
        Int32(2))
    assert substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32](
        Int32(2), Int32(3))

    for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64],
                                     [1.0, 1.0, 1, 1, 1],
                                     [2.0, 0.5, 2, 0, -1]):
        assert Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Max(atype(value1),
                        atype(value2)) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))
        assert Math.Max(atype(value1),
                        value2) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))

    clr.AddReference("System.Runtime.InteropServices")
    from System.Runtime.InteropServices import GCHandle, GCHandleType
    from System import Array, Byte
    cs_array = Array.CreateInstance(Byte, 1000)
    handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned)
예제 #2
0
    def rows(self):
        """
        Returns a list of rows which are of type _Pdata
        You may access any fields, do assignments and delete rows like any other _Pdata objects
        """
        _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1]
        _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1]
        _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1]
        nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1]

        _existing_rows = []
        for index in range(int(nrows)):
            data = self.api.AdkGetRowData(self.data, index, Int32(0))[1]
            _existing_rows.append(
                _Pdata(
                    self.api,
                    _row_db_id,
                    data,
                    parent_pdata=self,
                    is_a_row=True,
                    row_index=index + 1,
                )
            )

        return _existing_rows
예제 #3
0
def createDatasetWithCompoundType(h5file):

    mtype = createMemType()
    ftype = createFileType()

    npoints = 4
    shape = Array[Int64]((npoints, ))
    dspace = H5S.create_simple(shape.Length, shape)

    dset = H5D.create(h5file, 'DS1', ftype, dspace)

    ms = MemoryStream()
    writer = BinaryWriter(ms)

    writer.Write(Int32(1153))
    s = 'Exterior (static)'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(53.23))
    writer.Write(Double(24.57))

    writer.Write(Int32(1184))
    s = 'Intake'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(55.12))
    writer.Write(Double(22.95))

    writer.Write(Int32(1027))
    s = 'Intake manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(103.55))
    writer.Write(Double(31.23))

    writer.Write(Int32(1313))
    s = 'Exhaust manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(1252.89))
    writer.Write(Double(84.11))

    byteArray = ms.ToArray()

    H5D.write(dset, mtype, H5Array[Byte](byteArray))

    H5S.close(dspace)
    H5T.close(ftype)
    H5T.close(mtype)

    return dset
def generate_arrow_graph(tasks):
    nodes = tasks[:, 0]
    nodes = [string.ascii_uppercase.index(node.upper()) for node in nodes]
    tasks[:, 0] = nodes

    dependencies_list = tasks[:, 1]
    dependencies_index = [[
        string.ascii_uppercase.index(dep.upper()) for dep in dependencies
        if dep != "-"
    ] for dependencies in dependencies_list]

    tasks[:, 1] = dependencies_index

    ActivityDependencies = List[ActivityDependency]()
    for task in tasks:
        #print("Task: {}".format(task[0]))
        Predecessors = List[Int32]()
        for t in task[1]:
            #print("Dependecnies: {}".format(t))
            Predecessors.Add(Int32(t))

        task_id = Int32(task[0])
        ActivityDependencies.Add(
            ActivityDependency(Activity(task_id), Predecessors))

    arrow_graph_generator = ArrowGraphGenerator(ActivityDependencies)
    activity_arrow_graph = arrow_graph_generator.GenerateGraph()

    edges = []
    # returns Dictionary<ActivityEdge, ActivityEdge>
    ActivityEdges = activity_arrow_graph.Edges
    for activity_edge in ActivityEdges:
        #print("edge [{}, {}]".format(activity_edge.Source.Id, activity_edge.Target.Id))
        #print(activity_edge.Target.Id)
        #print(activity_edge.Activity)
        if activity_edge.Activity:
            edges.append([
                activity_edge.Source.Id + 1, activity_edge.Target.Id + 1, {
                    'name': activity_edge.Activity.Id
                }
            ])
        else:
            edges.append([
                activity_edge.Source.Id + 1, activity_edge.Target.Id + 1, {
                    'name': ''
                }
            ])

    nodes = []
    Vertices = activity_arrow_graph.Vertices
    for verticle in Vertices:
        #print(verticle.Id)
        nodes.append(verticle.Id + 1)

    return nodes, edges
예제 #5
0
    def read_frame(self, cam):
        """Reads a image from the camera, if available, and returns it.

        If available, it returns
        ``(data, fmt, (w, h), count, queued_count, t)``, otherwise, it returns
        None. See :class:`ThorCamServer`.
        """
        queued_count = cam.get_NumberOfQueuedFrames()
        if queued_count <= 0:
            return

        frame = cam.GetPendingFrameOrNull()
        t = clock()
        if not frame:
            return

        count = frame.FrameNumber
        h = frame.ImageData.Height_pixels
        w = frame.ImageData.Width_pixels
        if self._color_processor is not None:
            from Thorlabs.TSI import ColorInterfaces
            demosaicked_data = Array.CreateInstance(UInt16, h * w * 3)
            processed_data = Array.CreateInstance(UInt16, h * w * 3)
            fmt = ColorInterfaces.ColorFormat.BGRPixel
            max_pixel_val = int(2**cam.BitDepth - 1)

            self._demosaic.Demosaic(w, h, Int32(0), Int32(0),
                                    cam.ColorFilterArrayPhase, fmt,
                                    ColorInterfaces.ColorSensorType.Bayer,
                                    Int32(cam.BitDepth),
                                    frame.ImageData.ImageData_monoOrBGR,
                                    demosaicked_data)

            self._color_processor.Transform48To48(demosaicked_data, fmt, 0,
                                                  max_pixel_val, 0,
                                                  max_pixel_val, 0,
                                                  max_pixel_val, 0, 0, 0,
                                                  processed_data, fmt)

            pixel_fmt = 'bgr48le'
            data = as_numpy_array(processed_data)
        else:
            pixel_fmt = 'gray16le'
            data = as_numpy_array(frame.ImageData.ImageData_monoOrBGR)
        # img = Image(
        #     plane_buffers=[data.tobytes()],
        #     pix_fmt=pixel_fmt, size=(w, h))
        return data.tobytes(), pixel_fmt, (w, h), count, queued_count, t
예제 #6
0
        def __init__(self, title, url, width, height, resizable, fullscreen,
                     min_size, webview_ready):
            self.Text = title
            self.AutoScaleBaseSize = Size(5, 13)
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])

            # Application icon
            try:  # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller
                handler = windll.kernel32.GetModuleHandleW(None)
                icon_handler = windll.user32.LoadIconW(handler, 1)
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handler)))
            except:
                pass

            self.webview_ready = webview_ready

            self.web_browser = WinForms.WebBrowser()
            self.web_browser.Dock = WinForms.DockStyle.Fill

            if url:
                self.web_browser.Navigate(url)

            self.Controls.Add(self.web_browser)
            self.is_fullscreen = False
            self.Shown += self.on_shown

            if fullscreen:
                self.toggle_fullscreen()
예제 #7
0
        def __init__(self, window):
            self.uid = window.uid
            self.pywebview_window = window
            self.url = None
            self.Text = window.title
            self.Size = Size(window.initial_width, window.initial_height)
            self.MinimumSize = Size(window.min_size[0], window.min_size[1])
            self.BackColor = ColorTranslator.FromHtml(window.background_color)

            if window.initial_x is not None and window.initial_y is not None:
                self.move(window.initial_x, window.initial_y)
            else:
                self.StartPosition = WinForms.FormStartPosition.CenterScreen

            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not window.resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            if window.minimized:
                self.WindowState = WinForms.FormWindowState.Minimized

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_path = os.path.join(os.path.dirname(os.path.realpath(importlib.util.find_spec("bcml").origin)), "data", "bcml.ico")
            icon_handle = windll.shell32.ExtractIconW(handle, icon_path, 0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handle))
                ).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.closed = window.closed
            self.closing = window.closing
            self.shown = window.shown
            self.loaded = window.loaded
            self.url = window.url
            self.text_select = window.text_select
            self.on_top = window.on_top

            self.is_fullscreen = False
            if window.fullscreen:
                self.toggle_fullscreen()

            if window.frameless:
                self.frameless = window.frameless
                self.FormBorderStyle = 0
            CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert)

            self.Shown += self.on_shown
            self.FormClosed += self.on_close
            self.FormClosing += self.on_closing

            self.Resize += self.on_resize
예제 #8
0
        def __init__(self, window):
            self.uid = window.uid
            self.pywebview_window = window
            self.real_url = None
            self.Text = window.title
            self.ClientSize = Size(window.width, window.height)
            self.MinimumSize = Size(window.min_size[0], window.min_size[1])
            self.BackColor = ColorTranslator.FromHtml(window.background_color)

            if window.x is not None and window.y is not None:
                self.move(window.x, window.y)
            else:
                self.StartPosition = WinForms.FormStartPosition.CenterScreen

            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not window.resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.shown = window.shown
            self.loaded = window.loaded
            self.url = window.url
            self.text_select = window.text_select

            self.is_fullscreen = False
            if window.fullscreen:
                self.toggle_fullscreen()

            if window.frameless:
                self.frameless = window.frameless
                self.FormBorderStyle = 0

            if is_cef:
                CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert)
            elif is_edge:
                self.browser = BrowserView.EdgeHTML(self, window)
            else:
                self.browser = BrowserView.MSHTML(self, window)

            self.Shown += self.on_shown
            self.FormClosed += self.on_close

            if is_cef:
                self.Resize += self.on_resize

            if window.confirm_close:
                self.FormClosing += self.on_closing
예제 #9
0
 def testFills(self, mapper, addToCleanUp):
     # TODO: if we set a lower value, numpy will crash inside arr_add_docstring
     # I consider docstrings to be low-priority-enough that it's OK to fudge this
     # for now. also, fixing it would be hard ;).
     flagPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Int32()))
     addToCleanUp(lambda: Marshal.FreeHGlobal(flagPtr))
     mapper.RegisterData("Py_OptimizeFlag", flagPtr)
     
     self.assertEquals(CPyMarshal.ReadInt(flagPtr), 2)
예제 #10
0
    def test_to_type_conversions(self):
        from System import Decimal, Double, Single
        from System import Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte
        from System import Boolean, Char, DateTime, Object, Enum, DateTimeKind

        val = 1
        for i in [big(val), Int32(val)]:
            self.assertEqual(i.ToDecimal(self.p), val)
            self.assertIsInstance(i.ToDecimal(self.p), Decimal)
            self.assertEqual(i.ToDouble(self.p), val)
            self.assertIsInstance(i.ToDouble(self.p), Double)
            self.assertEqual(i.ToSingle(self.p), val)
            self.assertIsInstance(i.ToSingle(self.p), Single)
            self.assertEqual(i.ToInt64(self.p), val)
            self.assertIsInstance(i.ToInt64(self.p), Int64)
            self.assertEqual(i.ToUInt64(self.p), val)
            self.assertIsInstance(i.ToUInt64(self.p), UInt64)
            self.assertEqual(i.ToInt32(self.p), val)
            self.assertIsInstance(i.ToInt32(self.p), Int32)
            self.assertEqual(i.ToUInt32(self.p), val)
            self.assertIsInstance(i.ToUInt32(self.p), UInt32)
            self.assertEqual(i.ToInt16(self.p), val)
            self.assertIsInstance(i.ToInt16(self.p), Int16)
            self.assertEqual(i.ToUInt16(self.p), val)
            self.assertIsInstance(i.ToUInt16(self.p), UInt16)
            self.assertEqual(i.ToByte(self.p), val)
            self.assertIsInstance(i.ToByte(self.p), Byte)
            self.assertEqual(i.ToSByte(self.p), val)
            self.assertIsInstance(i.ToSByte(self.p), SByte)
            self.assertEqual(i.ToBoolean(self.p), val)
            self.assertIsInstance(i.ToBoolean(self.p), Boolean)
            self.assertEqual(i.ToChar(self.p), Char(val))
            self.assertEqual(i.ToString(self.p), str(val))
            self.assertRaisesRegex(TypeError,
                                   r"Invalid cast from '\w+' to 'DateTime'",
                                   i.ToDateTime, self.p)

            for t in [
                    Decimal, Double, Single, Int64, UInt64, Int32, UInt32,
                    Int16, UInt16, Byte, SByte, Boolean, Char, str
            ]:
                self.assertEqual(i.ToType(t, self.p), t(i))

            self.assertEqual(i.ToType(Object, self.p), i)
            self.assertIsInstance(i.ToType(Object, self.p), Object)
            self.assertRaisesRegex(TypeError,
                                   r"Invalid cast from '\w+' to 'DateTime'",
                                   i.ToType, DateTime, self.p)
            self.assertRaisesRegex(
                TypeError,
                r"Invalid cast from '[\w.]+' to 'System.DateTimeKind'\.",
                i.ToType, DateTimeKind, self.p)
            if not is_mono:
                self.assertRaisesRegex(
                    TypeError,
                    r"Unable to cast object of type '[\w.]+' to type 'System.Enum'\.",
                    i.ToType, Enum, self.p)
예제 #11
0
        def __init__(self, title, url, width, height, resizable, fullscreen,
                     min_size, confirm_quit, background_color, debug,
                     webview_ready):
            self.Text = title
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])
            self.BackColor = ColorTranslator.FromHtml(background_color)

            if not resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable,
                                                      0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.webview_ready = webview_ready

            self.web_browser = WinForms.WebBrowser()
            self.web_browser.Dock = WinForms.DockStyle.Fill
            self.web_browser.ScriptErrorsSuppressed = True
            self.web_browser.IsWebBrowserContextMenuEnabled = False
            self.web_browser.WebBrowserShortcutsEnabled = False

            # HACK. Hiding the WebBrowser is needed in order to show a non-default background color. Tweaking the Visible property
            # results in showing a non-responsive control, until it is loaded fully. To avoid this, we need to disable this behaviour
            # for the default background color.
            if background_color != '#FFFFFF':
                self.web_browser.Visible = False
                self.first_load = True
            else:
                self.first_load = False

            self.cancel_back = False
            self.web_browser.PreviewKeyDown += self.on_preview_keydown
            self.web_browser.Navigating += self.on_navigating
            self.web_browser.DocumentCompleted += self.on_document_completed

            if url:
                self.web_browser.Navigate(url)

            self.Controls.Add(self.web_browser)
            self.is_fullscreen = False
            self.Shown += self.on_shown

            if confirm_quit:
                self.FormClosing += self.on_closing

            if fullscreen:
                self.toggle_fullscreen()
예제 #12
0
    def testCorrectOverloadSelection(self):
        """
        Test correct overloading selection for common types.
        """
        from System.Drawing import Font

        from System import (String, Double, Single, Int16, Int32, Int64)
        from System import Math

        substr = String("substring")
        self.assertTrue(
            substr.Substring(2) == substr.Substring.__overloads__[Int32](Int32(
                2)))
        self.assertTrue(
            substr.Substring(2, 3) == substr.Substring.__overloads__[
                Int32, Int32](Int32(2), Int32(3)))

        for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64],
                                         [1.0, 1.0, 1, 1, 1],
                                         [2.0, 0.5, 2, 0, -1]):
            self.assertTrue(
                Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(
                    value1)))
            self.assertTrue(
                Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(
                    value1)))
            self.assertTrue(
                Math.Max(atype(value1), atype(value2)) ==
                Math.Max.__overloads__[atype,
                                       atype](atype(value1), atype(value2)))
            if (atype is Int64) and six.PY2:
                value2 = long(value2)
            self.assertTrue(
                Math.Max(atype(value1), value2) == Math.Max.__overloads__[
                    atype, atype](atype(value1), atype(value2)))

        clr.AddReference("System.Runtime.InteropServices")
        from System.Runtime.InteropServices import GCHandle, GCHandleType
        from System import Array, Byte
        CSArray = Array.CreateInstance(Byte, 1000)
        handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned)
예제 #13
0
        def __init__(self, uid, title, url, width, height, resizable, fullscreen, min_size,
                     confirm_quit, background_color, debug, js_api, text_select, frameless, webview_ready):
            self.uid = uid
            self.Text = title
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])
            self.BackColor = ColorTranslator.FromHtml(background_color)

            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.webview_ready = webview_ready
            self.load_event = Event()
            self.background_color = background_color
            self.url = url

            self.is_fullscreen = False
            if fullscreen:
                self.toggle_fullscreen()

            if frameless:
                self.frameless = frameless
                self.FormBorderStyle = 0

            if is_cef:
                CEF.create_browser(self.uid, self.Handle.ToInt32(), BrowserView.alert, url, js_api)
            else:
                self._create_mshtml_browser(url, js_api, debug)

            self.text_select = text_select
            self.Shown += self.on_shown
            self.FormClosed += self.on_close

            if is_cef:
                self.Resize += self.on_resize

            if confirm_quit:
                self.FormClosing += self.on_closing
예제 #14
0
    def create_rows(self, quantity=1):
        """
        Returns a list containg rows of _Pdata type.
        Example:
            rows = invoice.create_rows(2)
            rows[0].adk_ooi_... = "hello"
            rows[1].adk_ooi_... = "world"
            invoice.save()

        Args:
            quantity: number of rows to create
        """
        if quantity < 1:
            raise ValueError("New row quantity must be 1 or higher.")

        _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1]
        _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1]
        _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1]
        nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1]

        _rows = self.api.AdkCreateDataRow(_row_db_id, int(nrows) + quantity)
        self.api.AdkSetDouble(self.data, _nrows_field_id, Double(nrows + quantity))
        self.api.AdkSetData(self.data, _rows_field_id, _rows)

        row_objects = []
        for index in range(quantity):
            actual_nrows_index = nrows + index
            row_objects.append(
                _Pdata(
                    self.api,
                    _row_db_id,
                    self.api.AdkGetDataRow(_rows, actual_nrows_index),
                    parent_pdata=self,
                    row_index=actual_nrows_index,
                )
            )

        return row_objects
예제 #15
0
def createDatasetWithCompoundType(h5file):

    # component name -> (offset, size, type)

    ht = { 'a_name': (0, 4, H5T_NATIVE_INT),
           'b_name': (4, 4, H5T_NATIVE_FLOAT),
           'c_name': (8, 8, H5T_NATIVE_DOUBLE) }

    sizeof = 0
    for k in ht.keys():
        sizeof  += ht[k][1]

    dtype = H5T.create(H5T.CreateClass.COMPOUND, sizeof)
    for k in ht.keys():
        H5T.insert(dtype, k, ht[k][0], ht[k][2])

    npoints = 10
    shape = Array[Int64]((npoints,))
    dspace = H5S.create_simple(shape.Length, shape)

    dset = H5D.create(h5file, 'ArrayOfStructures', dtype, dspace)

    # create an array of Byte
    # use BitConverter to get Byte representations

    shape = Array[Int64]((npoints*sizeof,))
    byteArray = Array.CreateInstance(Byte, shape)

    for i in range(npoints):

        offset = i*sizeof

        a = Int32(i)
        Array.Copy(BitConverter.GetBytes(a), 0, byteArray,
                   offset+ht['a_name'][0], ht['a_name'][1])
        b = Single(i*i)
        Array.Copy(BitConverter.GetBytes(b), 0, byteArray,
                   offset+ht['b_name'][0], ht['b_name'][1])
        c = Double(1.0/(i+1.0))
        Array.Copy(BitConverter.GetBytes(c), 0, byteArray,
                   offset+ht['c_name'][0], ht['c_name'][1])

    H5D.write(dset, dtype, H5Array[Byte](byteArray))

    H5S.close(dspace)
    H5T.close(dtype)

    return dset
예제 #16
0
 def _fetch_getdev(self):
     clist = self._clean_channel_list()
     if self._inbuffer == None:
         return None
     #This conversion is much faster than doing
     # v=array(list(buf.GetDataAsVolts()))
     buf = self._inbuffer
     fullsize = buf.BufferSizeInSamples
     validsize = buf.ValidSamples
     v = np.ndarray(validsize, dtype=float)
     Marshal.Copy(buf.GetDataAsVolts(), 0,
                  IntPtr.op_Explicit(Int32(v.ctypes.data)), len(v))
     num_channel = len(clist)
     if num_channel != 1 and self.nb_samples.getcache() != 1:
         v.shape = (-1, num_channel)
         v = v.T
     return v
예제 #17
0
파일: c_utils.py 프로젝트: spfeiffer1/hyram
def convert_numpy_array_to_cnet(nparray):
    '''
    Given a `numpy.ndarray` returns a CLR `System.Array`.  See _MAP_NP_NET for
    the mapping of Numpy dtypes to CLR types.

    Note: `complex64` and `complex128` arrays are converted to `float32`
    and `float64` arrays respectively with shape [m,n,...] -> [m,n,...,2]
    Reference: https://github.com/pythonnet/pythonnet/issues/514
    '''
    dims = nparray.shape
    dtype = nparray.dtype
    # For complex arrays, we must make a view of the array as its corresponding
    # float type.
    if dtype == np.complex64:
        dtype = np.dtype('float32')
        dims.append(2)
        nparray = nparray.view(np.float32).reshape(dims)
    elif dtype == np.complex128:
        dtype = np.dtype('float64')
        dims.append(2)
        nparray = nparray.view(np.float64).reshape(dims)

    cnet_dims = Array.CreateInstance(Int32, nparray.ndim)
    for I in range(nparray.ndim):
        cnet_dims[I] = Int32(dims[I])

    if not nparray.flags.c_contiguous:
        nparray = nparray.copy(order='C')
    assert nparray.flags.c_contiguous

    try:
        cnet_array = Array.CreateInstance(_MAP_NP_NET[dtype], cnet_dims)
    except KeyError:
        raise NotImplementedError(
            "asNetArray does not yet support dtype {}".format(dtype))

    try:  # Memmove
        dest_handle = GCHandle.Alloc(cnet_array, GCHandleType.Pinned)
        src_ptr = nparray.__array_interface__['data'][0]
        dest_ptr = dest_handle.AddrOfPinnedObject().ToInt64()
        ctypes.memmove(dest_ptr, src_ptr, nparray.nbytes)
    finally:
        if dest_handle.IsAllocated: dest_handle.Free()
    return cnet_array
예제 #18
0
        def __init__(self, title, url, width, height, resizable, fullscreen,
                     min_size, confirm_quit, webview_ready):
            self.Text = title
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])

            if not resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable,
                                                      0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.webview_ready = webview_ready

            self.web_browser = WinForms.WebBrowser()
            self.web_browser.Dock = WinForms.DockStyle.Fill
            self.web_browser.ScriptErrorsSuppressed = True
            self.web_browser.IsWebBrowserContextMenuEnabled = False

            self.cancel_back = False
            self.web_browser.PreviewKeyDown += self.on_preview_keydown
            self.web_browser.Navigating += self.on_navigating

            if url:
                self.web_browser.Navigate(url)

            self.Controls.Add(self.web_browser)
            self.is_fullscreen = False
            self.Shown += self.on_shown

            if confirm_quit:
                self.FormClosing += self.on_closing

            if fullscreen:
                self.toggle_fullscreen()
예제 #19
0
        def __init__(self, title, url, width, height, resizable, fullscreen,
                     min_size, confirm_quit, webview_ready):
            self.Text = title
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])
            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            try:  # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller
                handler = windll.kernel32.GetModuleHandleW(None)
                icon_handler = windll.user32.LoadIconW(handler, 1)
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handler)))
            except:
                pass

            self.webview_ready = webview_ready

            self.web_browser = WinForms.WebBrowser()
            self.web_browser.Dock = WinForms.DockStyle.Fill
            self.web_browser.ScriptErrorsSuppressed = True
            self.web_browser.IsWebBrowserContextMenuEnabled = False

            if url:
                self.web_browser.Navigate(url)

            self.Controls.Add(self.web_browser)
            self.is_fullscreen = False
            self.Shown += self.on_shown

            if confirm_quit:
                self.FormClosing += self.on_closing

            if fullscreen:
                self.toggle_fullscreen()
예제 #20
0
    def test_char_new(self):
        from System import Char, Int32, UInt16

        self.assertEqual(Char(), '\x00')
        self.assertEqual(Char('a'), 'a')
        self.assertEqual(Char(ord('A')), 'A')
        self.assertEqual(Char(chr(65)), 'A')
        self.assertEqual(Char(UInt16(65)), 'A')
        self.assertEqual(Char(Int32(65)), 'A')
        self.assertEqual(Char(big(65)), 'A')
        self.assertEqual(Char('€'), '€')

        self.assertIsInstance(Char(), Char)
        self.assertIsInstance(Char('a'), Char)
        self.assertIsInstance(Char(65), Char)

        self.assertRaises(TypeError, Char, 'a', 'b')
        self.assertRaises(
            TypeError,
            Char,
            'ab',
        )
        self.assertRaises(TypeError, Char, '🐍')  # surrogate pair
        self.assertRaises(TypeError, Char, '\U0001F40D')  # surrogate pair
        self.assertEqual(Char('🐍'[0]), '\uD83D')  # high surrogate

        self.assertRaises(TypeError, Char.__new__, str)
        self.assertRaises(TypeError, Char.__new__, str, 'a')
        self.assertRaises(TypeError, Char.__new__, str, 65)
        self.assertRaises(TypeError, Char.__new__, int)
        self.assertRaises(TypeError, Char.__new__, int, 'a')
        self.assertRaises(TypeError, Char.__new__, int, 65)

        # ValueError would be OK too
        self.assertRaises(OverflowError, Char, -1)
        self.assertRaises(OverflowError, Char, 0x110000)
        self.assertRaises(OverflowError, Char, 0x10000)
예제 #21
0
    def testClasses(self):
        from System.Collections import Hashtable
        from Python.Test import StringDelegate
        from System import Int32

        self.notify("Running class leak check...")

        for i in xrange(self.count):
            if i == 10:
                self.start_test()

            # Reference type
            x = Hashtable()
            del x

            # Value type
            x = Int32(99)
            del x

            # Delegate type
            x = StringDelegate(hello)
            del x

        self.end_test()
예제 #22
0
import sys
if sys.platform != 'cli':
    raise ImportError(
        "If you're running CPython, you don't need ironclad. If you're running Jython, ironclad won't work."
    )

import os
_dirname = os.path.dirname(__file__)

import clr
from System import GC, Int32, IntPtr
from System.Reflection import Assembly
from System.Runtime.InteropServices import Marshal

if Marshal.SizeOf(Int32()) != Marshal.SizeOf(IntPtr()):
    raise ImportError("Ironclad is currently 32-bit only")

clr.AddReference(Assembly.LoadFile(os.path.join(_dirname, "ironclad.dll")))
from Ironclad import CPyMarshal, PythonMapper
from Ironclad.Structs import PyObject, PyVarObject, PyTypeObject
_mapper = PythonMapper(os.path.join(_dirname, "python27.dll"))


def gcwait():
    """
    Attempt to force a garbage collection, and wait for pending finalizers.
    
    If you think you need to call this function, you're probably wrong.
    """
    for _ in range(4):
from AntPlus.Profiles.Components import DataPage
from AntPlus.Profiles.BikePower import BikePowerDisplay, SetCustomCalibrationParameterPage
from AntPlus.Types import BindableByteArray
from System import Array, Byte, BitConverter, Int32
from System.Collections.Generic import List
import System


def stopScript():
    simulator.TurnOff()


simulator.TurnOn()
page = SetCustomCalibrationParameterPage()

# byte 0
# 1 = SCALE
# 2 = ?
byte_0 = Byte(1)

# bytes 1-4 : values (little endian 32 bits int)
bytes_value = BitConverter.GetBytes(Int32(-2300))

# byte 5 : reserved future use
byte_5 = Byte(0)

x = List[Byte]([byte_0] + [Byte(b) for b in bytes_value] + [byte_5])
array = BindableByteArray(x)
# page.Encode(array)
page.ManufacturerSpecificData = array
simulator.SendSetCustomCalibrationParameterPage(page)
예제 #24
0
def ptr(offset: int):
    return IntPtr.op_Explicit(Int32(offset))
예제 #25
0
        def __init__(self, uid, title, url, width, height, resizable,
                     fullscreen, min_size, confirm_quit, background_color,
                     debug, js_api, text_select, webview_ready):
            self.uid = uid
            self.Text = title
            self.ClientSize = Size(width, height)
            self.MinimumSize = Size(min_size[0], min_size[1])
            self.BackColor = ColorTranslator.FromHtml(background_color)

            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            # Application icon
            handle = windll.kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable,
                                                      0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.webview_ready = webview_ready
            self.load_event = Event()

            self.web_browser = WebBrowserEx()
            self.web_browser.Dock = WinForms.DockStyle.Fill
            self.web_browser.ScriptErrorsSuppressed = not debug
            self.web_browser.IsWebBrowserContextMenuEnabled = debug
            self.web_browser.WebBrowserShortcutsEnabled = False
            self.web_browser.DpiAware = True

            self.web_browser.ScriptErrorsSuppressed = not debug
            self.web_browser.IsWebBrowserContextMenuEnabled = debug

            self.js_result_semaphore = Semaphore(0)
            self.js_bridge = BrowserView.JSBridge()
            self.js_bridge.parent_uid = uid
            self.web_browser.ObjectForScripting = self.js_bridge

            self.text_select = text_select

            if js_api:
                self.js_bridge.api = js_api

            # HACK. Hiding the WebBrowser is needed in order to show a non-default background color. Tweaking the Visible property
            # results in showing a non-responsive control, until it is loaded fully. To avoid this, we need to disable this behaviour
            # for the default background color.
            if background_color != '#FFFFFF':
                self.web_browser.Visible = False
                self.first_load = True
            else:
                self.first_load = False

            self.cancel_back = False
            self.web_browser.PreviewKeyDown += self.on_preview_keydown
            self.web_browser.Navigating += self.on_navigating
            self.web_browser.NewWindow3 += self.on_new_window
            self.web_browser.DownloadComplete += self.on_download_complete
            self.web_browser.DocumentCompleted += self.on_document_completed

            if url:
                self.web_browser.Navigate(url)
            else:
                self.web_browser.DocumentText = default_html

            self.url = url

            self.Controls.Add(self.web_browser)
            self.is_fullscreen = False
            self.Shown += self.on_shown
            self.FormClosed += self.on_close

            if confirm_quit:
                self.FormClosing += self.on_closing

            if fullscreen:
                self.toggle_fullscreen()
예제 #26
0
#===============================================================================

import System
from System import Array, Int32, Int64

#===============================================================================

print '\nInitializing HDF5 library\n'
status = H5.Open()

shape = Array[Int64]((5, 6))
data = Array.CreateInstance(Int32, shape)

for row in range(0, shape[0]):
    for col in range(0, shape[1]):
        data[row,col] = Int32(row+col)

h5file = H5F.create('SDS.h5', H5F.CreateMode.ACC_TRUNC)

dspace = H5S.create_simple(shape.Length, shape)
dtype = H5T.copy(H5T.H5Type.NATIVE_INT)
status = H5T.setOrder(dtype, H5T.Order.LE)

dset = H5D.create(h5file, 'IntArray', dtype, dspace)

dtype = H5T.copy(H5T.H5Type.NATIVE_INT)

status = H5D.write(dset, dtype, H5Array[Int32](data))

H5D.close(dset)
H5T.close(dtype)
예제 #27
0
        def __init__(self, window):
            self.uid = window.uid
            self.pywebview_window = window
            self.real_url = None
            self.Text = window.title
            self.Size = Size(window.initial_width, window.initial_height)
            self.MinimumSize = Size(window.min_size[0], window.min_size[1])

            if window.transparent:  # window transparency is not supported, as webviews are not transparent.
                self.BackColor = Color.LimeGreen
                self.TransparencyKey = Color.LimeGreen
                self.SetStyle(
                    WinForms.ControlStyles.SupportsTransparentBackColor, True)
            else:
                self.BackColor = ColorTranslator.FromHtml(
                    window.background_color)

            if window.initial_x is not None and window.initial_y is not None:
                self.move(window.initial_x, window.initial_y)
            else:
                self.StartPosition = WinForms.FormStartPosition.CenterScreen

            self.AutoScaleDimensions = SizeF(96.0, 96.0)
            self.AutoScaleMode = WinForms.AutoScaleMode.Dpi

            if not window.resizable:
                self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle
                self.MaximizeBox = False

            if window.minimized:
                self.WindowState = WinForms.FormWindowState.Minimized

            # Application icon
            handle = kernel32.GetModuleHandleW(None)
            icon_handle = windll.shell32.ExtractIconW(handle, sys.executable,
                                                      0)

            if icon_handle != 0:
                self.Icon = Icon.FromHandle(
                    IntPtr.op_Explicit(Int32(icon_handle))).Clone()

            windll.user32.DestroyIcon(icon_handle)

            self.closed = window.closed
            self.closing = window.closing
            self.shown = window.shown
            self.loaded = window.loaded
            self.url = window.real_url
            self.text_select = window.text_select
            self.on_top = window.on_top

            self.is_fullscreen = False
            if window.fullscreen:
                self.toggle_fullscreen()

            if window.frameless:
                self.frameless = window.frameless
                self.FormBorderStyle = 0
            if is_cef:
                CEF.create_browser(window, self.Handle.ToInt32(),
                                   BrowserView.alert)
            elif is_chromium:
                self.browser = Chromium.EdgeChrome(self, window)
            elif is_edge:
                self.browser = Edge.EdgeHTML(self, window)
            else:
                self.browser = IE.MSHTML(self, window)

            self.Shown += self.on_shown
            self.FormClosed += self.on_close
            self.FormClosing += self.on_closing

            if is_cef:
                self.Resize += self.on_resize