Esempio n. 1
0
def main():
    from qtpy.QtCore import Qt, QCoreApplication
    from qtpy.QtWidgets import QApplication
    from qtpy import API

    import hyperspyui.info
    from hyperspyui.settings import Settings

    QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    # Need to set early to make QSettings accessible
    QCoreApplication.setApplicationName("HyperSpyUI")
    QCoreApplication.setOrganizationName("Hyperspy")
    QCoreApplication.setApplicationVersion(hyperspyui.info.__version__)

    # First, clear all default settings!
    # TODO: This will cause a concurrency issue with multiple launch
    Settings.clear_defaults()
    # Setup default for single/multi-instance
    settings = Settings(group="General")
    settings.set_default('allow_multiple_instances', False)
    if settings['allow_multiple_instances', bool]:
        # Using multiple instances, get a new application
        app = QApplication(sys.argv)
    else:
        # Make sure we only have a single instance
        from hyperspyui.singleapplication import get_app
        app = get_app('hyperspyui')

    splash = get_splash()

    log_file = _get_logfile()
    if log_file:
        sys.stdout = sys.stderr = log_file
    else:
        @contextmanager
        def dummy_context_manager(*args, **kwargs):
            yield
        log_file = dummy_context_manager()

    with log_file:
        # Need to have import here, since QApplication needs to be called first
        from hyperspyui.mainwindow import MainWindow

        form = MainWindow(splash=splash)
        if not settings['allow_multiple_instances', bool]:
            if "pyqt" in API:
                app.messageAvailable.connect(form.handleSecondInstance)
            elif API == 'pyside':
                app.messageReceived.connect(form.handleSecondInstance)
        form.showMaximized()

        form.splash.hide()
        form.load_complete.emit()
        # Ensure logging is OK
        import hyperspy.api as hs
        hs.set_log_level(LOGLEVEL)

        app.exec_()
Esempio n. 2
0
def run():
    import sys
    from qtpy.QtWidgets import QApplication

    def selection():
        print('hello')

    app = QApplication(sys.argv)
    dialog = PeriodicTableDialog(None)
    dialog.selectionChanged.connect(selection)
    dialog.exec_()
    print(dialog.selection())
    app.exec_()
Esempio n. 3
0
def main(args=sys.argv):
    app = QApplication(args)

    widget = SpellCheckTextEdit('Type here')
    widget.show()
    widget.raise_()

    return app.exec_()
Esempio n. 4
0
def test(nr):
    if nr == 1:
        MyMainWindow().start()
    elif nr == 2:
        MyDialog(None, True).start()
    elif nr == 3:
        app = QApplication(sys.argv)
        w = WidgetWindow()
        print (w)
        app.exec_()
    if nr == 4:
        app = QApplication(sys.argv)
        window = QMainWindow()
        w = MyWidget(window)
        print (w)
        window.show()
        app.exec_()
    if nr == 5:
        MyMainWindowWithMenu().start()
    if nr == 6:
        MyCombinationWindow().start()
Esempio n. 5
0
def open_in_window(widget_name, script):
    """
    Displays a widget in a window.
    :param widget_name:  A qualified name of a widget, ie mantidqt.mywidget.MyWidget
    :param script: A qualified name of a test function that can be run after the
        widget is created. The test function must have the signature:

            def test(widget):
                ...

        where argument widget is an instance of the tested widget.
        The test function can yield from time to time after which the widget can update itself.
        This will make the test non-blocking and changes can be viewed as the script runs.
        If the test yields an integer it is interpreted as the number of seconds to wait
        until the next step.
    """
    raw_input('Please attach the Debugger now if required. Press any key to continue')
    setup_library_paths()
    app = QApplication([""])
    w = create_widget(widget_name)
    w.setWindowTitle(widget_name)
    w.show()

    if script is not None:
        try:
            # If script is a generator script_iter allows non-blocking
            # test execution
            script_iter = iter(run_script(script, w))
            pause_timer = QTimer()
            pause_timer.setSingleShot(True)

            def idle():
                if not pause_timer.isActive():
                    try:
                        # Run test script until the next 'yield'
                        pause_sec = script_iter.next()
                        if pause_sec is not None:
                            # Start non-blocking pause in seconds
                            pause_timer.start(int(pause_sec * 1000))
                    except StopIteration:
                        pass
                    except:
                        traceback.print_exc()
            timer = QTimer()
            # Zero-timeout timer runs idle() between Qt events
            timer.timeout.connect(idle)
            timer.start()
        except:
            pass

    sys.exit(app.exec_())
Esempio n. 6
0
def test():
    """Run conda packages widget test"""
    app = QApplication([])
    widget = TestWidget(None)
    widget.show()
    sys.exit(app.exec_())
Esempio n. 7
0
        else:
            self.url_input.setText(url)
        self.webview.load(QUrl(url))


class PMGWebEngineView(QWebEngineView):
    windowList = []
    signal_new_window_created = Signal(PMGWebBrowser)

    # 重写createwindow()
    def createWindow(self, QWebEnginePage_WebWindowType):
        # new_webview = WebEngineView()
        new_window = PMGWebBrowser()
        # new_window.setCentralWidget(new_webview)
        # new_window.show()
        self.windowList.append(new_window)  # 注:没有这句会崩溃!!!
        self.signal_new_window_created.emit(new_window)
        return new_window.webview


if __name__ == "__main__":
    app = QApplication(sys.argv)

    w = PMGWebBrowser()
    w.show()
    w2 = PMGWebBrowser()
    w2.show()
    w3 = PMGWebBrowser()
    w3.show()
    sys.exit(app.exec_())
Esempio n. 8
0
def main():
    from qtpy.QtWidgets import QApplication
    app = QApplication([])
    test = RemoveObjectDialog()
    test.show()
    app.exec_()
def main():
    app = QApplication(sys.argv)
    win = ManiWindow()
    win.show()
    sys.exit(app.exec_())
Esempio n. 10
0
def main():
    app = QApplication(sys.argv)
    ex = StackedCanvasView()
    sys.exit(app.exec_())
Esempio n. 11
0
def cmd_line():
    """the setup.py entry point for ``pyNastranGUI``"""
    # this fixes the icon shown in the windows taskbar to be the custom one (not the python one)
    if sys.platform == 'win32':
        myappid = 'pynastran.pynastrangui.%s' % (pyNastran.__version__) # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    from qtpy.QtWidgets import QApplication
    app = QApplication(sys.argv)

    try:
        import qtmodern.styles
    except ImportError:
        pass
    else:
        qtmodern.styles.dark(app)

    #app.setStyle('Fusion')
    #app.setStyle('WindowsXP')

    #if 0:
        #import qtpy.QtGui as QtGui
        #import qtpy.QtCore as QtCore
        #palette = QtGui.QPalette()
        #palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53,53,53))
        #palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white)
        #palette.setColor(QtGui.QPalette.Base, QtGui.QColor(15,15,15))
        #palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53,53,53))
        #palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white)
        #palette.setColor(QtGui.QPalette.ToolTipText, QtCore.Qt.white)
        #palette.setColor(QtGui.QPalette.Text, QtCore.Qt.white)
        #palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53,53,53))
        #palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.white)
        #palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)

        #palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(142,45,197).lighter())
        #palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)
        #app.setPalette(palette)

    if 0:
        import qtpy.QtGui as QtGui
        import qtpy.QtCore as QtCore
        from qtpy.QtGui import QPalette, QColor
        darkPalette = QtGui.QPalette()
        darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
        darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90))
        darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35))
        darkPalette.setColor(QPalette.Text, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.Base, QColor(42, 42, 42))
        darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
        darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
        darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180))
        darkPalette.setColor(QPalette.Link, QColor(56, 252, 196))
        darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
        darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
        darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180))

        # disabled
        darkPalette.setColor(QPalette.Disabled, QPalette.WindowText,
                             QColor(127, 127, 127))
        darkPalette.setColor(QPalette.Disabled, QPalette.Text,
                             QColor(127, 127, 127))
        darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText,
                             QColor(127, 127, 127))
        darkPalette.setColor(QPalette.Disabled, QPalette.Highlight,
                             QColor(80, 80, 80))
        darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText,
                             QColor(127, 127, 127))
        app.setPalette(darkPalette)

    QApplication.setOrganizationName("pyNastran")
    QApplication.setOrganizationDomain(pyNastran.__website__)
    QApplication.setApplicationName("pyNastran")
    QApplication.setApplicationVersion(pyNastran.__version__)
    inputs = get_inputs()
    #inputs['app'] = app
    MainWindow(inputs)
    app.exec_()
