def __init__(self, parent=None, job_name='', script_to_run=None, thread_index=-1): self.parent = parent if self.parent.job_monitor_interface is None: job_ui = JobMonitorInterface(parent=self.parent) job_ui.show() QApplication.processEvents() self.parent.job_monitor_interface = job_ui job_ui.launch_logbook_thread() else: self.parent.job_monitor_interface.activateWindow() job_ui = self.parent.job_monitor_interface if job_name == '': return job_list = self.parent.job_list p = subprocess.Popen(script_to_run.split()) new_job = {'job_name': job_name, 'time': self.get_launch_time(), 'status': 'processing', 'pid': p.pid, 'subprocess': p} job_list.append(new_job) self.parent.job_list = job_list job_ui.refresh_table(job_list)
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
def load(self): QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) o_table = TableRowHandler(main_window=self.parent) if self.parent.clear_master_table_before_loading: TableHandler.clear_table(self.table_ui) for _row, _key in enumerate(self.json.keys()): _entry = self.json[_key] run_number = _key title = _entry['title'] chemical_formula = _entry['resolved_conflict']['chemical_formula'] # geometry = _entry['resolved_conflict']['geometry'] mass_density = _entry['resolved_conflict']['mass_density'] # sample_env_device = _entry['resolved_conflict']['sample_env_device'] o_table.insert_row(row=_row, title=title, sample_runs=run_number, sample_mass_density=mass_density, sample_chemical_formula=chemical_formula) QApplication.restoreOverrideCursor()
def test_builtin_shift_del_and_ins(editor_bot): """ Test that the builtin key sequences Ctrl+Ins, Shit+Del and Shift+Ins result in copy, cut and paste actions in Windows and Linux. Regression test for issue #5035, #4947, and #5973. """ editorstack, qtbot = editor_bot editor = editorstack.get_current_editor() QApplication.clipboard().clear() # Select the first line of the editor. qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1' # Copy the selection with Ctrl+Ins. qtbot.keyClick(editor, Qt.Key_Insert, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1' # Paste the copied text at the end of the line with Shift+Ins. qtbot.keyClick(editor, Qt.Key_End) qtbot.keyClick(editor, Qt.Key_Insert, modifier=Qt.ShiftModifier) assert editor.toPlainText() == 'Line1Line1\nLine2\nLine3\nLine4\n' # Select the second line in the editor again. qtbot.keyClick(editor, Qt.Key_Home, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1Line1' # Cut the selection with Shift+Del. qtbot.keyClick(editor, Qt.Key_Delete, modifier=Qt.ShiftModifier) assert QApplication.clipboard().text() == 'Line1Line1' assert editor.toPlainText() == '\nLine2\nLine3\nLine4\n'
def test_copy_cut_paste_shortcuts(editor_bot): """ Test that the copy, cut, and paste keyboard shortcuts are working as expected with the default Spyder keybindings. """ editorstack, qtbot = editor_bot editor = editorstack.get_current_editor() QApplication.clipboard().clear() # Select and Copy the first line in the editor. qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1' qtbot.keyClick(editor, Qt.Key_C, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1' # Paste the selected text. qtbot.keyClick(editor, Qt.Key_Home) qtbot.keyClick(editor, Qt.Key_V, modifier=Qt.ControlModifier) assert editor.toPlainText() == 'Line1Line1\nLine2\nLine3\nLine4\n' # Select and Cut the first line in the editor. qtbot.keyClick(editor, Qt.Key_Home) qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1Line1' qtbot.keyClick(editor, Qt.Key_X, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1Line1' assert editor.toPlainText() == '\nLine2\nLine3\nLine4\n'
def main(self): """ Main function to process input and call smoothing function """ success = self.input_validation() if not success: return self.hide() self.abort_window = AbortWindow(self) QApplication.processEvents() # Add smoothing parameters self.smooth_cube.abort_window = self.abort_window if self.smooth_cube.parent is None and self.parent is not self.smooth_cube: self.smooth_cube.parent = self.parent if self.parent is not self.smooth_cube: self.smooth_cube.data = self.data self.smooth_cube.smoothing_axis = self.current_axis self.smooth_cube.kernel_type = self.current_kernel_type if self.current_kernel_type == "median": self.smooth_cube.kernel_size = int(self.k_size.text()) else: self.smooth_cube.kernel_size = float(self.k_size.text()) self.smooth_cube.component_id = str(self.component_combo.currentText()) self.smooth_cube.output_as_component = True if self.is_preview_active: self.parent.end_smoothing_preview() self.is_preview_active = False self.smooth_cube.multi_threading_smooth() return
def yDOLLAR(self, repeat): editor = self._widget.editor() cursor = editor.textCursor() cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor, repeat) text = cursor.selectedText() QApplication.clipboard().setText(text)
def eventFilter(self, obj, event): """ Filters events on this object. Params ------ object : QObject The object that is being handled. event : QEvent The event that is happening. Returns ------- bool True to stop the event from being handled further; otherwise return false. """ channel = getattr(self, 'channel', None) if is_channel_valid(channel): status = self._write_access and self._connected if event.type() == QEvent.Leave: QApplication.restoreOverrideCursor() if event.type() == QEvent.Enter and not status: QApplication.setOverrideCursor(QCursor(Qt.ForbiddenCursor)) return PyDMWidget.eventFilter(self, obj, event)
def _wrapper(self): global QAPP if not QAPP: setup_library_paths() QAPP = QApplication(['']) test_method(self) QAPP.closeAllWindows()
def test_pydmdrawing_paintEvent(qtbot, signals, alarm_sensitive_content): """ Test the paintEvent handling of the widget. This test method will also execute PyDMDrawing alarm_severity_changed and draw_item(). Expectations: The paintEvent will be triggered, and the widget's brush color is correctly set. NOTE: This test depends on the default stylesheet having different values for 'qproperty-brush' for different alarm states of PyDMDrawing. Parameters ---------- qtbot : fixture Window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots alarm_sensitive_content : bool True if the widget will be redraw with a different color if an alarm is triggered; False otherwise. """ QApplication.instance().make_main_window() main_window = QApplication.instance().main_window qtbot.addWidget(main_window) pydm_drawing = PyDMDrawing(parent=main_window, init_channel='fake://tst') qtbot.addWidget(pydm_drawing) pydm_drawing.alarmSensitiveContent = alarm_sensitive_content brush_before = pydm_drawing.brush.color().name() signals.new_severity_signal.connect(pydm_drawing.alarmSeverityChanged) signals.new_severity_signal.emit(PyDMWidget.ALARM_MAJOR) brush_after = pydm_drawing.brush.color().name() if alarm_sensitive_content: assert brush_before != brush_after else: assert brush_before == brush_after
def copy(self): """ Reimplement Qt method Copy text to clipboard with correct EOL chars """ if self.get_selected_text(): QApplication.clipboard().setText(self.get_selected_text())
def show_data(self, justanalyzed=False): if not justanalyzed: self.output = None self.log_button.setEnabled(self.output is not None and len(self.output) > 0) self.kill_if_running() filename = to_text_string(self.filecombo.currentText()) if not filename: return if self.stopped: self.datelabel.setText(_('Run stopped by user.')) self.datatree.initialize_view() return self.datelabel.setText(_('Sorting data, please wait...')) QApplication.processEvents() self.datatree.load_data(self.DATAPATH) self.datatree.show_tree() text_style = "<span style=\'color: %s\'><b>%s </b></span>" date_text = text_style % (self.text_color, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) self.datelabel.setText(date_text)
def qapplication(): """Either return a reference to an existing application instance or create a new one :return: A reference to the QApplication object """ app = QApplication.instance() if app is None: QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) argv = sys.argv[:] argv[0] = APPNAME # replace application name # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5 # Without this using this fix the above combination causes a segfault when the IPython # console is started # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0 # is to ensure readline is imported before the QApplication object is created if sys.version_info[0] == 3 and sys.version_info[1] == 5: importlib.import_module("readline") app = QApplication(argv) app.setOrganizationName(ORGANIZATION) app.setOrganizationDomain(ORG_DOMAIN) app.setApplicationName(APPNAME) app.setApplicationVersion(mantid_version_str()) # Spin up the usage service and set the name for the usage reporting # The report is sent when the FrameworkManager kicks up UsageService.setApplicationName(APPNAME) return app
def set_splash(self, msg=None): if not self.splash: return if msg: self.splash.showMessage(msg, Qt.AlignBottom | Qt.AlignLeft | Qt.AlignAbsolute, QColor(Qt.black)) QApplication.processEvents(QEventLoop.AllEvents)
def resize_to_contents(self): """Resize cells to contents""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor()
def eventFilter(self, obj, event): status = self._connected if event.type() == QEvent.Leave: QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor)) elif event.type() == QEvent.Enter and not status: QApplication.setOverrideCursor(QCursor(Qt.ForbiddenCursor)) return False
def closeEvent(self, *args, **kwargs): self.save_settings() # Enable paste of clipboard after termination clipboard = QApplication.clipboard() event = QEvent(QEvent.Clipboard) QApplication.sendEvent(clipboard, event) return QMainWindow.closeEvent(self, *args, **kwargs)
def test_copy_to_clipboard(self): self.widget.loadFunction('name=LinearBackground,A0=0,A1=0') yield self.start_setup_menu() yield self.start_manage_setup() QApplication.clipboard().clear() self.trigger_action('action_CopyToClipboard') yield self.wait_for_true(lambda: QApplication.clipboard().text() != '') self.assertEqual(QApplication.clipboard().text(), 'name=LinearBackground,A0=0,A1=0')
def main(args=sys.argv): app = QApplication(args) widget = SpellCheckTextEdit('Type here') widget.show() widget.raise_() return app.exec_()
def starting_long_process(self, message): """ Showing message in main window's status bar and changing mouse cursor to Qt.WaitCursor """ self.__show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
def show_context_menu(self, widget, pos, pause=0): QTest.mouseMove(widget, pos) yield pause QTest.mouseClick(widget, Qt.RightButton, Qt.NoModifier, pos) yield pause ev = QMouseEvent(QEvent.ContextMenu, pos, Qt.RightButton, Qt.NoButton, Qt.NoModifier) QApplication.postEvent(widget, ev) yield self.wait_for_popup()
def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(Qt.WaitCursor)) try: ret_val = func(*args, **kwargs) finally: QApplication.restoreOverrideCursor() return ret_val
def yw(self, repeat): editor = self._widget.editor() cursor = editor.textCursor() cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor, repeat - 1) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) text = cursor.selectedText() QApplication.clipboard().setText(text)
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_()
def run_script(self, script): with self.gui.wait_cursor(): self.set_output("") self.ui.labelLineNumber.setText("") QApplication.processEvents() sys.stdout = self starttime = -time.time() line_added=0 try: self.output = [] try: self.scriptRunner.run(script) except NameError as e: s = str(e).split("'") if len(s) == 3 and ((s[0] == "global name " and s[2] == " is not defined") or (s[0] == "name " and s[2] == " is not defined")): #python 3.5 lines = script.split("\n") if "# auto global" in lines[0] and s[1] in lines[0]: pass else: if self.gui.get_confirmation("Add global variable", "The variable '%s' seems to be missing in a scope. \nDo you want to add declare it as global?"%s[1])==True: if "# auto global" in lines[0] and s[1] not in lines[0].replace("# auto global","").replace("global",""): lines[0] = lines[0].replace(" # auto global", ", %s # auto global" % s[1]) else: lines[0] = "global %s # auto global\n%s" % (s[1], lines[0]) line_added = 1 script = "\n".join(lines) self.ui.tabWidget.currentWidget().set_script(script) raise self.set_output("".join(self.output)) beep(1000, 50) except (Warning, Exception) as inst: try: limit = -["exec(script_code, globals(), locals())" in traceback.format_exc(limit=-i) for i in range(100)].index(True)-1 except: limit=None traceback.print_exc(file=sys.stdout, limit=limit) self.set_output("".join(self.output)) sys.stdout = sys.__stdout__ try: linenr = self.output[[self.output.index(l) for l in self.output if "File \"<string>\", line " in l][-1]] linenr = linenr[23:] if "," in linenr: linenr = int(linenr[:linenr.index(",")]) else: linenr = int(linenr) self.selectLine(linenr - 1+line_added) except IndexError: pass print ('-' * 60) beep(500, 50) finally: sys.stdout = sys.__stdout__ self.ui.labelLineNumber.setText("Script executed in %d seconds" % (time.time() + starttime))
def copy_without_prompts(self): """Copy text to clipboard without prompts""" text = self.get_selected_text() lines = text.split(os.linesep) for index, line in enumerate(lines): if line.startswith('>>> ') or line.startswith('... '): lines[index] = line[4:] text = os.linesep.join(lines) QApplication.clipboard().setText(text)
def exec_long_guitask(self, text, task, *args, **kwargs): self.__show(text, False) QApplication.processEvents() task(*args, **kwargs) self.__hide() return self.taskThread.result
def override_cursor(self, cursor): """ Set new override cursor. :param cursor: New cursor. """ self._override_cursor = cursor QApplication.restoreOverrideCursor() if cursor is not None: QApplication.setOverrideCursor(cursor)
def __next__(self): if self.n % self.update_every == 0: if self.allow_cancel and self.QtProgressInformation._progressDialog.wasCanceled(): raise CancelWarning() self.QtProgressInformation._progressDialog.setValue(self.n) QApplication.processEvents() self.n += 1 return next(self.generator)
def write_error(self): if os.name == 'nt': #---This is apparently necessary only on Windows (not sure though): # emptying standard output buffer before writing error output self.process.setReadChannel(QProcess.StandardOutput) if self.process.waitForReadyRead(1): self.write_output() self.shell.write_error(self.get_stderr()) QApplication.processEvents()
def startDebugging(self): QApplication.instance().installEventFilter(self.mousedebugger)
# Make temporary YAML file yaml_file = tempfile.mktemp() with open(yaml_file, 'w') as f: f.write(dialog.as_yaml(name=str(uuid.uuid4()))) # Temporarily load YAML file yaml_filter = load_yaml_reader(yaml_file) def remove_yaml_filter(data): # Just some checking in the edge case where a user is simultaneously loading another file... if data.name != os.path.basename(filename).split('.')[0]: return io_registry._readers.pop((yaml_filter, Spectrum1DRef)) io_registry._identifiers.pop((yaml_filter, Spectrum1DRef)) dispatch.unregister_listener("on_added_data", remove_yaml_filter) dispatch.register_listener("on_added_data", remove_yaml_filter) # Emit signal to indicate that file should be read dispatch.on_file_read.emit(file_name=filename, file_filter=yaml_filter) if __name__ == "__main__": app = QApplication([]) dialog = FITSImportWizard(simplify_arrays(parse_fits(sys.argv[1]))) dialog.exec_()
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(r"$\mu s$") ax.set_ylabel("Counts") ax.plot(x, cx) fig1.show()
# os.environ['QT_API'] = 'pyside2' # forces pyside2 from qtpy.QtWidgets import QMainWindow, QApplication, QMessageBox from qtpy import uic, QtCore, QtGui import numpy as np # from timeit import default_timer as timer from plot.plot_main import All_Plots as plot from misc_widget import MessageWindow import appdirs, options_panel_widgets, convert_units, sim_explorer_widget import mech_fcns, settings, config_io, save_widget, error_window, help_menu if os.environ[ 'QT_API'] == 'pyside2': # Silence warning: "Qt WebEngine seems to be initialized from a plugin." QApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) # Handle high resolution displays: Minimum recommended resolution 1280 x 960 if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'): QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'): QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) # set main folder path = {'main': pathlib.Path(sys.argv[0]).parents[0].resolve()} # set appdata folder using AppDirs library (but just using the source code file) dirs = appdirs.AppDirs(appname='Frhodo', roaming=True, appauthor=False) path['appdata'] = pathlib.Path(dirs.user_config_dir) path['appdata'].mkdir(parents=True, exist_ok=True) # Make path if it doesn't exist
def __copy_expr(self) -> None: """Copy the expression.""" string = self.edges_text.text() if string: QApplication.clipboard().setText(string) self.edges_text.selectAll()
def resize_to_contents(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.dataTable.resizeColumnsToContents() self.dataModel.fetch_more(columns=True) self.dataTable.resizeColumnsToContents() QApplication.restoreOverrideCursor()
def copy(self): """Copy text to clipboard""" cliptxt = self._sel_to_text(self.selectedIndexes()) clipboard = QApplication.clipboard() clipboard.setText(cliptxt)
def open_client_from_connection_info(connection_info, qtbot): top_level_widgets = QApplication.topLevelWidgets() for w in top_level_widgets: if isinstance(w, KernelConnectionDialog): w.cf.setText(connection_info) qtbot.keyClick(w, Qt.Key_Enter)
def test(): """ """ app = QApplication([]) win = TestWindow() win.show() app.exec_()
else: config.mainWindow.show() # Set Qt input method variable to use fcitx / ibus if config.fcitx / config.ibus is "True" if config.fcitx: os.environ["QT_IM_MODULE"] = "fcitx" elif config.ibus: os.environ["QT_IM_MODULE"] = "ibus" # Set Qt input method variable to use Qt virtual keyboards if config.virtualKeyboard is "True" if config.virtualKeyboard: os.environ["QT_IM_MODULE"] = "qtvirtualkeyboard" # Start PySide2 gui app = QApplication(sys.argv) # Set application name app.setApplicationName("UniqueBible.app") app.setApplicationDisplayName("UniqueBible.app") # When application name is changed app.applicationNameChanged.connect(nameChanged) # Assign a function to save configurations when the app is closed. app.aboutToQuit.connect(exitApplication) # Apply window style if config.windowStyle and config.windowStyle in QStyleFactory.keys(): app.setStyle(config.windowStyle) # Apply theme style if config.qtMaterial and config.qtMaterialTheme: apply_stylesheet(app, theme=config.qtMaterialTheme) config.theme = "dark" if config.qtMaterialTheme.startswith( "dark_") else "default"
def resizeEvent(self, event): QFrame.resizeEvent(self, event) self.update_positions() font = self.label.font() font.setPointSize(self.height() / 2) self.label.setFont(font) if __name__ == "__main__": from qtpy.QtWidgets import QApplication, QWidget, QLabel, QHBoxLayout app = QApplication() w = QWidget() w.setGeometry(100, 100, 300, 300) layout = QHBoxLayout(w) check = PCheckBox(w) check.set_text("Full Address Only") check.set_direction(QBoxLayout.LeftToRight) check.set_text_color(QColor(255, 255, 255)) layout.addWidget(check) w.show()
def tearDown(self): self.assertTrue(self.view.close()) QApplication.sendPostedEvents()
def closeEvent(self, event): QApplication.quit( ) # some errors can be recovered from, maybe I shouldn't autoclose the program
def restore_launchservices(): """Restore LaunchServices to the previous state""" app = QApplication.instance() for key, handler in app._original_handlers.items(): UTI, role = key als.set_UTI_handler(UTI, role, handler)
def __init__(self, *args): QApplication.__init__(self, *args) self._never_shown = True self._has_started = False self._pending_file_open = [] self._original_handlers = {}
def _hide(self): """Hide method helper.""" QApplication.restoreOverrideCursor() self._timer_hide.start()
def AddTDTAnalogDataToNWB(tdt_block_dir, nwb_file_name='', signal_info=None, module_name='behavior', verbose=False): """ Copies analog (continuous) data from the specified Blackrock file to Neurodata Without Borders (NWB) file. This is usually continuous signals about behavior (joystick position, screen refreshes, etc). User should provide information about the signals to help end users understand what is in each signal. Multiple calls can be used to load multiple data signals from multiple files. Typically, the NWB file will already be initialized by calling InitializeNWBFromBlackrock. :param tdt_block_dir: {str} full path of TDT files to convert to NWB. If empty, will open dialog. :param nwb_file_name: [optional] {str} full path of NWB file to export to. Default is to change blackrock extension to 'nwb' :param signal_info: [optional] {list} List of dictionaries with information about the signals to save. :param module_name: [optional] {str} Name of module to store data. Usually 'behavior' but could also be 'ecephys' or 'misc' :param verbose: [optional] {bool} whether to print updates while converting. Default is false. :return: {str} filename of NWB file (empty if error) """ # Check to see if user specified a TDT filename if not tdt_block_dir: # no file name passed # Ask user to specify a file if 'app' not in locals(): app = QApplication([]) tdt_block_dir = QFileDialog.getExistingDirectory( QFileDialog(), 'Select Directory', getcwd()) # Check to see if valid nwb_file_name is passed tdt_tsq_files = [ f for f in listdir(tdt_block_dir) if path.splitext(f)[1] == '.tsq' ] if not nwb_file_name: nwb_file_name = path.splitext(tdt_tsq_files[0])[0] + '.nwb' if verbose: print("Writing to NWB data file %s" % (nwb_file_name)) # Initialize the TDT file try: # Requires the raw data to be imported tdt_header = tdt.read_block(tdt_block_dir, headers=1) except: # catch *all* exceptions e = sys.exc_info()[0] raise FileNotFoundError( "Couldn't open TDT file. Error: {:s}".format(e)) # Initialize the NWB file nwb_io = [] try: if not path.isfile(nwb_file_name): # Initialize NWB file if verbose: print("NWB file doesn't exist. Creating new one: %s..." % (nwb_file_name)) InitializeNWBFromTDT(tdt_block_dir, nwb_file_name, verbose=verbose) # Append to existing file if verbose: print("Opening NWB file %s..." % (nwb_file_name), end='') nwb_file_append = True nwb_io = NWBHDF5IO(nwb_file_name, mode='a') nwb_file = nwb_io.read() if verbose: print("done.") except: # catch *all* exceptions e = sys.exc_info()[0] if nwb_io: nwb_io.close() raise FileExistsError("Couldn't open NWB file. Error: %s" % e) # Make sure module name is either behavior or misc module_name = module_name.lower() if (module_name != 'behavior') and (module_name != 'misc'): raise ValueError("Module type must either be 'behavior' or 'misc'.") # Parse the signal_info list if not signal_info: raise ValueError("Must specify signals to load.") elec_ids = [] for cur_signal_ind, cur_signal_info in enumerate(signal_info): if 'label' not in cur_signal_info.keys(): raise ValueError( "Signal information must have a label for each signal.") if 'name' not in cur_signal_info.keys(): raise ValueError( "Signal information must have a name for each signal. (Should be user-understandable)" ) if 'comments' not in cur_signal_info.keys(): signal_info[cur_signal_ind]['comments'] = '' # Find electrode IDs for this signal if ('elec_id' not in cur_signal_info.keys()) or ( not cur_signal_info['elec_id']): # Loop through and grab all signals of type 'streams' that aren't RAW data signal_info[cur_signal_ind]['elec_id'] = [] for cur_store in tdt_header.stores.keys(): # Grab all 'streams' but ignore RAWs if (tdt_header.stores[cur_store].type_str == 'streams') and (cur_store[0:3] != 'RAW'): signal_info[cur_signal_ind]['elec_id'].append(cur_store) # Create processing module for saving data if module_name not in nwb_file.processing.keys(): if verbose: print( "Specified processing module (%s) does not exist. Creating." % (module_name)) signal_module = ProcessingModule( name=module_name, description="Processing module for continuous signal data from %s." % (path.split(tdt_tsq_files[0])[1])) nwb_file.add_processing_module(signal_module) # Create data interface for the analog signals signal_info_str = signal_info[0]['name'] for i in range(1, len(signal_info)): signal_info_str = signal_info_str + ", " + signal_info[i]['name'] if verbose: print("Creating %s data interface for signals %s." % (module_name, signal_info_str)) if module_name == 'behavior': cur_data_interface = BehavioralTimeSeries(name="Analog signals (" + signal_info_str + ")") elif module_name == 'misc': cur_data_interface = AbstractFeatureSeries(name="Analog signals (" + signal_info_str + ")") else: raise ValueError("Module type must either be 'behavior' or 'misc'.") if verbose: print("Adding signals...") for cur_signal_ind, cur_signal_info in enumerate(signal_info): # Get data from file analog_data = [] analog_fs = [] analog_start_time = [] for cur_elec_id in cur_signal_info['elec_id']: cur_data = tdt.read_block(tdt_block_dir, store=cur_elec_id) cur_analog_data = cur_data.streams[cur_elec_id].data cur_analog_data = np.reshape(cur_analog_data, [len(cur_analog_data), 1]) if len(analog_data) == 0: analog_fs = cur_data.streams[cur_elec_id].fs analog_start_time = cur_data.streams[cur_elec_id].start_time analog_data = cur_analog_data else: analog_fs.append(cur_data.streams[cur_elec_id].fs) analog_start_time.append( cur_data.streams[cur_elec_id].start_time) analog_data = np.concatenate([analog_data, cur_analog_data], axis=1) # Make sure all of the fs and start_times are the same analog_start_time = np.unique(analog_start_time) analog_fs = np.unique(analog_fs) if len(analog_start_time) != 1 or len(analog_fs) != 1: raise ValueError( 'Start time and sampling frequency need to be the same for signals to be combined.' ) # Create time series cur_data_interface.create_timeseries( name=cur_signal_info['name'], data=analog_data, comments=cur_signal_info['comments'], unit="V", #TODO: Check that this is correct for TDT resolution=1.0, #TODO: Can we get this from TDT? conversion= 0.001, #TODO: Check what the correct conversion is for TDT starting_time=analog_start_time[0], rate=analog_fs[0], description="Signal %s from %s." % (cur_signal_info['label'], path.split(tdt_tsq_files[0])[1])) if verbose: print("\tAdded %s." % (cur_signal_info['label'])) # Add data interface to module in NWB file if verbose: print("Adding data interface to module.") nwb_file.processing[module_name].add(cur_data_interface) # Write the file if verbose: print("Writing NWB file and closing.") nwb_io.write(nwb_file) nwb_io.close() return nwb_file_name
class SwitcherItem(SwitcherBaseItem): """ Switcher item with title, description, shortcut and section. SwitcherItem: [title description <shortcut> section] Based on HTML delegate. See: https://doc.qt.io/qt-5/richtext-html-subset.html """ _FONT_SIZE = 10 _HEIGHT = 20 _STYLE_ATTRIBUTES = [ 'title_color', 'description_color', 'section_color', 'shortcut_color', 'title_font_size', 'description_font_size', 'section_font_size', 'shortcut_font_size' ] _STYLES = { 'title_color': QApplication.palette().text().color().name(), 'description_color': 'rgb(153, 153, 153)', 'section_color': 'rgb(70, 179, 239)', 'shortcut_color': 'rgb(153, 153, 153)', 'title_font_size': _FONT_SIZE, 'description_font_size': _FONT_SIZE, 'section_font_size': _FONT_SIZE, 'shortcut_font_size': _FONT_SIZE, } _TEMPLATE = '''<table width="{width}" height="{height}" cellpadding="{padding}"> <tr> <td valign="bottom"> <span style="color:{title_color};font-size:{title_font_size}pt"> {title} </span> <small style="color:{description_color};font-size:{description_font_size}pt"> <span>{description}</span> </small> </td> <td valign="middle" align="right" float="right"> <span style="color:{shortcut_color};font-size:{shortcut_font_size}pt"> <small><code><i>{shortcut}</i></code></small> </span> <span style="color:{section_color};font-size:{section_font_size}pt"> <small>{section}</small> </span> </td> </tr> </table>''' def __init__(self, parent=None, icon=None, title=None, description=None, shortcut=None, section=None, data=None, tool_tip=None, action_item=False, styles=_STYLES): """Switcher item with title, description, shortcut and section.""" super(SwitcherItem, self).__init__(parent=parent, styles=styles) self._title = title if title else '' self._rich_title = '' self._shortcut = shortcut if shortcut else '' self._description = description if description else '' self._section = section if section else '' self._icon = icon self._data = data self._score = -1 self._action_item = action_item self._section_visible = True # Setup self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) if icon: self.setIcon(icon) self._set_styles() self._set_rendered_text() # --- Helpers def _render_text(self, title=None, description=None, section=None): """Render the html template for this item.""" if self._rich_title: title = self._rich_title else: title = title if title else self._title # TODO: Based on width this should elide/shorten description = description if description else self._description if self._section_visible: section = section if section else self._section else: section = '' padding = self._PADDING width = self._width height = self._HEIGHT shortcut = '<' + self._shortcut + '>' if self._shortcut else '' text = self._TEMPLATE.format(width=width, height=height, title=title, section=section, description=description, padding=padding, shortcut=shortcut, **self._styles) return text def _set_styles(self): """Set the styles for this item.""" for attr in self._STYLE_ATTRIBUTES: if attr not in self._styles: self._styles[attr] = self._STYLES[attr] rich_font = self._styles['title_font_size'] if sys.platform == 'darwin': title_font_size = rich_font description_font_size = title_font_size + 2 elif os.name == 'nt': title_font_size = rich_font description_font_size = title_font_size + 1 elif is_ubuntu(): title_font_size = rich_font - 2 description_font_size = title_font_size + 1 else: title_font_size = rich_font - 2 description_font_size = title_font_size + 1 self._styles['description_font_size'] = description_font_size self._styles['section_font_size'] = description_font_size # --- API def set_icon(self, icon): """Set the QIcon for the list item.""" self._icon = icon self.setIcon(icon) def get_icon(self): """Return the QIcon for the list item.""" return self._icon def set_title(self, value): """Set the main text (title) of the item.""" self._title = value self._set_rendered_text() def get_title(self): """Return the the main text (title) of the item.""" return self._title def set_rich_title(self, value): """Set the rich title version (filter highlight) of the item.""" self._rich_title = value self._set_rendered_text() def get_rich_title(self): """Return the rich title version (filter highlight) of the item.""" return self._rich_title def set_description(self, value): """Set the item description text.""" self._description = value self._set_rendered_text() def get_description(self): """Return the item description text.""" return self._description def set_shortcut(self, value): """Set the shortcut for the item action.""" self._shortcut = value self._set_rendered_text() def get_shortcut(self, value): """Return the shortcut for the item action.""" return self._shortcut def set_tooltip(self, value): """Set the tooltip text for the item.""" super(SwitcherItem, self).setTooltip(value) def set_data(self, value): """Set the additional data associated to the item.""" self._data = value def get_data(self): """Return the additional data associated to the item.""" return self._data def get_score(self): """Return the fuzzy matchig score.""" return self._score def set_section(self, value): """Set the item section name.""" self._section = value self._set_rendered_text() def get_section(self): """Return the item section name.""" return self._section def set_section_visible(self, value): """Set visibility of the item section.""" self._section_visible = value self._set_rendered_text() def set_action_item(self, value): """Enable/disbale the action type for the item.""" self._action_item = value self._set_rendered_text()
def show_tip(self, point, tip, wrapped_tiplines): """ Attempts to show the specified tip at the current cursor location. """ # Don't show the widget if the main window is not focused if QApplication.instance().applicationState() != Qt.ApplicationActive: return # Don't attempt to show it if it's already visible and the text # to be displayed is the same as the one displayed before. if self.isVisible(): if self.tip == tip: return True else: self.hide() # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False if self.hide_timer_on: self._hide_timer.stop() # Logic to decide how much time to show the calltip depending # on the amount of text present if len(wrapped_tiplines) == 1: args = wrapped_tiplines[0].split('(')[1] nargs = len(args.split(',')) if nargs == 1: hide_time = 1400 elif nargs == 2: hide_time = 1600 else: hide_time = 1800 elif len(wrapped_tiplines) == 2: args1 = wrapped_tiplines[1].strip() nargs1 = len(args1.split(',')) if nargs1 == 1: hide_time = 2500 else: hide_time = 2800 else: hide_time = 3500 self._hide_timer.start(hide_time, self) # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 0 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = self.app.desktop().screenGeometry(text_edit) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height() + screen_rect.y(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2 * point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width() + screen_rect.x(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2 * point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' % (vertical, horizontal)) adjusted_point = text_edit.mapToGlobal(pos()) if vertical == 'top': if os.name == 'nt': padding = -7 else: padding = -4.5 point.setY(adjusted_point.y() - tip_height - padding) if horizontal == 'Left': point.setX(adjusted_point.x() - tip_width - padding) self.move(point) self.show() return True
def AddTDTRawDataToNWB(tdt_block_dir, nwb_file_name='', verbose=False, elec_ids=None): """ Copies raw electrophysiological data from TDT format to Neurodata Without Borders (NWB) format. Typically, the NWB file will already be initialized by calling InitializeNWBFromTDT. Multiple electrodes can be added at once or with separate calls to this function. :param tdt_block_dir: {str} full path of TDT files to convert to NWB. If empty, will open dialog. :param nwb_file_name: [optional] {str} full path of NWB file to export to. Default is to change blackrock extension to 'nwb' :param verbose: [optional] {bool} whether to print updates while converting. Default is false. :param elec_ids: [optional] {list} List of electrode IDs to copy over. If empty, all are copied :return: {str} filename of NWB file (empty if error) """ # Check to see if user specified a TDT filename if not tdt_block_dir: # no file name passed # Ask user to specify a file if 'app' not in locals(): app = QApplication([]) tdt_block_dir = QFileDialog.getExistingDirectory( QFileDialog(), 'Select Directory', getcwd()) # Check to see if valid nwb_file_name is passed tdt_tsq_files = [ f for f in listdir(tdt_block_dir) if path.splitext(f)[1] == '.tsq' ] if not nwb_file_name: nwb_file_name = path.splitext(tdt_tsq_files[0])[0] + '.nwb' if verbose: print("Writing to NWB data file %s" % (nwb_file_name)) # Initialize the TDT file try: # Requires the raw data to be imported tdt_header = tdt.read_block(tdt_block_dir, headers=1) except: # catch *all* exceptions e = sys.exc_info()[0] raise FileNotFoundError( "Couldn't open TDT file. Error: {:s}".format(e)) # Initialize the NWB file nwb_io = [] try: if not path.isfile(nwb_file_name): # Initialize NWB file if verbose: print("NWB file doesn't exist. Creating new one: %s..." % (nwb_file_name)) InitializeNWBFromTDT(tdt_block_dir, nwb_file_name, verbose=verbose) # Append to existing file if verbose: print("Opening NWB file %s..." % (nwb_file_name), end='') nwb_file_append = True nwb_io = NWBHDF5IO(nwb_file_name, mode='a') nwb_file = nwb_io.read() if verbose: print("done.") except: # catch *all* exceptions e = sys.exc_info()[0] if nwb_io: nwb_io.close() raise FileExistsError("Couldn't open NWB file. Error: %s" % e) # Validate the elec_ids list if not elec_ids: # Grab electroe list from NWB file elec_ids = nwb_file.electrodes.id[:] # Load data for all of the electrodes if verbose: print("Loading raw data from TDT file...") chan_data = [] starting_time = 0 fs = 24414.0625 for cur_elec_id in elec_ids: # Convert electrode id into RAW and channel cur_raw = np.floor((cur_elec_id - 1) / 16) + 1 cur_raw = 'RAW{:1.0f}'.format(cur_raw) cur_chan = ((cur_elec_id - 1) % 16) + 1 print('{:s}_{:1.0f}'.format(cur_raw, cur_chan)) #Read this channel data in from file cur_chan_data = tdt.read_sev(tdt_block_dir, channel=cur_chan, event_name=cur_raw) fs = cur_chan_data[cur_raw].fs starting_time = cur_chan_data.time_ranges[0][0] cur_chan_data = cur_chan_data[cur_raw].data cur_chan_data = np.reshape(cur_chan_data, [len(cur_chan_data), 1]) if len(chan_data) == 0: chan_data = cur_chan_data else: chan_data = np.concatenate([chan_data, cur_chan_data], axis=1) if verbose: print("\tLoaded electrode %d..." % (cur_elec_id)) # Get resolution of signal in V if verbose: print("Processing electrode information.") V_resolution = 0.0 #TODO: See if we can get resolution information from TDT? # Create electrode table for new electrodes elec_table_ind = np.ones((len(elec_ids), 1)) * np.NaN for cur_elec_ind, cur_elec in enumerate(elec_ids): # In order to create electrode table, we have to have indexes for each channel into electrode list in NWB file cur_elec_table_ind = 0 while (cur_elec_table_ind < len(nwb_file.electrodes)) and ( nwb_file.electrodes[cur_elec_table_ind, 0] != cur_elec): cur_elec_table_ind = cur_elec_table_ind + 1 if cur_elec_table_ind >= len(nwb_file.electrodes): raise ValueError("Couldn't find electrode %d in NWB file list." % (cur_elec)) elec_table_ind[cur_elec_ind] = cur_elec_table_ind elec_table_ind = elec_table_ind.transpose().tolist()[ 0] # Convert to list for create_electrode_table_region electrode_table_region = nwb_file.create_electrode_table_region( elec_table_ind, "Electrodes %s" % (elec_ids)) # Write raw data for the electrode if verbose: print("\tAdding to NWB...", end='') ephys_ts = ElectricalSeries( 'Raw Data for Channels %s' % (elec_ids), chan_data, electrode_table_region, starting_time=starting_time, rate=fs, resolution=V_resolution, conversion=float( 1.0), #TODO: Check that TDT does read in V, as expected by NWB comments="", description="Raw data from TDT file.") nwb_file.add_acquisition(ephys_ts) if verbose: print("done") # Write the file if verbose: print("\tWriting NWB file and closing.") nwb_io.write(nwb_file) nwb_io.close() return nwb_file_name
def show_tip(self, point, tip, cursor=None, completion_doc=None): """ Attempts to show the specified tip at the current cursor location. """ # Don't show the widget if the main window is not focused if QApplication.instance().applicationState() != Qt.ApplicationActive: return # Set the text and resize the widget accordingly. self.tip = tip self.setText(tip) self.resize(self.sizeHint()) self.completion_doc = completion_doc padding = 0 text_edit = self._text_edit if cursor is None: cursor_rect = text_edit.cursorRect() else: cursor_rect = text_edit.cursorRect(cursor) screen_rect = self.app.desktop().screenGeometry(text_edit) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height() + screen_rect.y(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2 * point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width() + screen_rect.x(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2 * point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' % (vertical, horizontal)) adjusted_point = text_edit.mapToGlobal(pos()) if vertical == 'top': if os.name == 'nt': padding = -7 else: padding = -4.5 point.setY(adjusted_point.y() - tip_height - padding) if horizontal == 'Left': point.setX(adjusted_point.x() - tip_width - padding) self.move(point) if not self.isVisible(): self.show() return True
def InitializeNWBFromTDT(tdt_block_dir, nwb_file_name='', experiment=None, subject=None, electrode_info=None, electrode_group=None, notes=None, overwrite=False, verbose=False): """ Initializes a NWB file to copy over data from Blackrock file. User specified information is added to NWB file as metadata about data. :param tdt_block_dir: {str} full path of TDT files to convert to NWB. If empty, will open dialog. :param nwb_file_name: [optional] {str} full path of NWB file to export to. Default is to change TDT extension to 'nwb' :param verbose: [optional] {bool} whether to print updates while converting. Default is false. :param experiment: [optional] {dict} Dictionary that contains information about experimenter, name, animal, lab, and institution :param subject: [optional] {dict} Dictionary that contains information about subject :param electrode_info: [optional] {list} List of dictionaries carrying information about electrodes :param electrode_group: [optional] {list} List of dictionaries carrying information about electrode groupings :param notes: [optional] {str} Notes relevant for the dataset :param overwrite: [optional] {bool} Whether to overwrite the NWB file if it already exists :return: {str} filename of NWB file (empty if error) """ # Check to see if user specified a TDT filename if not tdt_block_dir: # no file name passed # Ask user to specify a file if 'app' not in locals(): app = QApplication([]) tdt_block_dir = QFileDialog.getExistingDirectory( QFileDialog(), 'Select Directory', getcwd()) # Check to see if valid nwb_file_name is passed tdt_tsq_files = [ f for f in listdir(tdt_block_dir) if path.splitext(f)[1] == '.tsq' ] if not nwb_file_name: nwb_file_name = tdt_block_dir + path.splitext( tdt_tsq_files[0])[0] + '.nwb' if verbose: print("Writing to NWB data file %s" % (nwb_file_name)) # Initialize the TDT file, get header and basic information try: # Requires the raw data to be imported tdt_header = tdt.read_block(tdt_block_dir, headers=1) tdt_data = tdt.read_block(tdt_block_dir, evtype=['epocs']) except: # catch *all* exceptions e = sys.exc_info()[0] raise FileNotFoundError("Couldn't open TDT file. Error: %s" % e) # Process experiment information from inputs if (not experiment) or not (type(experiment) is dict): if verbose: print("Using default experimental details.") nwb_session_description = 'Experimental details not provided' experimenter = '' lab = '' institution = '' else: if 'name' not in experiment.keys(): experiment['name'] = '' if 'animal' not in experiment.keys(): experiment['animal'] = '' if 'experimenter' not in experiment.keys(): experiment['experimenter'] = '' if 'lab' not in experiment.keys(): experiment['lab'] = '' if 'institution' not in experiment.keys(): experiment['institution'] = '' experimenter = experiment['experimenter'] lab = experiment['lab'] institution = experiment['institution'] nwb_session_description = 'Experiment: ' + experiment['name'] + \ ', Animal: ' + experiment['animal'] + \ ', Date: ' + tdt_data.info.start_date.strftime('%m/%d/%Y') # description of the recording session if verbose: print("Experiment description: %s" % (nwb_session_description)) # Process subject information if (not subject) or not (type(subject) is dict): cur_subject = None else: try: # Create a subject object from the passed dictionary cur_subject = file.Subject(**subject) except: # catch *all* exceptions e = sys.exc_info()[0] raise ValueError("Couldn't create subject object. Error: %s" % (e)) # Define the NWB file identifier as the filename, as this should be unique nwb_identifier = path.split(tdt_tsq_files[0])[1] # unique file identifier # Initialize the NWB file nwb_io = [] try: if not overwrite and path.isfile(nwb_file_name): raise FileExistsError( "Can't update basic attributes of NWB file. Create new NWB file if you need to change attributes." ) else: if verbose: print("Creating new NWB file %s..." % (nwb_file_name), end='') nwb_file_append = False nwb_io = NWBHDF5IO(nwb_file_name, mode='w') tdt_notes = '' if 'Note' in tdt_data.epocs.keys(): for cur_note in tdt_data.epocs.Note: tdt_notes = tdt_notes + cur_note.notes + '; ' nwb_file = NWBFile(nwb_session_description, nwb_identifier, tdt_data.info.start_date, file_create_date=datetime.now(tzlocal()), experimenter=experimenter, subject=cur_subject, lab=lab, institution=institution, source_script='ConvertTDTToNWB.py', source_script_file_name='ConvertTDTToNWB.py', notes=notes + tdt_notes) if verbose: print("done.") except: # catch *all* exceptions e = sys.exc_info()[0] if nwb_io: nwb_io.close() tdt_data.clear() raise FileExistsError("Couldn't open NWB file. Error: %s" % e) if verbose: print("Created NWB file.") # Create device in the NWB file device = nwb_file.create_device(name='TDT') if verbose: print("Created device.") # Make sure electrode input is provided and valid if (not electrode_info) or not (type(electrode_info) is list): if verbose: print("Creating electrode information from directory.") # Grab information about SEV files tdt_sev_files = [ f for f in listdir(tdt_block_dir) if path.splitext(f)[1] == '.sev' ] electrode_list = [] for sev_ind, sev_file in enumerate(tdt_sev_files): sev_match = re.search(".+_RAW(\\d+)_Ch(\\d+).sev", sev_file) electrode_list.append((int(sev_match.groups()[0]) - 1) * 16 + int(sev_match.groups()[1])) electrode_list = np.sort(electrode_list) # Create electrode information for each electrode electrode_info = [] for cur_elec in electrode_list: electrode_info.append({ 'x': 0.0, 'y': 0.0, 'z': 0.0, 'impedance': -1.0, 'location': 'unknown', 'group': 'electrodes', 'id': cur_elec, 'filtering': 'Unknown' }) if verbose: print("\tCreated %d electrodes." % (len(electrode_info))) # Make sure electrode group input is provided and valid if verbose: print("Processing electrode groups.") default_electrode_group = { 'name': 'default electrode group', 'description': 'Generic electrode group for ungrouped electrodes.', 'location': 'Unknown' } if (not electrode_group) or not (type(electrode_group) is list): electrode_group = [default_electrode_group] else: electrode_group.insert(0, default_electrode_group) # Fill in any missing information about electrodes ovr_elec_group_list = [ ] # will be used to keep track of electrode group list if verbose: print("Processing electrode information.") for cur_elec_info_ind, cur_elec_info in enumerate(electrode_info): # If id is not provided, then throw an error if ('id' not in cur_elec_info.keys()) or (not cur_elec_info['id']): tdt_data.clear() nwb_io.close() raise ValueError( "Couldn't process electrode inputs. Must provide IDs for all electrodes or pass empty array." ) # If filtering is not provided, add it from the file (can't with TDT) if ('filtering' not in cur_elec_info.keys()) or ( not cur_elec_info['filtering']): electrode_info[cur_elec_info_ind]['filtering'] = 'Unknown' # If other variables are not provided, just initialize them to defaults if ('x' not in cur_elec_info.keys()) or (not cur_elec_info['x']): electrode_info[cur_elec_info_ind]['x'] = 0.0 if ('y' not in cur_elec_info.keys()) or (not cur_elec_info['y']): electrode_info[cur_elec_info_ind]['y'] = 0.0 if ('z' not in cur_elec_info.keys()) or (not cur_elec_info['z']): electrode_info[cur_elec_info_ind]['z'] = 0.0 if ('location' not in cur_elec_info.keys()) or ( not cur_elec_info['location']): electrode_info[cur_elec_info_ind]['location'] = 'unknown' if ('impedance' not in cur_elec_info.keys()) or ( not cur_elec_info['impedance']): electrode_info[cur_elec_info_ind]['impedance'] = float(-1.0) if ('group' not in cur_elec_info.keys()) or (not cur_elec_info['group']): electrode_info[cur_elec_info_ind][ 'group'] = 'default electrode group' # Find the index to the electrode group grp_elec_ind = 0 while (grp_elec_ind < len(electrode_group)) and ( cur_elec_info['group'] != electrode_group[grp_elec_ind]['name']): grp_elec_ind = grp_elec_ind + 1 # If we made it past the end, this electrode group doesn't exist, put it in the default if grp_elec_ind >= len(electrode_group): grp_elec_ind = -1 # Save the index into group dictionary for easy reference electrode_info[cur_elec_info_ind][ 'electrode_group_index'] = grp_elec_ind ovr_elec_group_list.append(grp_elec_ind) # Create electrode groups nwb_electrode_group = [] if verbose: print("Creating electrode groups.") for cur_elec_group_ind, cur_elec_group in enumerate(electrode_group): # Create and add to our list nwb_electrode_group.append( nwb_file.create_electrode_group( cur_elec_group['name'], description=cur_elec_group['description'], location=cur_elec_group['location'], device=device)) if verbose: print("\tCreated %d electrode groups." % (len(electrode_group))) # Create electrodes in NWB file if verbose: print("Adding electrodes to NWB.") nwb_file_elec_list = [] for cur_elec_ind, cur_elec in enumerate(electrode_info): # Add electrode to NWB file nwb_file.add_electrode( id=cur_elec['id'], x=cur_elec['x'], y=cur_elec['y'], z=cur_elec['z'], imp=cur_elec['impedance'], location=cur_elec['location'], filtering=cur_elec['filtering'], group=nwb_electrode_group[cur_elec['electrode_group_index']]) # Keep track of electrodes entered so we can index for the electrode table nwb_file_elec_list.append(cur_elec['id']) if verbose: print("\tAdded %d electrodes." % (len(electrode_info))) # Close NSx file tdt_data.clear() # Write to file and close if verbose: print("\tWriting NWB file and closing.") nwb_io.write(nwb_file) nwb_io.close() return nwb_file_name
if inspect.isclass(self.model): self.model = self.model(self) if inspect.isclass(self.view): self.view = self.view() self.view.setModel(self.model) if inspect.isclass(self.controller): self.controller = self.controller(self.view) if __name__ == '__main__': from intake_bluesky.jsonl import BlueskyJSONLCatalog import glob class JSONLCatalogPlugin(BlueskyJSONLCatalog, CatalogPlugin): ... from qtpy.QtWidgets import QApplication qapp = QApplication([]) paths = glob.glob('/home/rp/data/Catalog Sample/abc/*.jsonl') model = JSONLCatalogPlugin(paths).model view = QListView() view.setModel(model) view.show() qapp.exec_()
if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) if fnmatch.fnmatch(file, self.pattern): return fullname class MouseEventFilter(QtCore.QObject): def eventFilter(self, obj, event): if event.type() == QtCore.QEvent.GraphicsSceneMousePress: #print("Mouse Click observed") return True return False if __name__ == "__main__": app = QApplication(sys.argv) #print("script location =", os.path.dirname(os.path.realpath(sys.argv[0]))) #print("help location =", os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "instructions.png")) screen = app.primaryScreen() size = screen.size() rect = screen.availableGeometry() #print("Screen size =", size.width(), "X", size.height()) #print("Available screen size =", rect.width(), "X", rect.height()) pix_ratio = screen.devicePixelRatio() currentPath = os.getcwd() if node() == 'MacBook-Pro.local': myapp = MyForm(size.width(), size.height() - 32, pix_ratio, currentPath) else: myapp = MyForm(size.width(), size.height(), pix_ratio, currentPath)
def import_data(self, filenames=None): """Import data from text file.""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd_or_home() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) if os.name == "nt": self.filename = remove_backslashes(self.filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() self.editor.new_value(var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() error_message = self.shellwidget.load_data(self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>" "The error message was:<br>%s") % (self.filename, error_message)) self.refresh_table()
import sys from qtpy.QtWidgets import QApplication, QWidget from ui_chat_widget import Ui_ChatWidget class ChatWidget(QWidget): def __init__(self, *args, **kwargs): super(ChatWidget, self).__init__(*args, **kwargs) self.ui = Ui_ChatWidget() self.ui.setupUi(self) if __name__ == "__main__": app = QApplication([]) chat = ChatWidget() chat.show() sys.exit(app.exec_())
# Create a stream handler (attaches to sys.stderr by default) stream_log_level = DEFAULT_STREAM_LOG_LEVEL # See if we have the stream logging level available to us stream_log_settings = logging_settings.get(STREAM_LOG_LEVEL_SETTINGS_NAME, {}).get("value") if logging_settings and stream_log_settings: stream_log_level = stream_log_settings stream_handler = logging.StreamHandler() stream_handler.setLevel(stream_log_level) # minimum level shown stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) trayicon = None if "qtpy" in sys.modules: from qtpy.QtWidgets import QApplication if QApplication.instance(): from qtpy.QtWidgets import QSystemTrayIcon from qtpy.QtGui import QIcon, QPixmap from xicam.gui.static import path trayicon = QSystemTrayIcon(QIcon(QPixmap(str(path("icons/cpu.png"))))) # TODO: better icon _thread_count = 0 def _increment_thread(): global _thread_count _thread_count += 1 return _thread_count
Warnings: For this function to work with Spyder, *Graphics backend* option of Spyder must be set to *inline*. """ if model is None: model = mx.cur_model() view = get_modeltree(model) app = QApplication.instance() if not app: raise RuntimeError("QApplication does not exist.") view.show() app.exec_() if __name__ == "__main__": model, space = mx.new_model("Fibonacci"), mx.new_space() @mx.defcells def fibo(x): if x == 0 or x == 1: return x else: return fibo[x - 1] + fibo[x - 2] app = QApplication.instance() if not app: app = QApplication(sys.argv) show_tree()
if self.ui.stock_option_combobox.currentText() == u"复权": menu.addAction(QAction("Kline", menu, checkable=True)) menu.addAction(QAction("Open", menu, checkable=True)) menu.addAction(QAction("Close", menu, checkable=True)) menu.addAction(QAction("High", menu, checkable=True)) menu.addAction(QAction("Low", menu, checkable=True)) menu.addAction(QAction("Volume", menu, checkable=True)) menu.addAction(QAction("Amount", menu, checkable=True)) if self.ui.stock_option_combobox.currentText() == u"分笔数据": menu.addAction(QAction("分笔", menu, checkable=True)) if self.ui.stock_option_combobox.currentText() == u"历史分钟": menu.addAction(QAction("Kline", menu, checkable=True)) menu.addAction(QAction("Open", menu, checkable=True)) menu.addAction(QAction("Close", menu, checkable=True)) menu.addAction(QAction("High", menu, checkable=True)) menu.addAction(QAction("Low", menu, checkable=True)) menu.addAction(QAction("Volume", menu, checkable=True)) menu.addAction(QAction("Amount", menu, checkable=True)) if self.ui.stock_option_combobox.currentText() == u"十大股东": menu.addAction(QAction("季度饼图", menu, checkable=True)) #menu.addAction(QAction("持股比例", menu, checkable=True)) menu.triggered.connect( lambda action: self.addActionSelected(action, collec)) menu.exec_(self.ui.stocks_tree.viewport().mapToGlobal(position)) app = QApplication(sys.argv) w = MyUi() w.show() sys.exit(app.exec_())
self.le.changed.connect(self._on_le_change) right = Container(widgets=[self.le, self.pt], labels=False) self.cb = make_checkboxes(self.pt) self.cb.native.layout().addStretch() self.cb.native.layout().setSpacing(0) self.pt.show() self.cb.show() self._container = Container( layout="horizontal", widgets=[self.cb, right], labels=False ) self._container.margins = 0, 0, 0, 0 self.setLayout(QHBoxLayout()) self.setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self._container.native) def _on_le_change(self, value: str): self.pt.filter_string = value if __name__ == "__main__": from pymmcore_plus import CMMCorePlus # noqa from qtpy.QtWidgets import QApplication app = QApplication([]) mmcore = CMMCorePlus() mmcore.loadSystemConfiguration("tests/test_config.cfg") pb = PropBrowser(mmcore) pb.show() app.exec()