Ejemplo n.º 1
0
 def test_qsettings(self):
     s = QSettings()
     s.setValue("one", 1)
     s.setValue("one-half", 0.5)
     s.setValue("empty", "")
     s.setValue("true", True)
     s.sync()
     del s
     s = QSettings()
     self.assertEqual(s.value("one", type=int), 1)
     self.assertEqual(s.value("one-half", type=float), 0.5)
     self.assertEqual(s.value("empty", type=str), "")
     self.assertEqual(s.value("true", type=bool), True)
Ejemplo n.º 2
0
def save_plot(data, file_formats, filename=""):
    _LAST_DIR_KEY = "directories/last_graph_directory"
    _LAST_FILTER_KEY = "directories/last_graph_filter"
    settings = QSettings()
    start_dir = settings.value(_LAST_DIR_KEY, filename)
    if not start_dir or \
            (not os.path.exists(start_dir) and
             not os.path.exists(os.path.split(start_dir)[0])):
        start_dir = os.path.expanduser("~")
    last_filter = settings.value(_LAST_FILTER_KEY, "")
    filename, writer, filter = \
        filedialogs.get_file_name(start_dir, last_filter, file_formats)
    if not filename:
        return
    try:
        writer.write(filename, data)
    except Exception as e:
        mb = QMessageBox(
            None,
            windowTitle="Error",
            text='Error occurred while saving file "{}": {}'.format(filename, e),
            detailedText=traceback.format_exc(),
            icon=QMessageBox.Critical)
        mb.exec_()
    else:
        settings.setValue(_LAST_DIR_KEY, os.path.split(filename)[0])
        settings.setValue(_LAST_FILTER_KEY, filter)
    def test_settings_model(self):
        store = QSettings(
            QSettings.IniFormat,
            QSettings.UserScope,
            "biolab.si",
            "Orange Canvas UnitTests",
        )

        defaults = [
            config_slot("S1", bool, True, "Something"),
            config_slot("S2", str, "I an not a String",
                        "Disregard the string."),
        ]

        settings = Settings(defaults=defaults, store=store)
        model = UserSettingsModel(settings=settings)

        self.assertEqual(model.rowCount(), len(settings))

        view = QTreeView()
        view.setHeaderHidden(False)

        view.setModel(model)

        view.show()
        self.app.exec_()
    def test_qsettings_type(self):
        """
        Test if QSettings as exported by qtcompat has the 'type' parameter.
        """
        with tempfile.NamedTemporaryFile("w+b", suffix=".ini",
                                         delete=False) as f:
            settings = QSettings(f.name, QSettings.IniFormat)
            settings.setValue("bar", "foo")

            self.assertEqual(settings.value("bar", type=str), "foo")
            settings.setValue("frob", 4)

            del settings
            settings = QSettings(f.name, QSettings.IniFormat)
            self.assertEqual(settings.value("bar", type=str), "foo")
            self.assertEqual(settings.value("frob", type=int), 4)
Ejemplo n.º 5
0
    def write_statistics(self):
        """
        Write the statistics session to file, and clear it.
        """
        if not self.is_enabled():
            return

        statistics_path = self.filename()
        statistics = {
            "Date": str(datetime.now().date()),
            "Application Version": QCoreApplication.applicationVersion(),
            "Operating System": platform.system() + " " + platform.release(),
            "Launch Count": QSettings().value('startup/launch-count', 0, type=int),
            "Session": self._actions
        }

        if os.path.isfile(statistics_path):
            with open(statistics_path) as f:
                data = json.load(f)
        else:
            data = []

        data.append(statistics)

        with open(statistics_path, 'w') as f:
            json.dump(data, f)

        self.drop_statistics()