Esempio n. 12
0
def main():  # pragma: no cover
    """test example for CalculatorWindow"""
    # kills the program when you hit Cntl+C from the command line
    # doesn't save the current state as presumably there's been an error
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    import sys
    # Someone is launching this directly
    # Create the QApplication
    app = QApplication(sys.argv)
    #The Main window

    #from pyNastran.gui.menus.legend.animation import AnimationWindow
    data2 = {
        'font_size': 8,
        'icase_fringe': 1,
        'icase_disp': 2,
        'icase_vector': 3,
        'title': 'cat',
        'time': 2,
        'frames/sec': 30,
        'resolution': 1,
        'iframe': 0,
        'is_scale': False,
        'dirname': os.getcwd(),
        'scale': 2.0,
        'default_scale': 10,
        'arrow_scale': 3.0,
        'default_arrow_scale': 30,

        #'phase' : 0.,
        'phase': None,
        'default_phase': 120.,
        #'default_phase' : None,

        #'start_time' : 0.,
        #'end_time' : 0.,
        'default_time': 0.,
        'icase_start': 10,
        'icase_delta': 3,
        'stress_min': 0.,
        'stress_max': 1000.,
    }
    data2['phase'] = 0.  # uncomment for phase

    form = [
        [
            'Geometry',
            None,
            [
                ('NodeID', 0, []),
                ('ElementID', 1, []),
                ('PropertyID', 2, []),
                ('MaterialID', 3, []),
                ('E', 4, []),
                (
                    'Element Checks',
                    None,
                    [('ElementDim', 5, []), ('Min Edge Length', 6, []),
                     ('Min Interior Angle', 7, []),
                     ('Max Interior Angle', 8, [])],
                ),
            ],
        ],
    ]
    np_funcs = []
    #np_linalg_funcs = []

    modules = [
        ('numpy', numpy, [], []),
        ('numpy.linalg', numpy.linalg, [], []),
        ('scipy', scipy, [], []),
        ('scipy.interpolate', scipy.interpolate, [], []),
        ('scipy.special', scipy.special, [], []),
        #('scipy', scipy, [], []),
        #('scipy', scipy, [], []),
        #('numpy', numpy),
        #('numpy', numpy),
        #('numpy', numpy),
        #('numpy', numpy),
    ]

    #modules_form = [
    #['numpy', None, np_funcs2],
    #['numpy.linalg', None, np_linalg_funcs2],
    #]

    #from pyNastran.utils import object_methods
    [
        'ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'Bytes0', 'CLIP',
        'ComplexWarning', 'DataSource', 'Datetime64', 'ERR_CALL',
        'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE',
        'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO',
        'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf',
        'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'MachAr',
        'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF',
        'PZERO', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID',
        'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Str0', 'Tester',
        'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME',
        'Uint64', 'VisibleDeprecationWarning', 'WRAP', '_NoValue',
        '_UFUNC_API', '__NUMPY_SETUP__', '__all__', '__builtins__',
        '__cached__', '__config__', '__deprecated_attrs__', '__dir__',
        '__doc__', '__expired_functions__', '__file__', '__getattr__',
        '__git_revision__', '__loader__', '__name__', '__package__',
        '__path__', '__spec__', '__version__', '_add_newdoc_ufunc',
        '_builtins', '_distributor_init', '_financial_names', '_globals',
        '_mat', '_pytesttester', 'abs', 'absolute', 'add', 'add_docstring',
        'add_newdoc', 'add_newdoc_ufunc', 'alen', 'all', 'allclose', 'alltrue',
        'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis',
        'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh',
        'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition',
        'argsort', 'argwhere', 'around', 'array', 'array2string',
        'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str',
        'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray',
        'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d',
        'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr',
        'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or',
        'bitwise_xor', 'blackman', 'block', 'bmat', 'bool8', 'bool_',
        'broadcast', 'broadcast_arrays', 'broadcast_shapes', 'broadcast_to',
        'busday_count', 'busday_offset', 'busdaycalendar', 'byte',
        'byte_bounds', 'bytes0', 'bytes_', 'c_', 'can_cast', 'cast', 'cbrt',
        'cdouble', 'ceil', 'cfloat', 'char', 'character', 'chararray',
        'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack',
        'common_type', 'compare_chararrays', 'compat', 'complex128',
        'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate',
        'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'core',
        'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov',
        'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum',
        'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad',
        'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag',
        'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff',
        'digitize', 'disp', 'divide', 'divmod', 'dot', 'double', 'dsplit',
        'dstack', 'dtype', 'e', 'ediff1d', 'einsum', 'einsum_path', 'emath',
        'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma', 'exp',
        'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs',
        'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type',
        'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip',
        'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_',
        'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin',
        'fmod', 'format_float_positional', 'format_float_scientific',
        'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction',
        'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full',
        'full_like', 'gcd', 'generic', 'genfromtxt', 'geomspace',
        'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize',
        'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater',
        'greater_equal', 'half', 'hamming', 'hanning', 'heaviside',
        'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd',
        'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d',
        'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner',
        'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'intc',
        'integer', 'interp', 'intersect1d', 'intp', 'invert', 'is_busday',
        'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran',
        'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal',
        'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype',
        'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron', 'lcm', 'ldexp',
        'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg',
        'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log',
        'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and',
        'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longcomplex',
        'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mafromtxt',
        'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'matrixlib', 'max',
        'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median',
        'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum',
        'mintypecode', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan',
        'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum',
        'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod',
        'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray',
        'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative',
        'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal',
        'numarray', 'number', 'obj2sctype', 'object0', 'object_', 'ogrid',
        'oldnumeric', 'ones', 'ones_like', 'os', 'outer', 'packbits', 'pad',
        'partition', 'percentile', 'pi', 'piecewise', 'place', 'poly',
        'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint',
        'polymul', 'polynomial', 'polysub', 'polyval', 'positive', 'power',
        'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put',
        'put_along_axis', 'putmask', 'quantile', 'r_', 'rad2deg', 'radians',
        'random', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec',
        'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record',
        'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type',
        'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round',
        'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez',
        'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypes',
        'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions',
        'set_string_function', 'setbufsize', 'setdiff1d', 'seterr',
        'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory',
        'short', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin',
        'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort',
        'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square',
        'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract',
        'sum', 'swapaxes', 'sys', 'take', 'take_along_axis', 'tan', 'tanh',
        'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace',
        'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril',
        'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu',
        'triu_indices', 'triu_indices_from', 'true_divide', 'trunc',
        'typeDict', 'typecodes', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0',
        'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong',
        'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index',
        'unsignedinteger', 'unwrap', 'use_hugepage', 'ushort', 'vander', 'var',
        'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack',
        'warnings', 'where', 'who', 'zeros', 'zeros_like'
    ]

    exclusion_set = set([
        'os',
        'sys',
        'True_',
        'False_',
        'Bytes0',
        'Tester',
        'add_docstring',
        'add_newdoc',
        'add_newdoc_ufunc',
        'Str0',
        'Tester',
        'True_',
        'Uint64',
        'bytes0',
        'bytes_',
        'c_',
        'can_cast',
        'cast',
        'cbrt',
        'cdouble',
        'cfloat',
        'char',
        'character',
        'chararray',
        'clongdouble',
        'clongfloat',
        #'choose', 'clip', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip', 'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_', 'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'gcd', 'generic', 'genfromtxt', 'geomspace', 'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'half', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum', 'mintypecode', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'numarray', 'number', 'obj2sctype', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'os', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'place', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 'polyval', 'positive', 'power', 'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'quantile', 'r_', 'rad2deg', 'radians', 'random', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'short', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'sys', 'take', 'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc',
        'typeDict',
        'typecodes',
        'typename',
        'ubyte',
        'ufunc',
        'uint',
        'uint0',
        'uint16',
        'uint32',
        'uint64',
        'uint8',
        'uintc',
        'uintp'
    ])

    #load_module_functions(numpy, np_funcs, exclusion_set)
    #exclusion_set.update(set(np_funcs))
    #load_module_functions(numpy.linalg, np_linalg_funcs, exclusion_set)
    """
    Operations on field output:
    +	Perform addition.
    −	Perform subtraction or unary negation.
    *	Perform multiplication.
    /	Perform division.
    abs(A)	Take the absolute value.
    acos(A)	Take the arccosine.
    asin(A)	Take the arcsine.
    atan(A)	Take the arctangent.
    cos(A)	Take the cosine.
    degreeToRadian(A)	Convert degrees to radians.
    exp(A)	Take the natural exponential.
    exp10(A)	Take the base 10 exponential.
    log(A)	Take the natural logarithm.
    log10(A)	Take the base 10 logarithm.
    power(FO,F)	Raise a field output object to a power.
    radianToDegree(A)	Convert radians to degrees.
    sin(A)	Take the sine.
    sqrt(A)	Take the square root.
    tan(A)	Take the tangent.
    """
    funcs_dict = {
        #'numpy' : ('Inf', 'Infinity', 'NaN', 'abs', 'add', 'all', 'allclose', 'angle', 'any', 'append', 'arange',
        #           'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin',
        #           'argsort', 'argwhere', 'around', 'array', 'array_equal', 'array_equiv', 'asarray', 'atleast_1d', 'atleast_2d',
        #           'atleast_3d', 'average', 'bartlett', 'base_repr', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool8', 'broadcast', 'broadcast_arrays', 'broadcast_shapes', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'ceil', 'choose', 'clip', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex128', 'complex64', 'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma',
        #           'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip', 'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'gcd', 'generic', 'genfromtxt', 'geomspace', 'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'half', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubdtype', 'issubsctype', 'iterable', 'kaiser', 'kron', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum', 'mintypecode', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'numarray', 'number', 'obj2sctype', 'object0', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'place', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 'polyval', 'positive', 'power', 'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'quantile', 'rad2deg', 'radians', 'random', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'row_stack', 'savetxt', 'searchsorted', 'setdiff1d', 'setxor1d', 'shape', 'sign', 'sin', 'sinc', 'sinh', 'sometrue', 'sort', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'sum', 'swapaxes', 'tan', 'tanh', 'tensordot', 'tile', 'transpose', 'trapz', 'union1d', 'unique', 'vdot', 'vectorize', 'vsplit', 'vstack', 'where', 'zeros'),
        'numpy': ('abs', 'arccos', 'arcsin', 'arctan', 'cos', 'degrees',
                  'radians', 'exp', 'log', 'log10', 'power', 'sqrt', 'tan'),
        'scipy.special': ('exp10', ),
    }
    i = 0
    modules_form = []
    module_map = {}
    for mod in modules:
        mod_name, module, func_list, func_list2 = mod
        if mod_name in funcs_dict:
            func_list.extend(funcs_dict[mod_name])
        else:
            # load the functions into func_list
            continue
            load_module_functions(module, func_list, exclusion_set)
        exclusion_set.update(set(func_list))

        # build the lookup table
        modules_form.append([mod_name, None, func_list2])
        for func in func_list:
            module_map[i] = (module, func)
            func_list2.append((func, i, []))
            i += 1

    #for func in np_funcs:
    #func_list2.append((func, i, []))
    #if i > 3:
    #break
    #for func in np_linalg_funcs:
    #np_linalg_funcs2.append((func, i, []))
    #i += 1
    print(np_funcs)

    #modules_form = [
    #['Geometry', None, [
    #('NodeID', 0, []),
    #('ElementID', 1, []),
    #('PropertyID', 2, []),
    #('MaterialID', 3, []),
    #]]
    #]
    #modules_form = ['Modules', None, [
    #['numpy', None, [
    #[
    #('DataSource', 0, []),
    #('Datetime64', 1, []),
    #('Inf', 2, []),
    #('Infinity', 3, []),
    #]]
    #]]
    #]

    #[0, 1, 2, 3, 4, 5, 6, 7, 8]
    main_window = CalculatorWindow(data2,
                                   modules_form=(module_map, modules_form),
                                   fringe_cases=form)
    main_window.show()
    # Enter the main loop
    app.exec_()
