Esempio n. 1
0
    def report_issue(self):
        if PY3:
            from urllib.parse import quote
        else:
            from urllib import quote     # analysis:ignore

        issue_template = """\
## Description

- *What steps will reproduce the problem?*
1.
2.
3.

- *What is the expected output? What do you see instead?*


- *Please provide any additional information below*


## Version and main components

- Conda Package Manager Version:  {version}
- Conda Version:  {conda version}
- Python Version:  {python version}
- Qt Version    :  {Qt version}
- QtPy Version    :  {QtPy version}
"""
        url = QUrl("https://github.com/spyder-ide/conda-manager/issues/new")
        url.addEncodedQueryItem("body", quote(issue_template))
        QDesktopServices.openUrl(url)
    def download(self, url, path):
        """Download url and save data to path."""
        # original_url = url
#        print(url)
        qurl = QUrl(url)
        url = to_text_string(qurl.toEncoded(), encoding='utf-8')

        logger.debug(str((url, path)))
        if url in self._workers:
            while not self._workers[url].finished:
                return self._workers[url]

        worker = DownloadWorker(url, path)

        # Check download folder exists
        folder = os.path.dirname(os.path.abspath(path))
        if not os.path.isdir(folder):
            os.makedirs(folder)

        request = QNetworkRequest(qurl)
        self._head_requests[url] = request
        self._paths[url] = path
        self._workers[url] = worker
        self._manager.head(request)
        self._timer.start()

        return worker
Esempio n. 3
0
 def __init__(self):
     super(MyUi, self).__init__()
     self.ui = Ui_Main_Window()
     self.connection = None
     self.ui.setup_ui(self)
     self._init_db()
     self.ui.stocks_tree.clear()
     self.ui.search_btn.clicked.connect(lambda: self.search_weibo())
     self.ui.stocks_tree.itemClicked.connect(self.onItemClick)
     current_date = time.strftime("%Y/%m/%d")
     date_obj = datetime.strptime(current_date, "%Y/%m/%d")
     past = date_obj - timedelta(days=7)
     past_time = datetime.strftime(past, "%Y/%m/%d")
     self.QPastDate = QDate.fromString(past_time, "yyyy/MM/dd")
     self.QCurDate = QDate.fromString(current_date, "yyyy/MM/dd")
     self.ui.stocks_tree.setContextMenuPolicy(Qt.CustomContextMenu)
     self.ui.stocks_tree.customContextMenuRequested.connect(self.openMenu)
     self.ui.start_date_edit.setDate(self.QPastDate)
     self.ui.end_date_edit.setDate(self.QCurDate)
     self.ui.start_date_edit.setCalendarPopup(True)
     self.ui.end_date_edit.setCalendarPopup(True)
     self.ui.search_edit_text.setText("6004376285")
     self.choice = 'Open'
     file_path = os.path.abspath(
         os.path.join(os.path.dirname(__file__),
                      "WeiboData/Gui/render.html"))  #path to read html file
     local_url = QUrl.fromLocalFile(file_path)
     self.ui.webView.load(local_url)
     self.ui.stock_option_combobox.currentIndexChanged.connect(
         lambda: self.modifycombo(self.QPastDate, self.QCurDate))
Esempio n. 4
0
    def load_url(self, url):
        if isinstance(url, QUrl):
            qurl = url
        else:
            qurl = QUrl(url)

        self.load(qurl)
Esempio n. 5
0
 def go_to(self, url_or_text):
     """Go to page *address*"""
     if is_text_string(url_or_text):
         url = QUrl(url_or_text)
     else:
         url = url_or_text
     self.webview.load(url)
Esempio n. 6
0
 def _hide_loading_page(self):
     """Hide animation shown while the kernel is loading."""
     self.infowidget.hide()
     self.shellwidget.show()
     self.infowidget.setHtml(BLANK,
                             QUrl.fromLocalFile(self.css_path))
     self.shellwidget.sig_prompt_ready.disconnect(self._hide_loading_page)