Ejemplo n.º 6
0
    def open_report(self):
        """
        Present an 'Open report' dialog to the user, load a '.report' file
        (as saved by OWReport) and create a new canvas window associated
        with the OWReport instance.
        """
        settings = QSettings()
        KEY = "report/file-dialog-dir"
        start_dir = settings.value(KEY, "", type=str)
        dlg = QFileDialog(
            self,
            windowTitle=self.tr("Open Report"),
            acceptMode=QFileDialog.AcceptOpen,
            fileMode=QFileDialog.ExistingFile,
        )
        if os.path.isdir(start_dir):
            dlg.setDirectory(start_dir)

        dlg.setWindowModality(Qt.ApplicationModal)
        dlg.setNameFilters(["Report (*.report)"])

        def accepted():
            directory = dlg.directory().absolutePath()
            filename = dlg.selectedFiles()[0]
            settings.setValue(KEY, directory)
            self._open_report(filename)

        dlg.accepted.connect(accepted)
        dlg.exec()
Ejemplo n.º 7
0
    def __quicktipOnce(self):
        filename = os.path.join(settings.widget_settings_dir(),
                                "user-session-state.ini")
        namespace = (
            "user-message-history/{0.__module__}.{0.__qualname__}".format(
                type(self)))
        session_hist = QSettings(filename, QSettings.IniFormat)
        session_hist.beginGroup(namespace)
        messages = self.UserAdviceMessages

        def _ispending(msg):
            return not session_hist.value("{}/confirmed".format(
                msg.persistent_id),
                                          defaultValue=False,
                                          type=bool)

        messages = [msg for msg in messages if _ispending(msg)]

        if not messages:
            return

        message = messages[self.__msgchoice % len(messages)]
        self.__msgchoice += 1

        self.__showMessage(message)

        def _userconfirmed():
            session_hist = QSettings(filename, QSettings.IniFormat)
            session_hist.beginGroup(namespace)
            session_hist.setValue("{}/confirmed".format(message.persistent_id),
                                  True)
            session_hist.sync()

        self.__msgwidget.accepted.connect(_userconfirmed)
Ejemplo n.º 8
0
    def __init__(
        self,
        model_name: str,
        max_parallel_requests: int,
        server_url: str,
        embedder_type: str,
    ) -> None:
        self.server_url = getenv("ORANGE_EMBEDDING_API_URL", server_url)
        self._model = model_name
        self.embedder_type = embedder_type

        # remove in 3.34
        self._cancelled = False

        self.machine_id = None
        try:
            self.machine_id = QSettings().value(
                "error-reporting/machine-id", "", type=str) or str(
                    uuid.getnode())
        except TypeError:
            self.machine_id = str(uuid.getnode())
        self.session_id = str(random.randint(1, int(1e10)))

        self._cache = EmbedderCache(model_name)

        # default embedding timeouts are too small we need to increase them
        self.timeout = 180
        self.max_parallel_requests = max_parallel_requests

        self.content_type = None  # need to be set in a class inheriting
Ejemplo n.º 9
0
    def accept(self):
        super().accept()
        F = self.DataField
        data = self._data.copy()

        if QSettings().value('error-reporting/add-scheme', True, type=bool):
            data[F.WIDGET_SCHEME] = data['_' + F.WIDGET_SCHEME]
        else:
            data.pop(F.WIDGET_SCHEME, None)
        del data['_' + F.WIDGET_SCHEME]

        def _post_report(data):
            MAX_RETRIES = 2
            for _retry in range(MAX_RETRIES):
                try:
                    urlopen(REPORT_POST_URL,
                            timeout=10,
                            data=urlencode(data).encode('utf8'))
                except Exception as e:
                    if _retry == MAX_RETRIES - 1:
                        e.__context__ = None
                        log.exception('Error reporting failed', exc_info=e)
                    time.sleep(10)
                    continue
                break

        Thread(target=_post_report, args=(data, )).start()
Ejemplo n.º 10
0
def swp_name(canvas):
    document = canvas.current_document()
    if document.path():
        filename = os.path.basename(document.path())
        dirname = os.path.dirname(document.path())
        return os.path.join(dirname, '.' + filename + ".swp.p")
    # else it's a scratch workflow

    if not QSettings().value('startup/load-crashed-workflows', True,
                             type=bool):
        return None

    global canvas_scratch_name_memo
    if canvas in canvas_scratch_name_memo:
        return canvas_scratch_name_memo[canvas]

    swpname = scratch_swp_base_name()

    i = 0
    while os.path.exists(swpname + '.' + str(i)):
        i += 1
    swpname += '.' + str(i)

    canvas_scratch_name_memo[canvas] = swpname

    return swpname