Esempio n. 13
0
    def __init__(self, sys_argv):
        super().__init__()
        self.__m_vtkFboItem = None
        #sys_argv += ['--style', 'Material'] #! MUST HAVE
        #sys_argv += ['--style', 'Fusion'] #! MUST HAVE
        sys_argv += ['--style', 'Windows']  #! MUST HAVE

        QApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
        QtGui.QSurfaceFormat.setDefaultFormat(
            defaultFormat(False))  # from vtk 8.2.0
        app = QApplication(sys_argv)
        app.setApplicationName("QtQuickVTK")
        app.setWindowIcon(QIcon(":/resources/bq.ico"))
        app.setOrganizationName("Sexy Soft")
        app.setOrganizationDomain("www.sexysoft.com")

        engine = QQmlApplicationEngine()
        app.setApplicationName('QtVTK-Py')

        # Register QML Types
        qmlRegisterType(FboItem, 'QtVTK', 1, 0, 'VtkFboItem')

        # Expose/Bind Python classes (QObject) to QML
        ctxt = engine.rootContext()  # returns QQmlContext
        ctxt.setContextProperty('canvasHandler', self)
        self.dataProvider = ChartDataProvider()
        ctxt.setContextProperty('chartDataProvider', self.dataProvider)

        # Load main QML file
        engine.load(QUrl.fromLocalFile('resources/main.qml'))

        # Get reference to the QVTKFramebufferObjectItem in QML
        rootObject = engine.rootObjects()[0]  # returns QObject
        self.__m_vtkFboItem = rootObject.findChild(FboItem, 'vtkFboItem')

        # Give the vtkFboItem reference to the CanvasHandler
        if (self.__m_vtkFboItem):
            qDebug(
                'CanvasHandler::CanvasHandler: setting vtkFboItem to CanvasHandler'
            )
            self.__m_vtkFboItem.rendererInitialized.connect(
                self.startApplication)
        else:
            qCritical(
                'CanvasHandler::CanvasHandler: Unable to get vtkFboItem instance'
            )
            return

        MySettings = QSettings()

        print("load Settings")

        self.fileDialog = rootObject.findChild(QObject, "myFileDialog")
        if (self.fileDialog is not None):
            tmp = MySettings.value(CanvasHandler.DEFAULT_MODEL_DIR_KEY)
            print(tmp)
            self.fileDialog.setProperty("folder", QUrl.fromLocalFile(tmp))

        rc = app.exec_()
        qDebug(
            f'CanvasHandler::CanvasHandler: Execution finished with return code: {rc}'
        )
Esempio n. 14
0
def test_tomoworkflow():
    read = read_APS2BM()
    read.path.value = '/Users/hari/test.hdf'
    read.sino.value = (1050, 1051)

    norm = Normalize()
    read.arr.connect(norm.arr)
    read.flat.connect(norm.flats)
    read.dark.connect(norm.darks)

    outliers = RemoveOutlier()
    norm.normalized.connect(outliers.arr)
    outliers.dif.value = 500
    outliers.size.value = 5

    # maximum = ArrayMax()
    # outliers.corrected.connect(maximum.arr)
    # maximum.floor.value = 1e-16

    # neglog = MinusLog()
    # maximum.out.connect(neglog.arr)

    # phase = RetrievePhase()
    # maximum.out.connect(phase.arr)
    # phase.pixel_size.value=6.5e-5
    # phase.dist.value=3
    # phase.energy.value=27

    stripe = RemoveStripeFw()
    outliers.corrected.connect(stripe.tomo)
    stripe.level.value = 8
    stripe.wname.value = 'db5'
    stripe.sigma.value = 4
    stripe.pad.value = True

    padding = Pad()
    stripe.corrected.connect(padding.arr)
    padding.axis.value = 2
    padding.npad.value = 448
    padding.mode.value = 'edge'

    # angles = Angles()
    # angles.nang.value=0
    # angles.ang1.value=90
    # angles.ang2.value=180


    gridrec = Recon()
    padding.padded.connect(gridrec.tomo)
    read.angles.connect(gridrec.theta)
    gridrec.filter_name.value = 'butterworth'
    gridrec.algorithm.value = 'gridrec'
    gridrec.center.value = np.array([1295 + 448])  # 1295
    gridrec.filter_par.value = np.array([0.2, 2])
    # gridrec.sinogram_order.value = True

    crop = Crop()
    gridrec.reconstructed.connect(crop.arr)
    crop.p11.value = 448
    crop.p22.value = 448
    crop.p12.value = 448
    crop.p21.value = 448
    crop.axis.value = 0

    divide = ArrayDivide()

    circularmask = CircMask()
    crop.croppedarr.connect(circularmask.arr)
    circularmask.val.value = 0
    circularmask.axis.value = 0
    circularmask.ratio.value = 1

    writetiff = WriteTiffStack()

    workflow = Workflow('Tomography')
    for process in [read,
                    norm,
                    outliers,
                    # maximum,
                    # neglog,
                    # phase,
                    stripe,
                    padding,
                    # angles,
                    gridrec,
                    crop,
                    # divide,
                    circularmask,
                    # writetiff
                    ]:
        workflow.addProcess(process)

    dsk = DaskExecutor()
    result = dsk.execute(workflow)
    print(result)

    import pyqtgraph as pg
    pg.image(result[0]['normalized'].value.squeeze())

    from qtpy.QtWidgets import QApplication
    app = QApplication([])
    app.exec_()