Esempio n. 7
0
 def set_info_page(self):
     """Set current info_page."""
     if self.info_page is not None:
         self.infowidget.setHtml(
             self.info_page,
             QUrl.fromLocalFile(self.css_path)
         )
Esempio n. 8
0
    def show_intro_message(self):
        intro_message = _("Here you can get help of any object by pressing "
                          "%s in front of it, either on the Editor or the "
                          "Console.%s"
                          "Help can also be shown automatically after writing "
                          "a left parenthesis next to an object. You can "
                          "activate this behavior in %s.")
        prefs = _("Preferences > Help")
        if sys.platform == 'darwin':
            shortcut = "Cmd+I"
        else:
            shortcut = "Ctrl+I"

        if self.is_rich_text_mode():
            title = _("Usage")
            tutorial_message = _("New to Spyder? Read our")
            tutorial = _("tutorial")
            intro_message = intro_message % (
                "<b>" + shortcut + "</b>", "<br><br>", "<i>" + prefs + "</i>")
            self.set_rich_text_html(
                usage(title,
                      intro_message,
                      tutorial_message,
                      tutorial,
                      css_path=self.css_path),
                QUrl.fromLocalFile(self.css_path))
        else:
            install_sphinx = "\n\n%s" % _("Please consider installing Sphinx "
                                          "to get documentation rendered in "
                                          "rich text.")
            intro_message = intro_message % (shortcut, "\n\n", prefs)
            intro_message += install_sphinx
            self.set_plain_text(intro_message, is_code=False)
def start_file(filename):
    """
    Generalized os.startfile for all platforms supported by Qt

    This function is simply wrapping QDesktopServices.openUrl

    Returns True if successful, otherwise returns False.
    """

    # We need to use setUrl instead of setPath because this is the only
    # cross-platform way to open external files. setPath fails completely on
    # Mac and doesn't open non-ascii files on Linux.
    # Fixes spyder-ide/spyder#740.
    url = QUrl()
    url.setUrl(filename)
    return QDesktopServices.openUrl(url)
Esempio n. 10
0
    def show_kernel_error(self, error):
        """Show kernel initialization errors in infowidget."""
        # Replace end of line chars with <br>
        eol = sourcecode.get_eol_chars(error)
        if eol:
            error = error.replace(eol, '<br>')

        # Don't break lines in hyphens
        # From https://stackoverflow.com/q/7691569/438386
        error = error.replace('-', '&#8209')

        # Create error page
        message = _("An error ocurred while starting the kernel")
        kernel_error_template = Template(KERNEL_ERROR)
        page = kernel_error_template.substitute(css_path=self.css_path,
                                                message=message,
                                                error=error)

        # Show error
        self.infowidget.setHtml(page, QUrl.fromLocalFile(self.css_path))
        self.shellwidget.hide()
        self.infowidget.show()

        # Tell the client we're in error mode
        self.is_error_shown = True
Esempio n. 11
0
 def startDrag(self, dropActions):
     """Reimplement Qt Method - handle drag event"""
     data = QMimeData()
     data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
     drag = QDrag(self)
     drag.setMimeData(data)
     drag.exec_()
Esempio n. 12
0
 def go_to(self, url_or_text):
     """Go to page utl."""
     if isinstance(url_or_text, str):
         url = QUrl(url_or_text)
     else:
         url = url_or_text
     self.notebookwidget.load(url)
Esempio n. 13
0
    def __init__(self, parent=None):
        super(DynATC, self).__init__(parent)

        if IN_DESIGNER:
            return

        self.atc_position = 0
        self.pocket = 1
        self.home = 0
        self.homing = 0
        self.pocket_slots = int(INIFILE.find("ATC", "POCKETS") or 12)

        self.engine().rootContext().setContextProperty("atc_spiner", self)
        qml_path = os.path.join(WIDGET_PATH, "atc.qml")
        url = QUrl.fromLocalFile(qml_path)

        self.setSource(url)  # Fixme fails on qtdesigner

        self.tool_table = None
        self.status_tool_table = None
        self.pockets = dict()
        self.tools = None

        self.pocketSig.emit(self.pocket_slots)

        for pocket in range(1, self.pocket_slots + 1):
            self.hideToolSig.emit(pocket)