Ejemplo n.º 11
0
    def __init__(
        self,
        model_name: str,
        max_parallel_requests: int,
        server_url: str,
        embedder_type: str,
    ) -> None:
        self.server_url = getenv("ORANGE_EMBEDDING_API_URL", server_url)
        self._model = model_name
        self.embedder_type = embedder_type

        # attribute that offers support for cancelling the embedding
        # if ran in another thread
        self._cancelled = False
        self.machine_id = QSettings().value(
            "error-reporting/machine-id", "", type=str) or str(uuid.getnode())
        self.session_id = str(random.randint(1, 1e10))

        self._cache = EmbedderCache(model_name)

        # default embedding timeouts are too small we need to increase them
        self.timeout = 60
        self.num_parallel_requests = 0
        self.max_parallel = max_parallel_requests
        self.content_type = None  # need to be set in a class inheriting
Ejemplo n.º 12
0
    def send_statistics(url):
        """Send the statistics to the remote at `url`"""
        import json
        import requests
        settings = QSettings()
        if not settings.value(
                "error-reporting/send-statistics", False, type=bool):
            log.info("Not sending usage statistics (preferences setting).")
            return
        if not UsageStatistics.is_enabled():
            log.info("Not sending usage statistics (disabled).")
            return

        usage = UsageStatistics()
        data = usage.load()
        for d in data:
            d["Orange Version"] = d.pop("Application Version", "")
        try:
            r = requests.post(url, files={'file': json.dumps(data)})
            if r.status_code != 200:
                log.warning(
                    "Error communicating with server while attempting to send "
                    "usage statistics.")
                return
            # success - wipe statistics file
            log.info("Usage statistics sent.")
            with open(usage.filename(), 'w', encoding="utf-8") as f:
                json.dump([], f)
        except (ConnectionError, requests.exceptions.RequestException):
            log.warning(
                "Connection error while attempting to send usage statistics.")
        except Exception:  # pylint: disable=broad-except
            log.warning("Failed to send usage statistics.", exc_info=True)
    def __init__(self, model="inception-v3", layer="penultimate",
                 server_url='api.garaza.io:443'):
        super().__init__(server_url)
        model_settings = self._get_model_settings_confidently(model, layer)
        self._model = model
        self._layer = layer
        self._target_image_size = model_settings['target_image_size']

        cache_file_path = self._cache_file_blueprint.format(model, layer)
        self._cache_file_path = join(cache_dir(), cache_file_path)
        self._cache_dict = self._init_cache()

        self._session = cachecontrol.CacheControl(
            requests.session(),
            cache=cachecontrol.caches.FileCache(
                join(cache_dir(), __name__ + ".ImageEmbedder.httpcache"))
        )

        # attribute that offers support for cancelling the embedding
        # if ran in another thread
        self.cancelled = False
        self.machine_id = \
            QSettings().value('error-reporting/machine-id', '', type=str)  \
            or str(uuid.getnode())
        self.session_id = None
Ejemplo n.º 14
0
def setup_notifications():
    settings = QSettings()
    # data collection permission
    if not settings.value(
            "error-reporting/permission-requested", False, type=bool):
        notif = Notification(icon=QIcon(
            resource_filename("canvas/icons/statistics-request.png")),
                             title="Anonymous Usage Statistics",
                             text="Do you wish to opt-in to sharing "
                             "statistics about how you use Orange? "
                             "All data is anonymized and used "
                             "exclusively for understanding how users "
                             "interact with Orange.",
                             accept_button_label="Allow",
                             reject_button_label="No")

        def handle_permission_response(role):
            if role != notif.DismissRole:
                settings.setValue("error-reporting/permission-requested", True)
            if role == notif.AcceptRole:
                UsageStatistics.set_enabled(True)
                settings.setValue("error-reporting/send-statistics", True)

        notif.clicked.connect(handle_permission_response)
        canvas.notification_server_instance.registerNotification(notif)
Ejemplo n.º 15
0
 def __init__(self):
     enabled = QSettings().value('add-ons/allow-conda',
                                 True, type=bool)
     if enabled:
         self.conda = self._find_conda()
     else:
         self.conda = None