Esempio n. 15
0
class ShapeViewerQt(QMainWindow):
    """
    Simple class for viewing items using Qt.

    :param int width: Window width.
    :param int height: Window height.
    :param PySide.QtGui.QWidget parent: The parent widget.
    """
    def __init__(self, width=800, height=600, parent=None):
        # Start app
        self._app = QApplication.instance()
        if self._app is None:
            self._app = QApplication([])
        super(ShapeViewerQt, self).__init__(parent)

        # Window settings
        self.setWindowTitle('pyOCCT')
        _icon = os.path.dirname(__file__) + '/_resources/icon.png'
        _qicon = QIcon(_icon)
        self.setWindowIcon(_qicon)

        # Create the OCCT view
        frame = QFrame(self)
        layout = QVBoxLayout(frame)
        layout.setContentsMargins(0, 0, 0, 0)
        self._the_view = QOpenCascadeWidget(self)
        layout.addWidget(self._the_view)
        self.setCentralWidget(frame)
        self.show()
        self.resize(width, height)
        self.view.my_view.MustBeResized()

    @property
    def view(self):
        return self._the_view

    def _continue(self, *args):
        self._app.exit()

    def keyPressEvent(self, e):
        if e.key() == ord('F'):
            self.view.fit()
        elif e.key() == ord('0'):
            self.view.view_iso()
        elif e.key() == ord('1'):
            self.view.view_front()
        elif e.key() == ord('2'):
            self.view.view_top()
        elif e.key() == ord('3'):
            self.view.view_right()
        elif e.key() == ord('4'):
            self.view.view_rear()
        elif e.key() == ord('5'):
            self.view.view_bottom()
        elif e.key() == ord('6'):
            self.view.view_left()
        elif e.key() == ord('S'):
            self.view.set_display_mode('s')
        elif e.key() == ord('W'):
            self.view.set_display_mode('w')
        elif e.key() == ord('C'):
            self._continue()
        else:
            print('Key is not mapped to anything.')

    def display_shape(self,
                      shape,
                      rgb=None,
                      transparency=None,
                      material=Graphic3d_NOM_DEFAULT):
        """
        Display a shape.

        :param OCCT.TopoDS.TopoDS_Shape shape: The shape.
        :param rgb: The RGB color (r, g, b).
        :type rgb: collections.Sequence[float] or OCCT.Quantity.Quantity_Color
        :param float transparency: The transparency (0 to 1).
        :param OCCT.Graphic3d.Graphic3d_NameOfMaterial material: The material.

        :return: The AIS_Shape created for the part.
        :rtype: OCCT.AIS.AIS_Shape
        """
        return self.view.display_shape(shape, rgb, transparency, material)

    def add(self,
            entity,
            rgb=None,
            transparency=None,
            material=Graphic3d_NOM_DEFAULT):
        """
        Add an entity to the view.

        :param entity: The entity.
        :param rgb: The RGB color (r, g, b).
        :type rgb: collections.Sequence[float] or OCCT.Quantity.Quantity_Color
        :param float transparency: The transparency (0 to 1).
        :param OCCT.Graphic3d.Graphic3d_NameOfMaterial material: The material.

        :return: The AIS_Shape created for the entity. Returns *None* if the
            entity cannot be converted to a shape.
        :rtype: OCCT.AIS.AIS_Shape or None
        """
        if isinstance(entity, TopoDS_Shape):
            return self.view.display_shape(entity, rgb, transparency, material)
        elif isinstance(entity, (gp_Pnt, Geom_Curve, Geom_Surface)):
            return self.view.display_geom(entity, rgb, transparency, material)
        else:
            return None

    def clear(self):
        """
        Clear contents of the view.

        :return: None.
        """

        self.view.remove_all()

    def start(self, fit=True):
        """
        Start the viewer.

        :param bool fit: Option to fit contents.

        :return: None.
        """
        print('Press \"c\" to continue...')

        if fit:
            self.view.fit()
        self._app.exec_()
Esempio n. 16
0
def main():
    # First, some boilerplate to make a super-minimal Qt application that we want
    # to add some bluesky-widgets components into.
    app = QApplication(["Some App"])
    window = QMainWindow()
    central_widget = QWidget(window)
    window.setCentralWidget(central_widget)
    central_widget.setLayout(QVBoxLayout())
    central_widget.layout().addWidget(QLabel("This is part of the 'original' app."))
    window.show()

    # *** INTEGRATION WITH BLUESKY-WIDGETS STARTS HERE. ***

    # Ensure that any background workers started by bluesky-widgets stop
    # gracefully when the application closes.
    from bluesky_widgets.qt.threading import wait_for_workers_to_quit

    app.aboutToQuit.connect(wait_for_workers_to_quit)

    # Model a list of figures.
    # This will generate line plot automatically based on the structure (shape)
    # of the data and its hints. Other models could be used for more explicit
    # control of what gets plotted. See the examples in
    # http://blueskyproject.io/bluesky-widgets/reference.html#plot-builders
    from bluesky_widgets.models.auto_plot_builders import AutoLines

    model = AutoLines(max_runs=3)

    # Feed it data from the RunEngine. In actual practice, the RunEngine should
    # be in a separate process and we should be receiving these documents
    # over a network via publish--subscribe. See
    # bluesky_widgets.examples.advanced.qt_viewer_with_search for an example of
    # that. Here, we keep it simple.
    from bluesky_widgets.utils.streaming import stream_documents_into_runs
    from bluesky import RunEngine

    RE = RunEngine()
    RE.subscribe(stream_documents_into_runs(model.add_run))

    # Add a tabbed pane of figures to the app.
    from bluesky_widgets.qt.figures import QtFigures

    view = QtFigures(model.figures)  # view is a QWidget
    central_widget.layout().addWidget(view)

    # When the model receives data or is otherwise updated, any changes to
    # model.figures will be reflected in changes to the view.

    # Just for this example, generate some data before starting this app.
    # Again, in practice, this should happen in a separate process and send
    # the results over a network.

    from bluesky.plans import scan
    from ophyd.sim import motor, det

    def plan():
        for i in range(1, 5):
            yield from scan([det], motor, -1, 1, 1 + 2 * i)

    RE(plan())

    # *** INTEGRATION WITH BLUESKY-WIDGETS ENDS HERE. ***

    # Run the app.
    app.exec_()
Esempio n. 17
0
            
            hcam.startRecording()
            
        
        finally:
            
            dcam.dcamcap_stop(hcam.camera_handle)

            error_uninit = dcam.dcamapi_uninit()
            
            if (error_uninit != DCAMERR_NOERROR):
                raise DCAMException("DCAM uninitialization failed with error code " + str(error_uninit))
        

    if sys.flags.interactive !=1 or not hasattr(qtpy.QtCore, 'PYQT_VERSION'):
            QApplication.exec_()
    
    
    
    
    
    #start = hcam.startAcquisition()

#     start = hcam.startAcquisition()
#     stop = hcam.stopAcquisition()
#    print(start, stop)
# Testing.
#
# if (__name__ == "__main__"):
# 
#     import time
Esempio n. 18
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("objects",
                        type=str,
                        nargs="+",
                        help="Files or directories to load.")
    parser.add_argument("-ns", "--no-segmentations", action="store_true")
    parser.add_argument("-nm", "--no-memmap", action="store_true")
    parser.add_argument("--column-kwargs", default="{}")
    parser.add_argument("--row-kwargs", default="{}")
    parser.add_argument("--volume-kwargs", default="{}")
    args = parser.parse_args()

    column_kwargs = json.loads(args.column_kwargs)
    row_kwargs = json.loads(args.row_kwargs)
    volume_kwargs = json.loads(args.volume_kwargs)
    mmap = None if args.no_memmap else "r"

    app = QApplication(sys.argv)

    data = []
    labels = []

    for o, obj in enumerate(args.objects):

        current_data = np.load(obj, mmap)
        current_label = os.path.basename(obj).split(".")[0]

        if o >= 1 and current_data.ndim != data[-1].ndim:
            raise IndexError(
                "All loaded datasets must have the same dimensionality.")

        if current_data.ndim not in (3, 4, 5):
            raise IndexError(
                "Can only load datasets with dimension 3, 4 or 5.")

        if o >= 1 and current_data.ndim >= 5:
            raise IndexError(
                "When loading multiple datasets, the dimensionality of each can't be greater than 4."
            )

        if current_data.ndim == 4:
            current_label = [
                current_label + "-" + str(i)
                for i in range(current_data.shape[0])
            ]

        if current_data.ndim == 5:
            col_label = []
            for i in range(current_data.shape[0]):
                row_label = []
                for j in range(current_data.shape[1]):
                    row_label.append(current_label + "-" +
                                     "{},{}".format(i, j))
                col_label.append(row_label)
            current_label = col_label

        data.append(current_data)
        labels.append(current_label)

    data = np.array(data)

    if data.ndim == 4:
        data = data[np.newaxis, ...]
        labels = [labels]

    if data.ndim == 6:
        data = data[0]
        labels = labels[0]

    main = make_gridview(data,
                         labels=labels,
                         identify_segmentations=not args.no_segmentations,
                         column_kwargs=column_kwargs,
                         row_kwargs=row_kwargs,
                         volume_kwargs=volume_kwargs)

    main.show()

    sys.exit(app.exec_())