Esempio n. 14
0
    def __init__(self,
                 parent,
                 CONF,
                 term_url='http://127.0.0.1:8070',
                 handler=None):
        """Webview main constructor."""
        super().__init__(parent)
        web_page = QWebEnginePage(self)
        self.setPage(web_page)
        self.source_text = ''
        self.parent = parent
        self.CONF = CONF
        self.shortcuts = self.create_shortcuts()
        self.channel = QWebChannel(self.page())
        self.page().setWebChannel(self.channel)
        self.channel.registerObject('handler', handler)

        self.term_url = QUrl(term_url)
        self.load(self.term_url)

        self.document = self.page()
        try:
            self.document.profile().clearHttpCache()
        except AttributeError:
            pass

        self.initial_y_pos = 0
        self.setFocusPolicy(Qt.ClickFocus)
Esempio n. 15
0
 def set_info_page(self):
     """Set current info_page."""
     if self.info_page is not None:
         self.infowidget.setHtml(
             self.info_page,
             QUrl.fromLocalFile(self.css_path)
         )
Esempio n. 16
0
    def GraphInit(self):
        self.K_graph = t2.My_plot()
        #加入列表
        self.K_lineTab = self.ui.GraphTab.insertTab(0, self.K_graph.win,
                                                    'graph')
        if self.GraphEnable == True:
            self.ui.pbar.setRange(0, 5)
            self.K_graph.setCodeDate(
                code='sh',
                start='%s' % self.startdate,
                end='%s' % self.enddate)
            self.ui.pbar.setValue(1)
            self.K_graph.Kline_plotting()
            self.ui.pbar.setValue(2)
            self.K_graph.update_plotting()
            self.ui.pbar.setValue(3)
            self.K_graph.macd_plotting()
            self.ui.pbar.setValue(4)
            self.K_graph.RSI_plotting()
            self.ui.pbar.setValue(5)

        else:
            pass
        #self.Top10H=Top10shareholder.Top10Holder
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "src\\Wakuang.html"))

        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
Esempio n. 17
0
 def reload_chart(self):
     file_path = os.path.abspath(
         os.path.join(os.path.dirname(__file__), "src\\render.html"))
     print(file_path)
     local_url = QUrl.fromLocalFile(file_path)
     self.ui.webView.load(local_url)
     return
Esempio n. 18
0
 def _hide_loading_page(self):
     """Hide animation shown while the kernel is loading."""
     self.infowidget.hide()
     self.shellwidget.show()
     self.infowidget.setHtml(self.blank_page,
                             QUrl.fromLocalFile(self.css_path))
     self.shellwidget.sig_prompt_ready.disconnect(self._hide_loading_page)
Esempio n. 19
0
 def go_to(self, url_or_text):
     """Go to page utl."""
     if is_text_string(url_or_text):
         url = QUrl(url_or_text)
     else:
         url = url_or_text
     self.notebookwidget.load(url)
Esempio n. 20
0
    def __init__(self, parent, term_url='http://127.0.0.1:8070', handler=None):
        """Webview main constructor."""
        WebView.__init__(self, parent)
        self.parent = parent
        self.copy_action = create_action(self,
                                         _("Copy text"),
                                         icon=ima.icon('editcopy'),
                                         triggered=self.copy,
                                         shortcut='Ctrl+Shift+C')
        self.paste_action = create_action(self,
                                          _("Paste text"),
                                          icon=ima.icon('editpaste'),
                                          triggered=self.paste,
                                          shortcut='Ctrl+Shift+V')
        if WEBENGINE:
            self.channel = QWebChannel(self.page())
            self.page().setWebChannel(self.channel)
            self.channel.registerObject('handler', handler)
        self.term_url = QUrl(term_url)
        self.load(self.term_url)

        if WEBENGINE:
            self.document = self.page()
            try:
                self.document.profile().clearHttpCache()
            except AttributeError:
                pass
        else:
            self.document = self.page().mainFrame()

        self.initial_y_pos = 0
        self.setFocusPolicy(Qt.ClickFocus)