Ejemplo n.º 16
0
 def __init__(self):
     enabled = QSettings().value('add-ons/allow-conda-experimental',
                                 False, type=bool)
     if enabled:
         self.conda = self._find_conda()
     else:
         self.conda = None
Ejemplo n.º 17
0
def fix_set_proxy_env():
    """
    Set http_proxy/https_proxy environment variables (for requests, pip, ...)
    from user-specified settings or, if none, from system settings on OS X
    and from registry on Windos.
    """
    # save default proxies so that setting can be reset
    global default_proxies
    if default_proxies is None:
        default_proxies = getproxies(
        )  # can also read windows and macos settings

    settings = QSettings()
    proxies = getproxies()
    for scheme in set(["http", "https"]) | set(proxies):
        from_settings = settings.value("network/" + scheme + "-proxy",
                                       "",
                                       type=str)
        from_default = default_proxies.get(scheme, "")
        env_scheme = scheme + '_proxy'
        if from_settings:
            os.environ[env_scheme] = from_settings
        elif from_default:
            os.environ[
                env_scheme] = from_default  # crucial for windows/macos support
        else:
            os.environ.pop(env_scheme, "")
Ejemplo n.º 18
0
def show_survey():
    # If run for the first time, open a browser tab with a survey
    settings = QSettings()
    show_survey = settings.value("startup/show-survey", True, type=bool)
    if show_survey:
        question = QMessageBox(
            QMessageBox.Question, 'Orange Survey',
            'We would like to know more about how our software is used.\n\n'
            'Would you care to fill our short 1-minute survey?',
            QMessageBox.Yes | QMessageBox.No)
        question.setDefaultButton(QMessageBox.Yes)
        later = question.addButton('Ask again later', QMessageBox.NoRole)
        question.setEscapeButton(later)

        def handle_response(result):
            if result == QMessageBox.Yes:
                success = QDesktopServices.openUrl(
                    QUrl("https://orange.biolab.si/survey/short.html"))
                settings.setValue("startup/show-survey", not success)
            else:
                settings.setValue("startup/show-survey",
                                  result != QMessageBox.No)

        question.finished.connect(handle_response)
        question.show()
        return question
Ejemplo n.º 19
0
def check_for_updates():
    settings = QSettings()
    check_updates = settings.value('startup/check-updates', True, type=bool)
    last_check_time = settings.value('startup/last-update-check-time',
                                     0,
                                     type=int)
    ONE_DAY = 86400

    if check_updates and time.time() - last_check_time > ONE_DAY:
        settings.setValue('startup/last-update-check-time', int(time.time()))

        class GetLatestVersion(QThread):
            resultReady = pyqtSignal(str)

            def run(self):
                try:
                    request = Request('https://orange.biolab.si/version/',
                                      headers={
                                          'Accept': 'text/plain',
                                          'Accept-Encoding': 'gzip, deflate',
                                          'Connection': 'close',
                                          'User-Agent': ua_string()
                                      })
                    contents = urlopen(request, timeout=10).read().decode()
                # Nothing that this fails with should make Orange crash
                except Exception:  # pylint: disable=broad-except
                    log.exception('Failed to check for updates')
                else:
                    self.resultReady.emit(contents)

        def compare_versions(latest):
            version = pkg_resources.parse_version
            skipped = settings.value('startup/latest-skipped-version',
                                     "",
                                     type=str)
            if version(latest) <= version(current) or \
                    latest == skipped:
                return

            notif = Notification(
                title='橙现智能有更新版本',
                text='菜单栏点击: 选项 -> 升级与插件, 选中 orange3-zh 升级',
                icon=QIcon(resource_filename("canvas/icons/update.png")))

            def handle_click(role):
                if role == notif.RejectRole:
                    settings.setValue('startup/latest-skipped-version', latest)
                if role == notif.AcceptRole:
                    QDesktopServices.openUrl(
                        QUrl("https://orange.biolab.si/download/"))

            notif.clicked.connect(handle_click)
            canvas.notification_server_instance.registerNotification(notif)

        thread = GetLatestVersion()
        thread.resultReady.connect(compare_versions)
        thread.start()
        return thread
    return None