Esempio n. 19
0
def main():
    from pyNastran.bdf.bdf import BDF
    model = BDF()

    pid = 1
    model.add_pshell(pid,
                     mid1=1,
                     t=0.1,
                     mid2=None,
                     twelveIt3=1.0,
                     mid3=None,
                     tst=0.833333,
                     nsm=0.0,
                     z1=None,
                     z2=None,
                     mid4=None,
                     comment='')

    pid = 2
    mids = [1, 2]
    thicknesses = [0.1, 0.2]
    thetas = None
    model.add_pcomp(pid,
                    mids,
                    thicknesses,
                    thetas=thetas,
                    souts=None,
                    nsm=0.,
                    sb=0.,
                    ft=None,
                    tref=0.,
                    ge=0.,
                    lam=None,
                    z0=None,
                    comment='')

    pid = 3
    mids = [1, 2]
    thicknesses = [0.1, 0.2]
    thetas = None
    model.add_pcomp(pid,
                    mids,
                    thicknesses,
                    thetas=thetas,
                    souts=None,
                    nsm=0.,
                    sb=0.,
                    ft=None,
                    tref=0.,
                    ge=0.,
                    lam='SYM',
                    z0=0.,
                    comment='')

    pid = 5
    mid = 1
    Type = 'BOX'
    dim = [2., 1., 0.2, 0.1]
    model.add_pbarl(pid, mid, Type, dim)
    model.validate()

    pid = 6
    mid = 1
    Type = 'BAR'
    dim = [2., 1.]
    model.add_pbarl(pid, mid, Type, dim)
    model.validate()

    import sys
    from qtpy.QtWidgets import QApplication
    app = QApplication(sys.argv)
    window = PropertyPlotter(model, parent=None)

    # Enter the main loop
    app.exec_()
Esempio n. 20
0
def main():
    app = QApplication([])
    main_window = MainWindow()
    main_window.show()
    app.exec_()
Esempio n. 21
0
def main():
    """Execute QDarkStyle example."""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--qt_from',
        default='qtpy',
        type=str,
        choices=[
            'pyqt5', 'pyqt', 'pyside2', 'pyside', 'qtpy', 'pyqtgraph', 'qt.py'
        ],
        help=
        "Choose which binding and/or abstraction is to be used to run the example."
    )
    parser.add_argument(
        '--no_dark',
        action='store_true',
        help="Exihibts the original window (without qdarkstyle).")
    parser.add_argument('--test',
                        action='store_true',
                        help="Auto close window after 2s.")
    parser.add_argument('--reset',
                        action='store_true',
                        help="Reset GUI settings (position, size) then opens.")
    parser.add_argument('--screenshots',
                        action='store_true',
                        help="Generate screenshots on images folder.")

    # Parsing arguments from command line
    args = parser.parse_args()

    # To avoid problems when testing without screen
    if args.test or args.screenshots:
        os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    # Set QT_API variable before importing QtPy
    if args.qt_from in ['pyqt', 'pyqt5', 'pyside', 'pyside2']:
        os.environ['QT_API'] = args.qt_from
    elif args.qt_from == 'pyqtgraph':
        os.environ['QT_API'] = os.environ['PYQTGRAPH_QT_LIB']
    elif args.qt_from in ['qt.py', 'qt']:
        try:
            import Qt
        except ImportError:
            print('Could not import Qt (Qt.Py)')
        else:
            os.environ['QT_API'] = Qt.__binding__

    # QtPy imports
    from qtpy import API_NAME, QT_VERSION, PYQT_VERSION, PYSIDE_VERSION
    from qtpy import __version__ as QTPY_VERSION
    from qtpy.QtWidgets import (QApplication, QMainWindow, QDockWidget,
                                QStatusBar, QLabel, QPushButton, QMenu)
    from qtpy.QtCore import QTimer, Qt, QSettings

    # Set API_VERSION variable
    API_VERSION = ''

    if PYQT_VERSION:
        API_VERSION = PYQT_VERSION
    elif PYSIDE_VERSION:
        API_VERSION = PYSIDE_VERSION
    else:
        API_VERSION = 'Not found'

    # Import examples UI
    from mw_menus_ui import Ui_MainWindow as ui_main

    from dw_buttons_ui import Ui_DockWidget as ui_buttons
    from dw_displays_ui import Ui_DockWidget as ui_displays
    from dw_inputs_fields_ui import Ui_DockWidget as ui_inputs_fields
    from dw_inputs_no_fields_ui import Ui_DockWidget as ui_inputs_no_fields

    from dw_widgets_ui import Ui_DockWidget as ui_widgets
    from dw_views_ui import Ui_DockWidget as ui_views
    from dw_containers_tabs_ui import Ui_DockWidget as ui_containers_tabs
    from dw_containers_no_tabs_ui import Ui_DockWidget as ui_containers_no_tabs

    # create the application
    app = QApplication(sys.argv)
    app.setOrganizationName('QDarkStyle')
    app.setApplicationName('QDarkStyle Example')

    style = ''

    if not args.no_dark:
        style = qdarkstyle.load_stylesheet()

    app.setStyleSheet(style)

    # create main window
    window = QMainWindow()
    window.setObjectName('mainwindow')

    ui = ui_main()
    ui.setupUi(window)

    title = ("QDarkStyle Example - " + "(QDarkStyle=v" +
             qdarkstyle.__version__ + ", QtPy=v" + QTPY_VERSION + ", " +
             API_NAME + "=v" + API_VERSION + ", Qt=v" + QT_VERSION +
             ", Python=v" + platform.python_version() + ")")

    _logger.info(title)

    window.setWindowTitle(title)

    # Create docks for buttons
    dw_buttons = QDockWidget()
    dw_buttons.setObjectName('buttons')
    ui_buttons = ui_buttons()
    ui_buttons.setupUi(dw_buttons)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_buttons)

    # Add actions on popup toolbuttons
    menu = QMenu()

    for action in ['Action A', 'Action B', 'Action C']:
        menu.addAction(action)

    ui_buttons.toolButtonDelayedPopup.setMenu(menu)
    ui_buttons.toolButtonInstantPopup.setMenu(menu)
    ui_buttons.toolButtonMenuButtonPopup.setMenu(menu)

    # Create docks for buttons
    dw_displays = QDockWidget()
    dw_displays.setObjectName('displays')
    ui_displays = ui_displays()
    ui_displays.setupUi(dw_displays)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_displays)

    # Create docks for inputs - no fields
    dw_inputs_no_fields = QDockWidget()
    dw_inputs_no_fields.setObjectName('inputs_no_fields')
    ui_inputs_no_fields = ui_inputs_no_fields()
    ui_inputs_no_fields.setupUi(dw_inputs_no_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_no_fields)

    # Create docks for inputs - fields
    dw_inputs_fields = QDockWidget()
    dw_inputs_fields.setObjectName('inputs_fields')
    ui_inputs_fields = ui_inputs_fields()
    ui_inputs_fields.setupUi(dw_inputs_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_fields)

    # Create docks for widgets
    dw_widgets = QDockWidget()
    dw_widgets.setObjectName('widgets')
    ui_widgets = ui_widgets()
    ui_widgets.setupUi(dw_widgets)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_widgets)

    # Create docks for views
    dw_views = QDockWidget()
    dw_views.setObjectName('views')
    ui_views = ui_views()
    ui_views.setupUi(dw_views)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_views)

    # Create docks for containers - no tabs
    dw_containers_no_tabs = QDockWidget()
    dw_containers_no_tabs.setObjectName('containers_no_tabs')
    ui_containers_no_tabs = ui_containers_no_tabs()
    ui_containers_no_tabs.setupUi(dw_containers_no_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_no_tabs)

    # Create docks for containters - tabs
    dw_containers_tabs = QDockWidget()
    dw_containers_tabs.setObjectName('containers_tabs')
    ui_containers_tabs = ui_containers_tabs()
    ui_containers_tabs.setupUi(dw_containers_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_tabs)

    # Tabify right docks
    window.tabifyDockWidget(dw_buttons, dw_displays)
    window.tabifyDockWidget(dw_displays, dw_inputs_fields)
    window.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields)

    # Tabify left docks
    window.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs)
    window.tabifyDockWidget(dw_containers_tabs, dw_widgets)
    window.tabifyDockWidget(dw_widgets, dw_views)

    # Issues #9120, #9121 on Spyder
    qstatusbar = QStatusBar()
    qstatusbar.addWidget(
        QLabel('Issue Spyder #9120, #9121 - background not matching.'))
    qstatusbar.addWidget(QPushButton('OK'))

    # Add info also in status bar for screenshots get it
    qstatusbar.addWidget(QLabel('INFO: ' + title))
    window.setStatusBar(qstatusbar)

    # Todo: add report info and other info in HELP graphical

    # Auto quit after 2s when in test mode
    if args.test:
        QTimer.singleShot(2000, app.exit)

    # Save screenshots for different displays and quit
    if args.screenshots:
        window.showFullScreen()
        create_screenshots(app, window, args.no_dark)
    # Do not read settings when taking screenshots - like reset
    else:
        _read_settings(window, args.reset, QSettings)
        window.showMaximized()

    app.exec_()
    _write_settings(window, QSettings)
Esempio n. 22
0
        self.line_for_typing.setFocus()
        self.display_result()

    def update_typing(self):
        """Typing 정보를 갱신한다."""
        typing = self.typing
        typing.update_time()
        is_correct, err_str = typing.check_result(self.line_for_typing.text())

        if is_correct:
            self.new_game()
            self.line_for_error.setText("")

        self.line_for_error.setText(err_str)


if __name__ == "__main__":
    APP = QApplication(sys.argv)
    style_sheet = qdarkstyle.load_stylesheet_pyqt5()
    APP.setStyleSheet(style_sheet)

    FONT = QFont("D2Coding ligature", 15)
    FONT.setStyleHint(QFont.Monospace)
    APP.setFont(FONT)

    MAIN_WINDOW = MainWindowTyping()

    MAIN_WINDOW.show()

    sys.exit(APP.exec_())