Esempio n. 21
0
 def open_url(self, url):
     """
     Open link from action in default operating system browser.
     """
     if url is None:
         return
     QDesktopServices.openUrl(QUrl(url))
Esempio n. 22
0
    def show_kernel_error(self, error):
        """Show kernel initialization errors in infowidget."""
        # Replace end of line chars with <br>
        eol = sourcecode.get_eol_chars(error)
        if eol:
            error = error.replace(eol, '<br>')

        # Don't break lines in hyphens
        # From https://stackoverflow.com/q/7691569/438386
        error = error.replace('-', '&#8209')

        # Create error page
        message = _("An error ocurred while starting the kernel")
        kernel_error_template = Template(KERNEL_ERROR)
        page = kernel_error_template.substitute(css_path=self.css_path,
                                                message=message,
                                                error=error)

        # Show error
        self.infowidget.setHtml(page, QUrl.fromLocalFile(self.css_path))
        self.shellwidget.hide()
        self.infowidget.show()

        # Tell the client we're in error mode
        self.is_error_shown = True
Esempio n. 23
0
    def setHtml(self, html, baseUrl=QUrl()):
        """
        Reimplement Qt method to prevent WebEngine to steal focus
        when setting html on the page

        Solution taken from
        https://bugreports.qt.io/browse/QTBUG-52999
        """
        if WEBENGINE:
            if OLD_PYQT:
                self.setEnabled(False)
            super(WebView, self).setHtml(html, baseUrl)
            if OLD_PYQT:
                self.setEnabled(True)
        else:
            super(WebView, self).setHtml(html, baseUrl)

        # This is required to catch an error with PyQt 5.9, for which
        # it seems this functionality is not working.
        # Fixes spyder-ide/spyder#16703
        try:
            # The event filter needs to be installed every time html is set
            # because the proxy changes with new content.
            self.focusProxy().installEventFilter(self)
        except AttributeError:
            pass
Esempio n. 24
0
    def show_intro_message(self):
        intro_message = _("Here you can get help of any object by pressing "
                          "%s in front of it, either on the Editor or the "
                          "Console.%s"
                          "Help can also be shown automatically after writing "
                          "a left parenthesis next to an object. You can "
                          "activate this behavior in %s.")
        prefs = _("Preferences > Help")
        if sys.platform == 'darwin':
            shortcut = "Cmd+I"
        else:
            shortcut = "Ctrl+I"

        if self.is_rich_text_mode():
            title = _("Usage")
            tutorial_message = _("New to Spyder? Read our")
            tutorial = _("tutorial")
            intro_message = intro_message % ("<b>"+shortcut+"</b>", "<br><br>",
                                             "<i>"+prefs+"</i>")
            self.set_rich_text_html(usage(title, intro_message,
                                          tutorial_message, tutorial),
                                    QUrl.fromLocalFile(CSS_PATH))
        else:
            install_sphinx = "\n\n%s" % _("Please consider installing Sphinx "
                                          "to get documentation rendered in "
                                          "rich text.")
            intro_message = intro_message % (shortcut, "\n\n", prefs)
            intro_message += install_sphinx
            self.set_plain_text(intro_message, is_code=False)
Esempio n. 25
0
 def __init__(self, parent=None):
     super(Downloader, self).__init__(parent)
     self.manager = QNetworkAccessManager()
     self.url = 'http://localhost:9998/jpg/image.jpg'
     self.request = QNetworkRequest()
     self.request.setUrl(QUrl(self.url))
     self.buffer = QByteArray()
     self.reply = None
Esempio n. 26
0
 def connect_htp1(self):
     '''
     Connects to the websocket of the specified ip:port.
     '''
     self.ipAddress.setReadOnly(True)
     logger.info(f"Connecting to {self.ipAddress.text()}")
     self.__ws_client.open(
         QUrl(f"ws://{self.ipAddress.text()}/ws/controller"))
Esempio n. 27
0
def copy_files_clipboard(create_folders_files):
    """Fixture to copy files/folders into the clipboard"""
    file_paths = create_folders_files[0]
    file_content = QMimeData()
    file_content.setUrls([QUrl.fromLocalFile(fname) for fname in file_paths])
    cb = QApplication.clipboard()
    cb.setMimeData(file_content, mode=cb.Clipboard)
    return file_paths