Ejemplo n.º 20
0
 def save(self):
     fname, _ = QFileDialog.getSaveFileName(
         self, "File name", self._start_dir(),
         "Variable definitions (*.colors)")
     if not fname:
         return
     QSettings().setValue("colorwidget/last-location",
                          os.path.split(fname)[0])
     self._save_var_defs(fname)
Ejemplo n.º 21
0
def ua_string():
    is_anaconda = 'Continuum' in sys.version or 'conda' in sys.version
    return 'Orange{orange_version}:Python{py_version}:{platform}:{conda}:{uuid}'.format(
        orange_version=current,
        py_version='.'.join(str(a) for a in sys.version_info[:3]),
        platform=sys.platform,
        conda='Anaconda' if is_anaconda else '',
        uuid=QSettings().value("error-reporting/machine-id", "", str),
    )
Ejemplo n.º 22
0
 def setUp(self):
     self._stack = ExitStack().__enter__()
     # patch `_local_settings` to avoid side effects, across tests
     fname = self._stack.enter_context(named_file(""))
     s = QSettings(fname, QSettings.IniFormat)
     self._stack.enter_context(
         mock.patch.object(owcsvimport.OWCSVFileImport, "_local_settings",
                           lambda *a: s))
     self.widget = self.create_widget(owcsvimport.OWCSVFileImport)
Ejemplo n.º 23
0
    def __init__(self, parent=None, defaults=(), path=None, store=None):
        super().__init__(parent)
        if store is None:
            store = QSettings()

        path = (path or "").rstrip("/")

        self.__path = path
        self.__defaults = dict([(slot.key, slot) for slot in defaults])
        self.__store = store
Ejemplo n.º 24
0
def setup_notifications():
    settings = QSettings()
    # If run for the fifth time, prompt short survey
    show_survey = settings.value("startup/show-short-survey", True, type=bool) and \
                  settings.value("startup/launch-count", 0, type=int) >= 5
    if show_survey:
        surveyDialogButtons = NotificationWidget.Ok | NotificationWidget.Close
        surveyDialog = NotificationWidget(
            icon=QIcon(gui.resource_filename("icons/information.png")),
            title="Survey",
            text="We want to understand our users better.\n"
            "Would you like to take a short survey?",
            standardButtons=surveyDialogButtons)

        def handle_survey_response(button):
            if surveyDialog.buttonRole(
                    button) == NotificationWidget.AcceptRole:
                success = QDesktopServices.openUrl(
                    QUrl("https://orange.biolab.si/survey/short.html"))
                settings.setValue("startup/show-short-survey", not success)
            elif surveyDialog.buttonRole(
                    button) == NotificationWidget.RejectRole:
                settings.setValue("startup/show-short-survey", False)

        surveyDialog.clicked.connect(handle_survey_response)

        NotificationOverlay.registerNotification(surveyDialog)

    # data collection permission
    if not settings.value(
            "error-reporting/permission-requested", False, type=bool):
        permDialogButtons = NotificationWidget.Ok | NotificationWidget.Close
        permDialog = NotificationWidget(
            icon=QIcon(gui.resource_filename("../../distribute/icon-48.png")),
            title="Anonymous Usage Statistics",
            text="Do you wish to opt-in to sharing "
            "statistics about how you use Orange?\n"
            "All data is anonymized and used "
            "exclusively for understanding how users "
            "interact with Orange.",
            standardButtons=permDialogButtons)
        btnOK = permDialog.button(NotificationWidget.AcceptRole)
        btnOK.setText("Allow")

        def handle_permission_response(button):
            if permDialog.buttonRole(button) != permDialog.DismissRole:
                settings.setValue("error-reporting/permission-requested", True)
            if permDialog.buttonRole(button) == permDialog.AcceptRole:
                UsageStatistics.set_enabled(True)
                settings.setValue("error-reporting/send-statistics", True)

        permDialog.clicked.connect(handle_permission_response)

        NotificationOverlay.registerNotification(permDialog)