Esempio n. 23
0
def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())
Esempio n. 24
0
def main():
    from qtpy.QtWidgets import QApplication
    app = QApplication([])
    test = ProjectConfig()
    test.show()
    app.exec_()
Esempio n. 25
0
def main(*args, **kwargs):
    """ Runs the XSpecGui on an input file
    """
    import argparse

    parser = argparse.ArgumentParser(
        description=
        'Parser for lt_xspec v1.2; \n Note: Extra arguments are passed to read_spec (e.g. --flux_tag=FX)'
    )
    parser.add_argument(
        "file",
        type=str,
        help="Spectral file; specify extension by appending #exten#")
    parser.add_argument(
        "-guessfile",
        "--guessfile",
        type=str,
        help=
        "Igmguesses file, see https://github.com/pyigm/pyigm/blob/master/docs/igmguesses.rst "
    )
    parser.add_argument("-z", "--zsys", type=float, help="System Redshift")
    parser.add_argument(
        "--norm",
        help="Show spectrum continuum normalized (if continuum is provided)",
        action="store_true")
    parser.add_argument(
        "--air",
        default=False,
        help="Convert input spectrum wavelengths from air to vacuum",
        action="store_true")
    parser.add_argument("--exten", type=int, help="FITS extension")
    parser.add_argument(
        "--splice",
        type=str,
        help="Splice with the input file; extension convention applies")
    parser.add_argument("--scale",
                        type=float,
                        help="Scale factor for GUI size [1. is default]")
    #parser.add_argument("--wave_tag", type=str, help="Tag for wave in Table")
    #parser.add_argument("--flux_tag", type=str, help="Tag for flux in Table")
    #parser.add_argument("--sig_tag", type=str, help="Tag for sig in Table")
    #parser.add_argument("--var_tag", type=str, help="Tag for var in Table")
    #parser.add_argument("--ivar_tag", type=str, help="Tag for ivar in Table")

    #pargs = parser.parse_args()
    pargs, unknown = parser.parse_known_args()

    from qtpy.QtWidgets import QApplication
    from linetools.guis.xspecgui import XSpecGui

    # Normalized?
    if pargs.norm is True:
        norm = True
    else:
        norm = False

    # Extension
    file = pargs.file
    if pargs.file[-1] == '#':
        prs = pargs.file.split('#')
        exten = int(prs[1])
        file = prs[0]
    else:
        exten = (pargs.exten if hasattr(pargs, 'exten') else 0)

    # zsys
    zsys = (pargs.zsys if hasattr(pargs, 'zsys') else None)

    # guesses
    guessfile = (pargs.guessfile if hasattr(pargs, 'guessfile') else None)

    # Splice?
    if pargs.splice is not None:
        pdb.set_trace()
        if pargs.splice[-1] == '#':
            prs = pargs.splice.split('#')
            exten = [exten, int(prs[1])]
            file = [file, prs[0]]
        else:
            exten = [exten, None]
            file = [file, pargs.splice]

    # Read spec keywords
    rsp_kwargs = {}
    for arg in unknown:
        spl = arg.split('=')
        rsp_kwargs[spl[0][2:]] = spl[1]

    # GUI
    app = QApplication(sys.argv)

    # Scale
    if pargs.scale is None:
        # Screen dimensions
        width = app.desktop().screenGeometry().width()
        scale = 2. * (width / 3200.)
    else:
        scale = pargs.scale
    #
    gui = XSpecGui(file,
                   guessfile=guessfile,
                   zsys=zsys,
                   norm=norm,
                   exten=exten,
                   rsp_kwargs=rsp_kwargs,
                   air=pargs.air,
                   screen_scale=scale)
    gui.show()
    app.exec_()
Esempio n. 26
0
def test():
    """ """
    app = QApplication([])
    win = TestWindow()
    win.show()
    app.exec_()
Esempio n. 27
0
def run():
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())
Esempio n. 28
0
        layout.addWidget(self.l3, 2, 0)

        layout.addWidget(self.lb1, 3, 0)
        layout.addWidget(self.lb2, 4, 0)
        layout.addWidget(self.lb3, 5, 0)
        center.setLayout(layout)


def run():
    time.sleep(5)
    for i in range(1000000):
        mw.l1.setText("aaaa%s" % i)
        mw.l2.setText("bbbb%s" % i)
        mw.l3.setText("cccc%s" % i)

        mw.lb1.setText("aaaa%s" % i)
        mw.lb2.setText("bbbb%s" % i)
        mw.lb3.setText("cccc%s" % i)
        time.sleep(1)


qApp = QApplication([])
mw = MainWindow()

mw.show()

t1 = Thread(target=run)
t1.start()

sys.exit(qApp.exec_())
Esempio n. 29
0
def main():
    qapp = QApplication(sys.argv)
    exp_widget = ExpWidget()
    exp_widget.show()
    sys.exit(qapp.exec_())
Esempio n. 30
0
    def showLabel(self, item, points):
        if self._curvepoint:
            self.scene().removeItem(self._arrow)
            self.scene().removeItem(self._text)

        point = points[0]
        self._curvepoint = pg.CurvePoint(item.curve)
        self.addItem(self._curvepoint)
        self._arrow = pg.ArrowItem(angle=90)
        self._arrow.setParentItem(self._curvepoint)
        self._arrow.setZValue(10000)
        self._text = pg.TextItem(item.name(),
                                 anchor=(0.5, -1.0),
                                 border=pg.mkPen("w"),
                                 fill=pg.mkBrush("k"))
        self._text.setParentItem(self._curvepoint)

        self._curvepoint.setIndex(list(item.scatter.points()).index(point))


if __name__ == "__main__":
    qapp = QApplication([])
    w = CurveLabels()
    for i in range(10):
        pen = pg.mkColor((i, 10))
        w.plot(np.random.random((100, )) + i * 0.5, name=str(i), pen=pen)

    w.show()

    qapp.exec_()
Esempio n. 31
0
def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()
Esempio n. 32
0
            slider_max = gr.bottom() - slider_length + 1

        return style.sliderValueFromPosition(self.minimum(), self.maximum(),
                                             pos - slider_min,
                                             slider_max - slider_min,
                                             opt.upsideDown)


if __name__ == "__main__":
    import sys

    # kills the program when you hit Cntl+C from the command line
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    def echo(value):
        print(value)

    app = QApplication(sys.argv)
    slider = RangeSlider(Qt.Horizontal)
    slider.setMinimum(0)
    slider.setMaximum(10000)
    slider.setLow(0)
    slider.setHigh(10000)
    slider.setTickPosition(QSlider.TicksBelow)
    #slider.connect(QtCore.SIGNAL('sliderMoved(int)'), echo)
    slider.sliderMoved.connect(echo)
    slider.show()
    slider.raise_()
    app.exec_()
Esempio n. 33
0
def main():
    from qtpy.QtWidgets import QApplication
    app = QApplication([])
    test = Trimmer()
    test.show()
    app.exec_()
Esempio n. 34
0
def new_figure_manager_given_figure(num, figure):
    """
    Create a new figure manager instance for the given figure.
    """
    canvas = FigureCanvasQTAgg(figure)
    manager = FigureManagerWorkbench(canvas, num)
    return manager


if __name__ == '__main__':
    # testing code
    import numpy as np
    qapp = QApplication([' '])
    qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    x = np.linspace(0, 10*np.pi, 1000)
    cx, sx = np.cos(x), np.sin(x)
    fig_mgr_1 = new_figure_manager(1)
    fig1 = fig_mgr_1.canvas.figure
    ax = fig1.add_subplot(111)
    ax.set_title("Test title")
    ax.set_xlabel("$\mu s$")
    ax.set_ylabel("Counts")

    ax.plot(x, cx)
    fig1.show()
    qapp.exec_()
Esempio n. 35
0
    @xmax.setter
    def xmax(self, value):
        xmin = self.ax1.get_xlim()[0]
        self.ax1.set_xlim(xmin, value)

    # ymin property
    @property
    def ymin(self):
        return self.ax1.get_ylim()[0]

    @ymin.setter
    def ymin(self, value):
        ymax = self.ax1.get_ylim()[1]
        self.ax1.set_ylim(value, ymax)

    # ymax property
    @property
    def ymax(self):
        return self.ax1.get_ylim()[1]

    @ymax.setter
    def ymax(self, value):
        ymin = self.ax1.get_ylim()[0]
        self.ax1.set_ylim(ymin, value)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = PlotWidget()
    w.show()
    app.exec_()