Esempio n. 28
0
 def launch(self, uri, title):
     """
     Emit signal with youtube video identifier string.
     """
     qurl = QUrl(uri)
     QDesktopServices.openUrl(qurl)
     self.tracker.track_event('content', 'click', uri)
     self.sig_view_video.emit(uri, title)
Esempio n. 29
0
    def open_url(url):
        """
        Open link from action in default operating system browser.

        ADD TRACKING!.
        """
        if url:
            QDesktopServices.openUrl(QUrl(url))
Esempio n. 30
0
 def mouseReleaseEvent(self, event):
     """Ooen anchors when clicked."""
     if self.anchor:
         QDesktopServices.openUrl(QUrl(self.anchor))
         QApplication.setOverrideCursor(Qt.ArrowCursor)
         self.anchor = None
     else:
         super(ControlWidget, self).mouseReleaseEvent(event)
Esempio n. 31
0
 def open_login_page(self):
     """
     """
     conda_url = CONF.get('main', 'conda_url')
     url = "{0}/{1}".format(conda_url, self.username)
     qurl = QUrl(url)
     QDesktopServices.openUrl(qurl)
     self.tracker.track_event('content', 'clicked', url)
Esempio n. 32
0
 def handle_link_clicks(self, url):
     url = to_text_string(url.toString())
     if url == "spy://tutorial":
         self.show_tutorial()
     elif url.startswith('http'):
         programs.start_file(url)
     else:
         self.rich_text.webview.load(QUrl(url))
Esempio n. 33
0
    def text_to_url(self, text):
        """Convert text address into QUrl object"""
        if text != 'about:blank':
            text += '.html'
        if text.startswith('/'):
            text = text[1:]

        return QUrl(self.home_url.toString() + text)
Esempio n. 34
0
def copy_files_clipboard(create_folders_files):
    """Fixture to copy files/folders into the clipboard"""
    file_paths = create_folders_files[0]
    file_content = QMimeData()
    file_content.setUrls([QUrl.fromLocalFile(fname) for fname in file_paths])
    cb = QApplication.clipboard()
    cb.setMimeData(file_content, mode=cb.Clipboard)
    return file_paths
Esempio n. 35
0
 def helpClicked(self):
     try:
         from pymantidplot.proxies import showCustomInterfaceHelp
         showCustomInterfaceHelp("Filter Events")
     except ImportError:
         url = ("http://docs.mantidproject.org/nightly/interfaces/{}.html"
                "".format("Filter Events"))
         QDesktopServices.openUrl(QUrl(url))
Esempio n. 36
0
 def viewHtml(self, dictNote):
     htmlfn = dictNote['HTML']
     fn = os.path.join(self.path, htmlfn)
     if os.path.isfile(fn):
         url = QUrl.fromLocalFile(fn)
         self.wbrs.load(url)
     else:
         #self.wbrs.setHtml('') # blank page
         self.wbrs.setHtml(self.html_no)