Ejemplo n.º 25
0
def ua_string():
    settings = QSettings()

    is_anaconda = 'Continuum' in sys.version or 'conda' in sys.version
    machine_id = settings.value("reporting/machine-id", "", str)
    return 'Orange{orange_version}:Python{py_version}:{platform}:{conda}:{uuid}'.format(
        orange_version=current,
        py_version='.'.join(str(a) for a in sys.version_info[:3]),
        platform=sys.platform,
        conda='Anaconda' if is_anaconda else '',
        uuid=machine_id if settings.value("reporting/send-statistics", False, bool) else ''
    )
Ejemplo n.º 26
0
def open_link(url: QUrl):
    if url.scheme() == "orange":
        # define custom actions within Orange here
        if url.host() == "enable-statistics":
            settings = QSettings()

            settings.setValue("reporting/send-statistics", True)
            UsageStatistics.set_enabled(True)

            if not settings.contains('reporting/machine-id'):
                settings.setValue('reporting/machine-id', str(uuid.uuid4()))
    else:
        QDesktopServices.openUrl(url)
Ejemplo n.º 27
0
def check_for_updates():
    settings = QSettings()
    check_updates = settings.value('startup/check-updates', True, type=bool)
    last_check_time = settings.value('startup/last-update-check-time',
                                     0,
                                     type=int)
    ONE_DAY = 86400

    if check_updates and time.time() - last_check_time > ONE_DAY:
        settings.setValue('startup/last-update-check-time', int(time.time()))

        from urllib.request import urlopen
        from Orange.version import version as current

        class GetLatestVersion(QThread):
            resultReady = pyqtSignal(str)

            def run(self):
                try:
                    self.resultReady.emit(
                        urlopen('https://orange.biolab.si/version/',
                                timeout=10).read().decode())
                # Nothing that this fails with should make Orange crash
                except Exception:  # pylint: disable=broad-except
                    log.exception('Failed to check for updates')

        def compare_versions(latest):
            version = pkg_resources.parse_version
            if version(latest) <= version(current):
                return
            question = QMessageBox(
                QMessageBox.Information,
                'Orange Update Available',
                'A newer version of Orange is available.<br><br>'
                '<b>Current version:</b> {}<br>'
                '<b>Latest version:</b> {}'.format(current, latest),
                textFormat=Qt.RichText)
            ok = question.addButton('Download Now', question.AcceptRole)
            question.setDefaultButton(ok)
            question.addButton('Remind Later', question.RejectRole)
            question.finished.connect(
                lambda: question.clickedButton() == ok and QDesktopServices.
                openUrl(QUrl("https://orange.biolab.si/download/")))
            question.show()

        thread = GetLatestVersion()
        thread.resultReady.connect(compare_versions)
        thread.start()
        return thread
def check_for_updates():
    settings = QSettings()
    check_updates = settings.value('startup/check-updates', True, type=bool)
    last_check_time = settings.value('startup/last-update-check-time',
                                     0,
                                     type=int)
    ONE_DAY = 86400

    if check_updates and time.time() - last_check_time > ONE_DAY:
        settings.setValue('startup/last-update-check-time', int(time.time()))

        thread = GetLatestVersion()
        thread.resultReady.connect(compare_versions)
        thread.start()
        return thread
    def __init__(self, model, model_settings, layer, server_url):
        super().__init__(server_url)
        self._model = model
        self._layer = layer

        self._target_image_size = model_settings['target_image_size']
        # attribute that offers support for cancelling the embedding
        # if ran in another thread
        self.cancelled = False
        self.machine_id = \
            QSettings().value('error-reporting/machine-id', '', type=str) \
            or str(uuid.getnode())
        self.session_id = None

        self._image_loader = ImageLoader()
        self._cache = EmbedderCache(model, layer)
Ejemplo n.º 30
0
    def max_active(self) -> int:
        value = self.__max_running  # type: Optional[int]
        if value is None:
            value = mapping_get(os.environ, "MAX_ACTIVE_NODES", int, None)
        if value is None:
            s = QSettings()
            s.beginGroup(__name__)
            value = s.value("max-active-nodes", defaultValue=1, type=int)

        if value < 0:
            ccount = os.cpu_count()
            if ccount is None:
                return 1
            else:
                return max(1, ccount + value)
        else:
            return max(1, value)