Esempio n. 36
0
def opensesame():

	import os, sys, platform
	# Add the folder that contains the OpenSesame modules to the path. This is
	# generally only necessary if OpenSesame is directly run from source,
	# instead from an installation.
	if os.path.exists(os.path.join(os.getcwd(), 'libopensesame')):
		sys.path.insert(0, os.getcwd())
	# Support for multiprocessing when packaged
	# In OS X the multiprocessing module is horribly broken, but a fixed
	# version has been released as the 'billiard' module
	if platform.system() == 'Darwin':
		# Use normal multirpocessing module from python 3.4 and on
		if sys.version_info >= (3,4):
			from multiprocessing import freeze_support, set_start_method
			freeze_support()
			set_start_method('forkserver')
		else:
			from billiard import freeze_support, forking_enable
			freeze_support()
			forking_enable(0)
	else:
		from multiprocessing import freeze_support
		freeze_support()
	# Parse the (optional) environment file that contains special paths, etc.
	from libopensesame.misc import resource, filesystem_encoding, \
		parse_environment_file
	parse_environment_file()
	# Force the new-style Qt API
	import sip
	import qtpy
	sip.setapi('QString', 2)
	sip.setapi('QVariant', 2)
	# Load debug package (this must be after the working directory change)
	from libopensesame import debug
	# Do the basic window initialization
	from qtpy.QtWidgets import QApplication
	# From Qt 5.6 on, QtWebEngine is the default way to render web pages
	# QtWebEngineWidgets must be imported before a QCoreApplication instance is
	# created.
	try:
		from qtpy import QtWebEngineWidgets
	except ImportError:
		pass
	app = QApplication(sys.argv)
	# Enable High DPI display with PyQt5
	if hasattr(qtpy.QtCore.Qt, 'AA_UseHighDpiPixmaps'):
		app.setAttribute(qtpy.QtCore.Qt.AA_UseHighDpiPixmaps)
	from libqtopensesame.qtopensesame import qtopensesame
	opensesame = qtopensesame(app)
	opensesame.__script__ = __file__
	app.processEvents()
	# Install the translator. For some reason, the translator needs to be
	# instantiated here and not in the set_locale() function, otherwise the	
	# locale is ignored.
	from qtpy.QtCore import QTranslator
	translator = QTranslator()
	opensesame.set_locale(translator)
	# Now that the window is shown, load the remaining modules and resume the
	# GUI initialization.
	opensesame.resume_init()
	opensesame.restore_window_state()
	opensesame.refresh()
	opensesame.show()
	# Added for OS X, otherwise Window will not appear
	opensesame.raise_()
	# Exit using the application exit status
	sys.exit(app.exec_())