Esempio n. 37
0
    def show_intro_message(self):
        """Show message on Help with the right shortcuts."""
        intro_message_eq = _("Here you can get help of any object by pressing "
                             "%s in front of it, either on the Editor or the "
                             "Console.%s")
        intro_message_dif = _(
            "Here you can get help of any object by pressing "
            "%s in front of it on the Editor, or %s in front "
            "of it on the Console.%s")
        intro_message_common = _(
            "Help can also be shown automatically after writing "
            "a left parenthesis next to an object. You can "
            "activate this behavior in %s.")
        prefs = _("Preferences > Help")

        shortcut_editor = self.get_conf('editor/inspect current object',
                                        section='shortcuts')
        shortcut_console = self.get_conf('console/inspect current object',
                                         section='shortcuts')

        if sys.platform == 'darwin':
            shortcut_editor = shortcut_editor.replace('Ctrl', 'Cmd')
            shortcut_console = shortcut_console.replace('Ctrl', 'Cmd')

        if self.get_conf('rich_mode'):
            title = _("Usage")
            tutorial_message = _("New to Spyder? Read our")
            tutorial = _("tutorial")
            if shortcut_editor == shortcut_console:
                intro_message = (intro_message_eq + intro_message_common) % (
                    "<b>" + shortcut_editor + "</b>", "<br><br>",
                    "<i>" + prefs + "</i>")
            else:
                intro_message = (intro_message_dif + intro_message_common) % (
                    "<b>" + shortcut_editor + "</b>", "<b>" + shortcut_console
                    + "</b>", "<br><br>", "<i>" + prefs + "</i>")

            self.set_rich_text_html(
                usage(title,
                      intro_message,
                      tutorial_message,
                      tutorial,
                      css_path=self.css_path),
                QUrl.fromLocalFile(self.css_path))
        else:
            install_sphinx = "\n\n%s" % _("Please consider installing Sphinx "
                                          "to get documentation rendered in "
                                          "rich text.")
            if shortcut_editor == shortcut_console:
                intro_message = (intro_message_eq + intro_message_common) % (
                    shortcut_editor, "\n\n", prefs)
            else:
                intro_message = (intro_message_dif + intro_message_common) % (
                    shortcut_editor, shortcut_console, "\n\n", prefs)

            intro_message += install_sphinx
            self.set_plain_text(intro_message, is_code=False)
Esempio n. 38
0
def start_file(filename):
    """
    Generalized os.startfile for all platforms supported by Qt

    This function is simply wrapping QDesktopServices.openUrl

    Returns True if successfull, otherwise returns False.
    """
    from qtpy.QtCore import QUrl
    from qtpy.QtGui import QDesktopServices

    # We need to use setUrl instead of setPath because this is the only
    # cross-platform way to open external files. setPath fails completely on
    # Mac and doesn't open non-ascii files on Linux.
    # Fixes Issue 740
    url = QUrl()
    url.setUrl(filename)
    return QDesktopServices.openUrl(url)
Esempio n. 39
0
    def __init__(self, plugin, name, history_filename, config_options,
                 additional_options, interpreter_versions,
                 connection_file=None, hostname=None,
                 menu_actions=None, slave=False):
        super(ClientWidget, self).__init__(plugin)
        SaveHistoryMixin.__init__(self)

        # --- Init attrs
        self.name = name
        self.history_filename = get_conf_path(history_filename)
        self.connection_file = connection_file
        self.hostname = hostname
        self.menu_actions = menu_actions
        self.slave = slave

        # --- Other attrs
        self.options_button = None
        self.stop_button = None
        self.stop_icon = ima.icon('stop')
        self.history = []

        # --- Widgets
        self.shellwidget = ShellWidget(config=config_options,
                                       additional_options=additional_options,
                                       interpreter_versions=interpreter_versions,
                                       local_kernel=True)
        self.shellwidget.hide()
        self.infowidget = WebView(self)
        self.set_infowidget_font()
        self.loading_page = self._create_loading_page()
        self.infowidget.setHtml(self.loading_page,
                                QUrl.fromLocalFile(CSS_PATH))

        # --- Layout
        vlayout = QVBoxLayout()
        toolbar_buttons = self.get_toolbar_buttons()
        hlayout = QHBoxLayout()
        for button in toolbar_buttons:
            hlayout.addWidget(button)
        vlayout.addLayout(hlayout)
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addWidget(self.shellwidget)
        vlayout.addWidget(self.infowidget)
        self.setLayout(vlayout)

        # --- Exit function
        self.exit_callback = lambda: plugin.close_client(client=self)

        # --- Signals
        # As soon as some content is printed in the console, stop
        # our loading animation
        document = self.get_control().document()
        document.contentsChange.connect(self._stop_loading_animation)