Esempio n. 37
0
def main():  # pragma: no cover
    # kills the program when you hit Cntl+C from the command line
    # doesn't save the current state as presumably there's been an error
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    import os
    os.environ['QT_API'] = 'pyside'
    #os.environ['QT_API'] = 'pyqt5'

    import sys
    # Someone is launching this directly
    # Create the QApplication
    app = QApplication(sys.argv)
    #The Main window

    data = {
        'font_size':
        8,
        0:
        Group(name='main',
              element_str='1:#',
              elements_pound='103',
              editable=False),
        1:
        Group(name='wing',
              element_str='1:10',
              elements_pound='103',
              editable=True),
        2:
        Group(name='fuselage1',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        3:
        Group(name='fuselage2',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        4:
        Group(name='fuselage3',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        5:
        Group(name='fuselage4',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        6:
        Group(name='fuselage5',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        7:
        Group(name='fuselage6',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        8:
        Group(name='fuselage7',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        9:
        Group(name='fuselage8',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        10:
        Group(name='fuselage9',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        11:
        Group(name='fuselage10',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        12:
        Group(name='fuselage11',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        13:
        Group(name='fuselage12',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        14:
        Group(name='fuselage13',
              element_str='50:60',
              elements_pound='103',
              editable=True),
        15:
        Group(name='fuselage14',
              element_str='50:60',
              elements_pound='103',
              editable=True),
    }
    main_window = GroupsModify(data, win_parent=None, group_active='main')
    main_window.show()
    # Enter the main loop
    app.exec_()
Esempio n. 38
0
                'Green': QColor(15, 105, 0),
                'Yellow': QColor(210, 205, 0),
                'Orange': QColor(218, 70, 21),
                'Purple': QColor(135, 0, 131),
                'Blue': QColor(0, 3, 154)
            }

            self.leds = []
            for row, shape in enumerate(QLed.shapesdict.keys()):
                for col, color in enumerate(colorsdict.keys()):
                    led = QLed(self)
                    led.setOnColor(colorsdict[color])
                    led.setOffColor(QColor(90, 90, 90))
                    led.setShape(shape)
                    _l.addWidget(led, row, col, Qt.AlignCenter)
                    self.leds.append(led)

            self.toggleLeds()

        def toggleLeds(self):
            """Toggle leds state."""
            for led in self.leds:
                led.toggleState()
            QTimer.singleShot(1000, self.toggleLeds)

    a = QApplication(argv)
    t = Test()
    t.show()
    t.raise_()
    exit(a.exec_())
Esempio n. 39
0
def main(args=None):
    ap = argparse.ArgumentParser(
        usage=__doc__.splitlines()[0],
        epilog="You can also pass any command line arguments supported by Qt.",
    )
    ap.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="Enable debug logging.",
    )
    ap.add_argument(
        "-n",
        "--client-name",
        metavar="NAME",
        default=PROGRAM,
        help="Set JACK client name to NAME (default: '%(default)s')",
    )
    ap.add_argument(
        "-i",
        "--connect-interval",
        type=posnum,
        default=3.0,
        metavar="SECONDS",
        help="Interval between attempts to connect to JACK server "
        " (default: %(default)s)",
    )
    ap.add_argument(
        "-m",
        "--max-attempts",
        type=posnum,
        default=1,
        metavar="NUM",
        help="Max. number of attempts to connect to JACK server "
        "(0=infinite, default: %(default)s)).",
    )
    cargs, args = ap.parse_known_args(args)

    # App initialization
    app = QApplication(args)
    app.setApplicationName(PROGRAM)
    app.setApplicationVersion(__version__)
    app.setOrganizationName(ORGANIZATION)
    app.setWindowIcon(QIcon(":/icons//scalable/qjackcapture.svg"))

    logging.basicConfig(
        level=logging.DEBUG if cargs.debug else logging.INFO,
        format="%(name)s:%(levelname)s: %(message)s",
    )

    if jacklib is None:
        QMessageBox.critical(
            None,
            app.translate(PROGRAM, "Error"),
            app.translate(
                PROGRAM,
                "JACK is not available in this system, cannot use this application.",
            ),
        )
        return 1

    if not gJackCapturePath:
        QMessageBox.critical(
            None,
            app.translate(PROGRAM, "Error"),
            app.translate(
                PROGRAM,
                "The 'jack_capture' application is not available.\n"
                "Is not possible to render without it!",
            ),
        )
        return 2

    try:
        jack_client = QJackCaptureClient(
            cargs.client_name + "-ui",
            connect_interval=cargs.connect_interval,
            connect_max_attempts=cargs.max_attempts,
        )
    except KeyboardInterrupt:
        log.info("Aborted.")
        return 1
    except Exception as exc:
        QMessageBox.critical(
            None,
            app.translate(PROGRAM, "Error"),
            app.translate(
                PROGRAM,
                "Could not connect to JACK, possible reasons:\n%s\n\n"
                "See console log for more information.",
            ) % exc,
        )
        return 1

    # Show GUI
    gui = QJackCaptureMainWindow(None, jack_client, cargs.client_name)
    gui.setWindowIcon(get_icon("media-record", 48))
    gui.show()

    # Main loop
    return app.exec_()
Esempio n. 40
0
        if hdu is None:
            raise Exception("Could not make cutout. "
                "Object may be out of the image's range.")

        if self.session is not None:
            iv = StandaloneImageViewer(hdu.data)
            iv.setWindowFlags(iv.windowFlags() | Qt.Tool)
            iv.show()
        else:
            import matplotlib.pyplot as plt
            plt.imshow(hdu.data)
            plt.show()


@menubar_plugin("Cutout Tool (JWST/NIRSpec MSA)")
def nIRSpec_cutout_tool(session, data_collection):
    ex = NIRSpecCutoutTool(session)
    return

@menubar_plugin("General Purpose Cutout Tool")
def general_cutout_tool(session, data_collection):
    ex = GeneralCutoutTool(session)
    return

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex1 = NIRSpecCutoutTool()
    ex2 = GeneralCutoutTool()
    sys.exit(app.exec_())
Esempio n. 41
0
class ViewerQt(QMainWindow):
    """
    Simple class for viewing items using Qt.

    :param int width: Window width.
    :param int height: Window height.
    :param PySide.QtGui.QWidget parent: The parent widget.
    """
    def __init__(self, width=800, height=600, parent=None):
        # Start app
        self._app = QApplication.instance()
        if self._app is None:
            self._app = QApplication([])
        super(ViewerQt, self).__init__(parent)

        # Window settings
        self.setWindowTitle('pyOCCT')
        _icon = os.path.dirname(__file__) + '/_resources/icon.png'
        _qicon = QIcon(_icon)
        self.setWindowIcon(_qicon)

        # Create the OCCT view
        frame = QFrame(self)
        layout = QVBoxLayout(frame)
        layout.setContentsMargins(0, 0, 0, 0)
        self._the_view = QOpenCascadeWidget()
        layout.addWidget(self._the_view)
        self.setCentralWidget(frame)
        self.show()
        self.resize(width, height)
        self.view.my_view.MustBeResized()

    @property
    def view(self):
        return self._the_view

    def _continue(self, *args):
        self._app.exit()

    def keyPressEvent(self, e):
        if e.key() == ord('F'):
            self.view.fit()
        elif e.key() == ord('0'):
            self.view.view_iso()
        elif e.key() == ord('1'):
            self.view.view_front()
        elif e.key() == ord('2'):
            self.view.view_top()
        elif e.key() == ord('3'):
            self.view.view_right()
        elif e.key() == ord('4'):
            self.view.view_rear()
        elif e.key() == ord('5'):
            self.view.view_bottom()
        elif e.key() == ord('6'):
            self.view.view_left()
        elif e.key() == ord('S'):
            self.view.set_display_mode('s')
        elif e.key() == ord('W'):
            self.view.set_display_mode('w')
        elif e.key() == ord('C'):
            self._continue()
        else:
            print('Key is not mapped to anything.')

    def display_shape(self,
                      shape,
                      rgb=None,
                      transparency=None,
                      material=Graphic3d_NOM_DEFAULT):
        """
        Display a shape.

        :param OCCT.TopoDS.TopoDS_Shape shape: The shape.
        :param rgb: The RGB color (r, g, b).
        :type rgb: collections.Sequence[float] or OCCT.Quantity.Quantity_Color
        :param float transparency: The transparency (0 to 1).
        :param OCCT.Graphic3d.Graphic3d_NameOfMaterial material: The material.

        :return: The AIS_Shape created for the part.
        :rtype: OCCT.AIS.AIS_Shape
        """
        return self.view.display_shape(shape, rgb, transparency, material)

    def display_mesh(self,
                     mesh,
                     mode=2,
                     group=None,
                     display_nodes=False,
                     node_size=1,
                     node_color=(1, 1, 1),
                     display_edges=True,
                     edge_size=1,
                     edge_color=(0.5, 0.5, 0.5),
                     beam_size=2,
                     beam_color=(1, 1, 0),
                     face_color=(0, 0, 0.5),
                     back_face_color=None):
        """
        Display a mesh.

        :param mesh: The mesh.
        :type mesh: OCCT.SMESH_SMESH_Mesh or OCCT.SMESH_SMESH_subMesh
        :param int mode: Display mode for mesh elements (1=wireframe, 2=solid).
        :param group: Option to display a group of mesh elements.
        :type group: None or OCCT.SMESH.SMESH_Group group
        :param bool display_nodes: Option to display mesh nodes or not. If a group of nodes is
            provided, then this option is turned on by default.
        :param float node_size: An option to scale the size of the node markers.
        :param node_color: The RGB values for the node markers between 0 and 1.
        :type node_color: tuple(float, float, float)
        :param bool display_edges: An option to display the edges of faces and beams.
        :param float edge_size: An option to scale the size of the edges.
        :param edge_color: The RGB values for the edges between 0 and 1.
        :type edge_color: tuple(float, float, float)
        :param float beam_size: An option to scale the size of the beams.
        :param beam_color: The RGB values for the beams between 0 and 1.
        :type beam_color: tuple(float, float, float)
        :param face_color: The RGB values for the faces between 0 and 1.
        :type face_color: tuple(float, float, float)
        :param back_face_color: The RGB values of the back side of the faces between 0 and 1. If not
            provided, then the back faces are colored the same as the faces.
        :type back_face_color: None or tuple(float, float, float)

        :return: The MeshVS_Mesh created for the mesh.
        :rtype: OCCT.MeshVS.MeshVS_Mesh
        """
        return self.view.display_mesh(mesh, mode, group, display_nodes,
                                      node_size, node_color, display_edges,
                                      edge_size, edge_color, beam_size,
                                      beam_color, face_color, back_face_color)

    def add(self,
            entity,
            rgb=None,
            transparency=None,
            material=Graphic3d_NOM_DEFAULT,
            mode=None):
        """
        Add an entity to the view.

        :param entity: The entity.
        :param rgb: The RGB color (r, g, b).
        :type rgb: collections.Sequence[float] or OCCT.Quantity.Quantity_Color
        :param float transparency: The transparency (0 to 1).
        :param OCCT.Graphic3d.Graphic3d_NameOfMaterial material: The material.
        :param int mode: Display mode for mesh elements (1=wireframe, 2=solid).

        :return: The AIS_Shape created for the entity. Returns *None* if the
            entity cannot be converted to a shape.
        :rtype: OCCT.AIS.AIS_Shape or None
        """
        if isinstance(entity, TopoDS_Shape):
            return self.view.display_shape(entity, rgb, transparency, material)
        elif isinstance(entity, (gp_Pnt, Geom_Curve, Geom_Surface)):
            return self.view.display_geom(entity, rgb, transparency, material)
        elif HAS_SMESH and isinstance(entity, SMESH_Mesh):
            return self.view.display_mesh(entity, mode)
        else:
            return None

    def clear(self):
        """
        Clear contents of the view.

        :return: None.
        """

        self.view.remove_all()

    def start(self, fit=True):
        """
        Start the viewer.

        :param bool fit: Option to fit contents.

        :return: None.
        """
        print('Press \"c\" to continue...')

        if fit:
            self.view.fit()
        self._app.exec_()
Esempio n. 42
0
class ModalTester(object):
    """
    Helper class for testing modal widgets (dialogs).
    """
    def __init__(self, creator, tester):
        """
        Initialise ModalTester.
        :param creator: Function without arguments that creates a modal widget. Can be a class name.
            A modal widget must have exec_() method.
        :param tester: A function taking a widget as its argument that does testing.
        """
        self.app = QApplication.instance()
        if self.app is None:
            self.app = QApplication([''])
        self.creator = creator
        self.tester = tester
        self.widget = None
        self.timer = None
        self.passed = False

    def __call__(self):
        """
        Initialise testing.
        """
        try:
            self.widget = self.creator()
        except:
            traceback.print_exc()
            self.app.exit(0)
        if self.widget is not None:
            self.widget.exec_()

    def _idle(self):
        """
        This function runs every time in QApplication's event loop.
        Call the testing function.
        """
        modal_widget = self.app.activeModalWidget()
        if modal_widget is not None:
            if self.widget is modal_widget:
                try:
                    self.tester(self.widget)
                    self.passed = True
                except:
                    traceback.print_exc()
            if modal_widget.isVisible():
                modal_widget.close()

    def start(self):
        """
        Start this tester.
        """
        self.timer = QTimer()
        # Connecting self.idle to a QTimer with 0 time delay
        # makes it called when there are no events to process
        self.timer.timeout.connect(self._idle)
        self.timer.start()
        # This calls __call__() method
        QTimer.singleShot(0, self)
        # Start the event loop
        self.app.exec_()
Esempio n. 43
0
def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
Esempio n. 44
0
def test():
    """ """
    app = QApplication([])
    win = TourTestWindow()
    win.show()
    app.exec_()
Esempio n. 45
0
def main():  # pragma: no cover
    """gui independent way to test the program"""
    # kills the program when you hit Cntl+C from the command line
    # doesn't save the current state as presumably there's been an error
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    import sys
    # Someone is launching this directly
    # Create the QApplication
    app = QApplication(sys.argv)
    parent = app
    red = (255, 0, 0)
    blue = (0, 0, 255)
    green = (0, 255, 0)
    purple = (255, 0, 255)

    # representation
    # * main - main mesh
    # * toggle - change with main mesh
    # * wire - always wireframe
    # * point - always points
    # * wire+point - point (vertex) and wireframe allowed
    # * surface - always surface
    # * bar - this can use bar scale
    data = {
        'font_size':
        8,
        'toggle':
        AltGeometry(parent,
                    'toggle',
                    color=green,
                    line_width=3,
                    opacity=0.2,
                    representation='toggle'),
        'wire':
        AltGeometry(parent,
                    'wire',
                    color=purple,
                    line_width=4,
                    opacity=0.3,
                    representation='wire'),
        'wire+point':
        AltGeometry(parent,
                    'wire+point',
                    color=blue,
                    line_width=2,
                    opacity=0.1,
                    bar_scale=1.0,
                    representation='wire+point'),
        'wire+surf':
        AltGeometry(parent,
                    'wire+surf',
                    display='surface',
                    color=blue,
                    line_width=2,
                    opacity=0.1,
                    bar_scale=1.0,
                    representation='wire+surf'),
        'main':
        AltGeometry(parent,
                    'main',
                    color=red,
                    line_width=1,
                    opacity=0.0,
                    representation='main'),
        'point':
        AltGeometry(parent,
                    'point',
                    color=blue,
                    opacity=0.1,
                    representation='point'),
        'surface':
        AltGeometry(parent,
                    'surface',
                    color=blue,
                    opacity=0.1,
                    representation='surface'),
    }
    main_window = EditGeometryProperties(data, win_parent=None)
    main_window.show()
    # Enter the main loop
    app.exec_()