Esempio n. 40
0
    def __init__(self, plugin, name, history_filename, connection_file=None, 
                 hostname=None, sshkey=None, password=None, 
                 kernel_widget_id=None, menu_actions=None):
        super(IPythonClient, self).__init__(plugin)
        SaveHistoryMixin.__init__(self)
        self.options_button = None
        
        # stop button and icon
        self.stop_button = None
        self.stop_icon = ima.icon('stop')        
        self.connection_file = connection_file
        self.kernel_widget_id = kernel_widget_id
        self.hostname = hostname
        self.sshkey = sshkey
        self.password = password
        self.name = name
        self.get_option = plugin.get_option
        self.shellwidget = IPythonShellWidget(config=self.shellwidget_config(),
                                              local_kernel=False)
        self.shellwidget.hide()
        self.infowidget = WebView(self)
        self.menu_actions = menu_actions
        self.history_filename = get_conf_path(history_filename)
        self.history = []
        self.namespacebrowser = None

        self.set_infowidget_font()
        self.loading_page = self._create_loading_page()
        self.infowidget.setHtml(self.loading_page,
                                QUrl.fromLocalFile(CSS_PATH))

        vlayout = QVBoxLayout()
        toolbar_buttons = self.get_toolbar_buttons()
        hlayout = QHBoxLayout()
        for button in toolbar_buttons:
            hlayout.addWidget(button)
        vlayout.addLayout(hlayout)
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addWidget(self.shellwidget)
        vlayout.addWidget(self.infowidget)
        self.setLayout(vlayout)
        
        self.exit_callback = lambda: plugin.close_client(client=self)
Esempio n. 41
0
 def _show_loading_page(self):
     """Show animation while the kernel is loading."""
     self.shellwidget.hide()
     self.infowidget.show()
     self.infowidget.setHtml(self.loading_page,
                             QUrl.fromLocalFile(CSS_PATH))
Esempio n. 42
0
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd+"/time"):
            with open("time","r") as outfile:#reads current time
                history = cPickle.load(outfile)
            if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Pickle...")
                #with open("time","w") as infile: #update time
                    #cPickle.dump(datetime.now(),infile)

            else:
                print("More than 12 hours. Updating Pickle...")
                data = ts.get_industry_classified()
                with open("class","w+") as outfile:
                    cPickle.dump(data,outfile)
                now = datetime.now()
                with open("time", "w+") as outfile: #update time
                    cPickle.dump(now, outfile)

        else:
            print("No Pickle found!") #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            with open('class', 'w+') as outfile: #records pickle
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now,outfile)

        with open("class", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)

        curdate = time.strftime("%Y/%m/%d")  # gets current time to put into dateedit
        curdateQ = QDate.fromString(curdate,"yyyy/MM/dd")

        dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object

        past = dateobj - timedelta(days = 7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        pastQ = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values



        pastL = dateobj - timedelta(days=30)  # minus a month to start date
        pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
        pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")


        np_indexes = np.array([['sh', '上证指数', '大盘指数'],
                               ['sz', '深证成指', '大盘指数'],
                               ['hs300', '沪深300指数', '大盘指数'],
                               ['sz50', '上证50', '大盘指数'],
                               ['zxb', '中小板', '大盘指数'],
                               ['cyb', '创业板', '大盘指数']])
        indexes = df(data=np_indexes,
                     index=range(5000, 5006),
                     columns=["code", "name", "c_name"])
        series = indexes.append(series)
        list1_bfr = series["c_name"].tolist()  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1_bfr))
        list1.sort(key=list1_bfr.index)
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        self.init_treeWidget(list1,series)

        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
        #self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
        self.ui.init_code_btn.clicked.connect(lambda: self.code_sort_tree(series))
        self.ui.init_category_btn.clicked.connect(lambda: self.init_treeWidget(list1, series))

        self.ui.commandLinkButton.clicked.connect(self.classify)  #when the arrow button is clicked, trigger events


        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")
        self.ui.dateEdit.setDate(pastQL)
        self.ui.dateEdit_2.setDate(curdateQ)#populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(lambda: self.modifycombo(pastQL,pastQ))
Esempio n. 43
0
 def _on_sphinx_thread_html_ready(self, html_text):
     """Set our sphinx documentation based on thread result"""
     self._sphinx_thread.wait()
     self.set_rich_text_html(html_text, QUrl.fromLocalFile(CSS_PATH))