Exemplo n.º 1
0
    def verify_email_confirmation(self, code: str) -> Union[str, None]:
        '''
            If the corresponding email verification exist, create such user.
            If not - throws an exception
        '''

        self.cursor.execute(
            f"SELECT * FROM EmailVerification WHERE `verification_hash` = '{code}'"
        )

        on_failed = Settings.failed_email_verification_link()
        on_valid = Settings.vaild_email_verification_link()

        try:
            (_, email, password, date) = self.cursor.fetchone()
        except TypeError:
            raise EmailValidationError(-1204, 'No such verification code exists or it was already used.', on_failed)
        
        if (datetime.now() - datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")) > timedelta(hours=24):
            raise EmailValidationError(-1203, 'Email verification time has passed.', on_failed)

        if self.check_user_exists(email):
            raise EmailValidationError(-1200, 'Email is already in use.', on_failed)
        
        self.logger.debug(f'New user `{email}` has successfuly confirmed his email and created an account')
        self.create_user(email, password)

        return on_valid
Exemplo n.º 2
0
    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_thread = QtCore.QThread()
            self.aubio_thread.start()
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(
                self.mixer.onset_detected)
            self.aubio_connector.fft_data.connect(
                self.mixer.audio.update_fft_data)
            self.aubio_connector.pitch_data.connect(
                self.mixer.audio.update_pitch_data)
            self.aubio_connector.moveToThread(self.aubio_thread)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)
Exemplo n.º 3
0
 def test_set_get(self):
     "Sets and gets values."
     x = Settings()
     x.a = 1
     x.b = 2
     self.assertEqual(x.a, 1)
     self.assertEqual(x.b, 2)
Exemplo n.º 4
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)

        # Create the default layer.
        default_playlist = Playlist(self, self.args.playlist, 'last_playlist')
        default_layer = Layer(self, 'default')
        default_layer.set_playlist(default_playlist)
        self.mixer.add_layer(default_layer)

        if self.args.speech_layer:
            speech_playlist = Playlist(self, self.args.speech_playlist, 'last_speech_playlist')
            speech_layer = Layer(self, 'speech')
            speech_layer.set_playlist(speech_playlist)
            self.mixer.add_layer(speech_layer)

        if self.args.route_layer:
            route_playlist = Playlist(self, self.args.route_playlist, 'last_route_playlist')
            route_layer = Layer(self, 'routes')
            route_layer.set_playlist(route_playlist)
            self.mixer.add_layer(route_layer)

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)

        self.osc_server = None
        if not self.args.noosc:
            self.osc_server = OscServer(
                self.args.osc_port, self.args.mixxx_osc_port, self.mixer)
            self.osc_server.start()

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.mixer.save()
        self.settings.save()
Exemplo n.º 5
0
    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()
Exemplo n.º 6
0
    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()
Exemplo n.º 7
0
 def test_callable_overwrite_with_callable(self):
     "Allows overwriting a callable with a callable."
     x = Settings()
     x.a = lambda s: s.init + " original"
     x.a = lambda s: s.a + " and derived"
     x.init = "init"
     self.assertEqual(x.a, "init original and derived")
Exemplo n.º 8
0
 def test_list_validity(self):
    Settings._list_validity_check(['x','y'], ['x','y','z'])
    Settings._list_validity_check(['x','y'], ['x','y','z'])
    with self.assertRaises(InvalidSettingError):
       Settings._list_validity_check(['a','y'], ['x','y','z'])
    Settings._list_validity_check([['x','y'],['a']], [['b','a'],['x','y','z']])
    with self.assertRaises(InvalidSettingError):
       Settings._list_validity_check([['x','y'],['c']], [['b','a'],['x','y','z']])
Exemplo n.º 9
0
 def test_ctor_with_settings_file(self):
    s = Settings('foo_settings.json',
                 {'foo':[0, 1], 'bar':['barval', 'barval2']})
    with self.assertRaises(InvalidSettingError):
       Settings('foo_settings.json',
                {'foo':[0, 2], 'bar':['barval', 'barval2']})
    with self.assertRaises(InvalidSettingError):
       Settings('foo_settings.json',
                {'foo':[0, 1], 'bar':['barval2', 'barval3']})
Exemplo n.º 10
0
 def test_no_callable_overwrite_non_callable(self):
     "Disallows overwriting a callable with non-callable."
     x = Settings()
     x.a = lambda s: 1
     with self.assertRaisesRegex(
             AttributeError, "^trying to override attribute 'a' "
             "from a callable value to a non-callable "
             "one"):
         x.a = 1
Exemplo n.º 11
0
 def setUp(self):
    self.settings = Settings({'foo': 1, 'bar': 'barval'},
                             {'foo': [1], 'bar': ['barval']})
    self.empty_settings = Settings({}, {})
    self.same = Settings({'bar': 'barval', 'foo': 1},
                         {'foo': [1], 'bar': ['barval']})
    self.slightly_diff = Settings({'bar': 'barval', 'fooo': 1},
                                  {'fooo': [1], 'bar': ['barval']})
    dammit.keep_fkn_trying(self.create_foo_settings_json)
Exemplo n.º 12
0
 def test_cannot_set_parent_or_attrs(self):
     "Cannot set the attributes 'parent' or 'attrs'."
     x = Settings()
     with self.assertRaisesRegex(AttributeError,
                                 "'parent' is a reserved name"):
         x.parent = 1
     with self.assertRaisesRegex(AttributeError,
                                 "'attrs' is a reserved name"):
         x.attrs = 1
Exemplo n.º 13
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)

        # Create the default layer.
        default_playlist = Playlist(self, self.args.playlist, 'last_playlist')
        default_layer = Layer(self, 'default')
        default_layer.set_playlist(default_playlist)
        self.mixer.add_layer(default_layer)

        if self.args.speech_layer:
            speech_playlist = Playlist(self, self.args.speech_playlist,
                                       'last_speech_playlist')
            speech_layer = Layer(self, 'speech')
            speech_layer.set_playlist(speech_playlist)
            self.mixer.add_layer(speech_layer)

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(
                self.mixer.onset_detected)

        self.osc_server = None
        if not self.args.noosc:
            self.osc_server = OscServer(self.args.osc_port,
                                        self.args.mixxx_osc_port, self.mixer)
            self.osc_server.start()

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.mixer.save()
        self.settings.save()
Exemplo n.º 14
0
 def onLoadFile(self):
     initialdir = os.path.expanduser("~")
     filename = askopenfilename(initialdir=initialdir,
                                filetypes=[
                                    ('Config files', '*.pickle'),
                                    ('All files', '*.*'),
                                ])
     if filename:
         self.s = Settings(filename=filename)
         self.showInfo()
Exemplo n.º 15
0
 def test_list_with_dict(self):
    self.assertTrue(Settings._is_in_list(
       [{'a':'d'}],
       [{'a':['d']}]))
    self.assertTrue(Settings._is_in_list(
       [{'a':{'c': 'd', 'h': 'i'}, 'e': 'f'}],
       [{'e':['f'],'a':{'h':['i'],'c':['d']}}]))
    self.assertTrue(Settings._is_in_list(
       [['y'],[{'f':'g','j':'k'}]],
       [['y', 'z'],[{'j':['k'],'f':['g']}]]))
    self.assertTrue(Settings._is_in_list(
       [[[[['b', {'a': {'c':'d','h':'i'}, 'e':'f'}], ['y'], [{'f':'g', 'j':'k'}]]]]],
       [[[[['y', 'z'], [{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c'], [{'j': ['k'], 'f': ['g']}]]]]]))
    self.assertFalse(Settings._is_in_list(
       [[[[['f', {'a': {'c': 'd'}}], ['y'], [{'f': 'g'}]]]]],
       [[[[['y', 'z'], [{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c'], [{'j': ['k'], 'f': ['g']}]]]]]))
    self.assertFalse(Settings._is_in_list(
       [[[[[{'a': {'c': 'd'}}], ['yy'], [{'f': 'g'}]]]]],
       [[[[['y', 'z'], [{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c'], [{'j': ['k'], 'f': ['g']}]]]]]))
    self.assertFalse(Settings._is_in_list(
       [[[[[{'a': {'c': 'd'}}], ['y'], [{'f': 'h'}]]]]],
       [[[[['y', 'z'], [{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c'], [{'j': ['k'], 'f': ['g']}]]]]]))
    self.assertFalse(Settings._is_in_list(
       [[[{'a': {'c': 'e'}}]]],
       [[[{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c']]]))
    self.assertFalse(Settings._is_in_list(
       [[[[[{'a': {'c': 'e'}}], ['y'], [{'f': 'g'}]]]]],
       [[[[['y', 'z'], [{'e': ['f'], 'a': {'h': ['i'], 'c': ['d']}}, 'a', 'b', 'c'], [{'j': ['k'], 'f': ['g']}]]]]]))
Exemplo n.º 16
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.Signal()

    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_thread = QtCore.QThread()
            self.aubio_thread.start()
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(
                self.mixer.onset_detected)
            self.aubio_connector.fft_data.connect(
                self.mixer.audio.update_fft_data)
            self.aubio_connector.pitch_data.connect(
                self.mixer.audio.update_pitch_data)
            self.aubio_connector.moveToThread(self.aubio_thread)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.aubio_thread.quit()
        self.mixer.stop()
        self.playlist.save()
        self.settings.save()
Exemplo n.º 17
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.Signal()

    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_thread = QtCore.QThread()
            self.aubio_thread.start()
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)
            self.aubio_connector.fft_data.connect(self.mixer.audio.update_fft_data)
            self.aubio_connector.pitch_data.connect(self.mixer.audio.update_pitch_data)
            self.aubio_connector.moveToThread(self.aubio_thread)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.aubio_thread.quit()
        self.mixer.stop()
        self.playlist.save()
        self.settings["last-preset"] = self.playlist.active_preset.name()
        self.settings.save()
Exemplo n.º 18
0
 def __init__(self,app,onlyDBAccess=False):
     '''main window init'''
     QtGui.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.db = DB(self)
     self.settings=Settings(self)
     self.onlyDBAccess=onlyDBAccess
     if onlyDBAccess:
         return 
     #GUI setting
     guiSettings(self)
     connectSignals(self)
     changeStyle(self)
     
     self.taskOpened = False
     self.app = app
     loadContexts(self)
     self.currentContext = self.settings.getInitContext()
     selectCurrentContext(self)
     self.loadTasksList(init=True)  
     self.tray=Trayicon(self)
     self.timer=TaskReminder(self)
     self.shortcuts=ShortcutsHandler(self,self.settings['keyMainWindowToggle'])
     finalizeInit(self)
     self.translate()
     self.adjustHeight(init=True)
Exemplo n.º 19
0
    def __init__(self, args=None):
        super(MainFrame, self).__init__()

        # Загружаем элементы окна
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Восстанавливаем состояние окна
        self.settings = QtCore.QSettings(company_section, app_section)
        self.restoreGeometry(self.settings.value("geometry"))
        self.restoreState(self.settings.value("windowState"))

        # Настройки
        self.s = Settings()
        self.s.saveEnv()

        # Добавляем свой виджет
        verticalLayout = QtGui.QVBoxLayout(self.ui.widget)
        verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.ui.gragWidget = DragWidget(self.ui.widget, self.settings, self.s)
        self.ui.gragWidget.setObjectName("gragWidget")
        verticalLayout.addWidget(self.ui.gragWidget)

        # Читаем из директории с базой данных данные о задачах
        self.loadScheme()
Exemplo n.º 20
0
    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_thread = QtCore.QThread()
            self.aubio_thread.start()
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)
            self.aubio_connector.fft_data.connect(self.mixer.audio.update_fft_data)
            self.aubio_connector.pitch_data.connect(self.mixer.audio.update_pitch_data)
            self.aubio_connector.moveToThread(self.aubio_thread)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)
Exemplo n.º 21
0
 def onLoadFile(self):
     initialdir = os.path.expanduser("~")
     filename = askopenfilename(
         initialdir=initialdir, filetypes=[("Config files", "*.pickle"), ("All files", "*.*")]
     )
     if filename:
         self.s = Settings(filename=filename)
         self.showInfo()
Exemplo n.º 22
0
 def onLoadFile(self):
     initialdir = os.path.expanduser("~")
     filename = askopenfilename(initialdir=initialdir, filetypes=[
                    ('Config files', '*.pickle'),
                    ('All files', '*.*'),
                ])
     if filename:
         self.s = Settings(filename=filename)
         self.showInfo()
Exemplo n.º 23
0
 def test_parent(self):
     "Fetches values from parent."
     parent = Settings()
     child = Settings(parent)
     parent.a = 1
     parent.b = 2
     child.b = "overriden"
     self.assertEqual(child.a, 1)
     self.assertEqual(child.b, "overriden")
Exemplo n.º 24
0
    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent
        self.gui = None

        self.scene.warmup()

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)
Exemplo n.º 25
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.Signal()

    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)

        self.aubio_connector = None
        if self.args.audio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.playlist.save()
        self.settings.save()
        self.scene.save()
Exemplo n.º 26
0
    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        self.scene = Scene(SceneLoader(self))
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)

        self.aubio_connector = None
        if self.args.audio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)
Exemplo n.º 27
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.Signal()

    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        self.scene = Scene(SceneLoader(self))
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)

        self.aubio_connector = None
        if self.args.audio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)

    def run(self):
        self._running = True
        self.mixer.run()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.playlist.save()
        self.settings.save()
Exemplo n.º 28
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.pyqtSignal()

    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent
        self.gui = None

        self.scene.warmup()

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

    def run(self):
        self._running = True
        self.mixer.start()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.playlist.save()
        self.settings.save()
Exemplo n.º 29
0
class FireMixApp(QtCore.QThread):
    """
    Main logic of FireMix.  Operates the mixer tick loop.
    """
    playlist_changed = QtCore.pyqtSignal()

    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent
        self.gui = None

        self.scene.warmup()

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

    def run(self):
        self._running = True
        self.mixer.start()

    def stop(self):
        self._running = False
        self.mixer.stop()
        self.playlist.save()
        self.settings.save()
Exemplo n.º 30
0
   def test_default_injection(self):
      self.assertEqual(
         Settings._inject_defaults({}, None),
         {})

      self.assertEqual(
         Settings._inject_defaults({}, {'foo': 'foov'}),
         {'foo': 'foov'})
      self.assertEqual(
         Settings._inject_defaults({'foo': 'bar'}, {'foo': 'foov'}),
         {'foo': 'bar'})
      self.assertEqual(
         Settings._inject_defaults({'foo': None}, {'foo': 'foov'}),
         {'foo': 'foov'})
      self.assertEqual(
         Settings._inject_defaults(
            {'foo':'foov','bar':None},
            {'foo':'foo_default','bar':'bar_default','baz':'baz_default'}),
         {'foo':'foov','bar':'bar_default','baz':'baz_default'}
      )

      self.assertEqual(
         Settings._inject_defaults({'foo':{}}, {'foo':{'bar':'baz'}}),
         {'foo':{'bar':'baz'}}
      )
      self.assertEqual(
         Settings._inject_defaults({'foo':{'bar':'barv'}}, {'foo':{'bar':'barv','baz':'bazv'}}),
         {'foo':{'bar':'barv','baz':'bazv'}}
      )

      s = Settings({}, {'foo': [1, 0], 'bar': ['barval', 'barval2']}, {'foo': 0, 'bar': 'barval'})
      self.assertEqual(s['bar'], 'barval')
      self.assertEqual(s['foo'], 0)

      with self.assertRaises(InvalidSettingError):
         Settings({}, {'foo': [1, 0], 'bar': ['barval', 'barval2']}, {'bar': 'barval'})
      s = Settings({'bar': 'barval', 'foo': 1}, {'foo': [1, 0], 'bar': ['barval', 'barval2']}, {'bar': 2})
Exemplo n.º 31
0
    def send(to: str, subject: str, body: str):
        host, port, user, password = Settings.get_smtp_data()

        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = user
        msg['To'] = to

        msg.attach(MIMEText(body, 'html'))

        server = smtplib.SMTP_SSL(host, port)
        server.ehlo()
        server.login(user, password)
        server.sendmail(user, to, msg.as_string())
        server.close()
Exemplo n.º 32
0
    def __setup(self):
        flow = flow_from_clientsecrets(Settings.getSecret(),
                                       message=self.MISSING_CLIENT_SECRETS_MESSAGE,
                                       scope=self.YOUTUBE_READ_WRITE_SCOPE)
        storage = Storage("%s-oauth2.json" % sys.argv[0])
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            flags = get_cmd_line_parser().parse_args()
            credentials = run_flow(flow, storage, flags)

        self.yt = build(self.YOUTUBE_API_SERVICE_NAME,
                        self.YOUTUBE_API_VERSION,
                        http=credentials.authorize(httplib2.Http()))
        return self.yt
Exemplo n.º 33
0
 def test_as_dict(self):
     "The ``as_dict`` method returns a dictionary of values."
     x = Settings()
     x.a = lambda s: s.init + " original"
     x.a = lambda s: s.a + " and derived"
     x.init = "init"
     self.assertEqual(x.as_dict(), {
         "a": "init original and derived",
         "init": "init",
     })
Exemplo n.º 34
0
    def __init__(self, parent, args):
        QtCore.QThread.__init__(self, parent)
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)
        self.playlist = Playlist(self)
        self.qt_app = parent
        self.gui = None

        self.scene.warmup()

        self.mixer.set_playlist(self.playlist)

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)
Exemplo n.º 35
0
class Workload(QtGui.QMainWindow):

    def __init__(self,app,onlyDBAccess=False):
        '''main window init'''
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.db = DB(self)
        self.settings=Settings(self)
        self.onlyDBAccess=onlyDBAccess
        if onlyDBAccess:
            return 
        #GUI setting
        guiSettings(self)
        connectSignals(self)
        changeStyle(self)
        
        self.taskOpened = False
        self.app = app
        loadContexts(self)
        self.currentContext = self.settings.getInitContext()
        selectCurrentContext(self)
        self.loadTasksList(init=True)  
        self.tray=Trayicon(self)
        self.timer=TaskReminder(self)
        self.shortcuts=ShortcutsHandler(self,self.settings['keyMainWindowToggle'])
        finalizeInit(self)
        self.translate()
        self.adjustHeight(init=True)


    def resizeEvent(self,e):
       
        path=QtGui.QPainterPath()
        rect=e.size()
        path.addRoundedRect(-1,-1,rect.width()+1,rect.height()+1,7,7)
        region=QtGui.QRegion(path.toFillPolygon().toPolygon())
        self.setMask(region)
        


    def taskListFocusIn(self,e):
        if e.reason()==QtCore.Qt.FocusReason.TabFocusReason:
            try:
                item=self.ui.taskList.itemAt(0)
                self.ui.taskList.setCurrentItem(self.ui.taskList.itemAt(0))
            except:
                pass
    def toggle(self):
        if self.isVisible():
            self.hide()
        else:
            self.show()
            
    def dropTask(self,e):
        Task.dropTask(self, e)
        
    def resizeColumns(self):
        self.ui.taskList.setColumnWidth(0, 20)
        self.ui.taskList.setColumnWidth(1, 20)
        self.ui.taskList.hideColumn(0)

        
    def setMarker(self,tasks):
        icon=QtGui.QIcon(':res/status/clock.png')
        items=self.ui.taskList.findItems("",QtCore.Qt.MatchContains|QtCore.Qt.MatchRecursive)
        for i in items:
            removeicon=QtGui.QIcon()
            i.setIcon(2,removeicon)
        for i in tasks:
            for j in items:
                if j.data(0,32)==i:
                    j.setIcon(2,icon)
    
                    
    def drawRow(self,painter,myopt,index):
        myopt.decorationPosition=QtGui.QStyleOptionViewItem.Right
        myopt.decorationAlignment=QtCore.Qt.AlignCenter
        QtGui.QTreeWidget.drawRow(self.ui.taskList,painter,myopt,index)
        
# TASKS RELATED ACTIONS
    def addTask(self):
        t = self.ui.taskInput.text().strip()
        if t =="":
            return False
        self.ui.taskInput.clear()
        priority = 0
        try:
            if t[1] == ":":
                priority = int(t[0])
                if priority<6:
                    t = t[2:]
                else:
                    priority = 0

            elif t[-2] == ":":
                priority = int(t[-1])
                if priority<6:
                    t = t[:-2]
                else:
                    priority = 0
        except:
            pass
#TODO: create new function to handle input (regexp etc)
        if len(t)>50:
            taskname=t[:50]
            taskDescription=t
        else:
            taskname=t
            taskDescription=""
        if self.checkIfExist(taskname) is not True:
            duedate=self.defaultDueDate()  
            taskid = self.db.addTask(taskname,priority, taskDescription, duedate, self.currentContext)
            self.createTaskItem(taskname, taskid, priority)
            self.adjustHeight()
            self.ui.statusbar.showMessage(QtGui.QApplication.translate("ui","New task created."),3300)
        else:
            self.ui.taskInput.setText(taskname)
            self.taskAlreadyExistMsg()
            
    def defaultDueDate(self):
        if self.settings["defaultDueDateOn"]:
            dueValue=int(self.settings["defaultDueDateValue"])
            if self.settings["defaultDueDateUnit"]=="0":
                td=datetime.timedelta(hours=dueValue)
            else:
                td=datetime.timedelta(days=dueValue)
            return timestamp(datetime.datetime.now()+td)
        else:
            return None
            
    def createTaskItem(self, t, taskid=None, priority=0):
        item = QtGui.QTreeWidgetItem([str(priority),"", t])
        item.setData(0, 32, taskid)
        item.setSizeHint(1, QtCore.QSize(0, 22))
        self.ui.taskList.addTopLevelItem(item)
        self.setPriorityColor(item, priority)
        self.ui.taskList.sortItems(0,QtCore.Qt.AscendingOrder)
        
    def checkIfExist(self,t):
        if len(self.ui.taskList.findItems(t,QtCore.Qt.MatchFlags(QtCore.Qt.MatchExactly),2))>0:
            return True
            
            
    def taskAlreadyExistMsg(self,parent=None):
        text=QtGui.QApplication.translate("ui","Task with same name already exist, choose another")
        windowtitle=QtGui.QApplication.translate("ui","Task name already exists")
        msgWindow=QtGui.QMessageBox()
        if parent is not None: self=parent
        msgWindow.information(self, windowtitle, text, buttons=QtGui.QMessageBox.Ok )
    
    def loadTasksList(self, archived=False,init=False):
        self.ui.taskList.clear()
        for i in self.db.getTasks(self.currentContext):
            self.createTaskItem(i[1], i[0],i[2])

    def deleteSelectedTasks(self, force=False):
        selectedItems = self.ui.taskList.selectedItems()
        if len(selectedItems)>0:
            tasks = []
            for item in selectedItems:
                tasks.append(item)
            windowtitle=QtGui.QApplication.translate("ui","Delete task")
            text=QtGui.QApplication.translate("ui","Do you really want to delete selected  task(s) ?")
            if force:
                self.deleteTasks(tasks)
                windowtitle=QtGui.QApplication.translate("ui","Delete task")
                text=QtGui.QApplication.translate("ui","Do you really want to delete selected  task(s) ?")
            elif self.questionPopup(windowtitle,text):
                self.deleteTasks(tasks)
            self.adjustHeight(downSize=True)

    def deleteTasks(self, tasks):
        for item in tasks:
            self.db.deleteTask(item.data(0, 32))
            index = self.ui.taskList.indexOfTopLevelItem(item)
            self.ui.taskList.takeTopLevelItem(index)
            self.ui.statusbar.showMessage(QtGui.QApplication.translate("ui","Task removed."),3300)


    def setTaskPriority(self,priority):
        selectedItems = self.ui.taskList.selectedItems()
        for item in selectedItems:
            self.db.setTaskPriority(item.data(0, 32),priority)
            self.setPriorityColor(item, priority)
            item.setText(0,str(priority))
            self.ui.taskList.sortItems(0,QtCore.Qt.AscendingOrder)
            self.ui.statusbar.showMessage(QtGui.QApplication.translate("ui","Priority updated."),3300)
            
    def setPriorityColor(self,item,priority):
        icon=QtGui.QIcon(':res/status/'+str(priority)+'.png')
        item.setIcon(1,icon)

    def openTask(self,taskname=None):
        if not self.taskOpened:
            item = self.getSelectedItem()
            if item:
                Task(self,item.data(0, 32))
                

    def getSelectedItem(self):
        selectedItems = self.ui.taskList.selectedItems()
        if len(selectedItems) == 1:
            item = self.ui.taskList.selectedItems()[0]
            return item
        else:
            return False


    # SHORTCUTS AND KEYBOARD EVENTS RELATED ACTIONS
    def getKeysOnList(self, e):
        if e.key() == 16777223:  # delete
            if (QtCore.Qt.ShiftModifier & e.modifiers()):
                self.deleteSelectedTasks(True)
        elif e.key()>48 and e.key()<54:
            self.setTaskPriority(e.key()-48)
        elif e.key()==78:
            self.ui.taskInput.setFocus()
        else:
            QtGui.QTreeWidget.keyPressEvent(self.ui.taskList,e)


    def getKeysOnInput(self, e):
        if e.key()==16777221 or e.key()==16777220:  # enter/return
            if (QtCore.Qt.AltModifier & e.modifiers()):
                self.createTask()
            else:
                self.addTask()
        else:
            QtGui.QLineEdit.keyPressEvent(self.ui.taskInput,e)
            input=self.ui.taskInput.text()
            if len(input)>50:
                taskname=input[:50].strip()
                taskname=taskname.replace("\r\n","\n")
                taskname=taskname.replace("\n"," ")
                taskname=taskname.replace("\t"," ")
                taskname=taskname.replace("  ","")
                description=input
                Task(self,taskid=0,taskname=taskname,description=description)
                self.ui.taskInput.clear()

    #ADDITIONAL FUNTIONS
    def questionPopup(self, title, msg):
        window=QtGui.QMessageBox()
        window.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        resp = window.question(self, title, msg,
        buttons=QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
       
        if resp == QtGui.QMessageBox.Ok:
            return True
        else:
            return False
            

    #WINDOWS MOVEMENT
    def mouseMoveEvent(self, e):
        if e.buttons() & QtCore.Qt.LeftButton:
            try:
                self.posx
                self.posy
            except:
                self.posx=e.x()
                self.posy=e.y()
            y=e.globalY()-self.posy
            x=e.globalX()-self.posx
            self.move(x,y)
            #e.accept()


    def mouseReleaseEvent(self, e):
        try:
            del(self.posx)
            del(self.posy)
        except:
            pass
        
    def adjustHeight(self,downSize=False,init=False):
        tasks=self.db.getTasks(self.currentContext)
        if len(tasks)>0:
            item=self.ui.taskList.topLevelItem(0)
            qmodel=self.ui.taskList.indexFromItem(item)
            
            taskheight=self.ui.taskList.rowHeight(qmodel)
        else:
            taskheight=22
        if init:
            winheight=320
            listheight=252
        else:
            winheight=self.height()
            listheight=self.ui.taskList.height()
        desiredHeight=taskheight*len(tasks)+winheight-listheight+6
        if ( desiredHeight>self.height() or downSize ) and desiredHeight<QtGui.QApplication.desktop().height():
            self.resize(self.width(),desiredHeight)

    def closeEvent(self, e=None):
        self.hide()
        if e:
            e.ignore()

###### MENU FUNCTIONS

    def importTasklist(self):
        fname=QtGui.QFileDialog.getOpenFileName(self, QtGui.QApplication.translate("ui","Open"), "", QtGui.QApplication.translate("ui","Workload Import File (*.w)"))
        if fname[0]:
            filename=fname[0]
            from lib import importexport
            importexport.importTasks(self,filename,self.settings["dateFormat"])
            
    def exportTaskList(self):
        fname=QtGui.QFileDialog.getSaveFileName(self,QtGui.QApplication.translate("ui","Save"), "", QtGui.QApplication.translate("ui","Workload Export File (*.w)"))
        if fname[0]:
            includeArchive=self.questionPopup(QtGui.QApplication.translate("ui","Exporting tasks"), QtGui.QApplication.translate("ui","Do you want to include completed tasks?"))
            tasks=self.db.exportTasks(self.currentContext, includeArchive)
            from lib import importexport
            filename=fname[0]
            importexport.export(tasks, filename,self.settings["dateFormat"])
            
    def about(self):
        f=open("about.html")
        text=f.read()
        f.close()
        QtGui.QMessageBox.information(self, QtGui.QApplication.translate("ui","About"), text, buttons=QtGui.QMessageBox.Ok )

    def exit(self,exitcode=0):
        exit_=False
        if self.settings["askOnExit"]:
            if self.questionPopup(QtGui.QApplication.translate("ui","Exit"), QtGui.QApplication.translate("ui","Are you sure?")):
                exit_=True
        else: exit_=True
        if exit_==True:
            self.settings.setCurrentContextAsLast()
            self.shortcuts.terminate()
            self.app.exit(exitcode)

    def createTask(self):
        Task(self,taskid=0)

    def completeTasks(self):
        if self.ui.taskList.hasFocus():
            tasks=self.ui.taskList.selectedItems()
            for i in tasks:
                self.db.completeTask(i.data(0,32))
                index = self.ui.taskList.indexOfTopLevelItem(i)
                self.ui.taskList.takeTopLevelItem(index)
                self.ui.statusbar.showMessage(QtGui.QApplication.translate("ui","Task completed."),3300)

    def showHistory(self):
        ArchiveWindow(self)
                
    def hoyKeyError(self):
        QtGui.QMessageBox.critical(self,QtGui.QApplication.translate("ui","Error"),QtGui.QApplication.translate("ui","Unable to register global shortcut"))

    def changeEvent(self, e):
        if e.type()==QtCore.QEvent.LanguageChange:
            self.ui.retranslateUi(self)
            self.ui.statusbar.showMessage(QtGui.QApplication.translate("ui","Hello! Ready to work ;-)"),3600)
            loadContexts(self)
            selectCurrentContext(self)
            
        QtGui.QMainWindow.changeEvent(self,e)
        
    def translate(self,lang=None):
        if lang is None:
            lang= self.settings["lang"]
        translate=True
        if lang=="auto":
            locale = QtCore.QLocale.system().name()
        
        elif lang=="en":
            translate=False
            try:
                self.app.removeTranslator(self.qtTranslator)
            except:
                pass
        else:
            locale=lang
    
        if translate:
            self.qtTranslator = QtCore.QTranslator()
            self.qtTranslator.load("i18n"+os.sep+"workload_"+locale+".qm")
            self.app.installTranslator(self.qtTranslator)
    def showMsg(self,msg):
        msgWindow=QtGui.QMessageBox()
        msgWindow.information(self, "Workload - Information", msg, buttons=QtGui.QMessageBox.Ok )
Exemplo n.º 36
0
   def test_is_in_dict(self):
      self.assertTrue(Settings._is_in_dict({'a':'b','c':'d'}, {'c':['d'],'a':['b']}))
      self.assertFalse(Settings._is_in_dict({'a':'b'}, {'c':['d'],'a':['c']}))
      self.assertTrue(Settings._is_in_dict({'d':'f','a':['b','c']}, {'d':['e','f'],'a':['x','c','g','b','h']}))
      self.assertTrue(Settings._is_in_dict({'d':'e','a':['b','c']}, {'d':['e','f'],'a':['x','c','g','b','h']}))
      self.assertFalse(Settings._is_in_dict({'d':'f','a':['b','c']}, {'d':['e','f'],'a':['x','c','g','i','h']}))
      self.assertTrue(Settings._is_in_dict({'a':{'b':'c','f':'g'},'d':'e'}, {'d':['e'],'a':{'f':['g'],'b':['h','c']}}))
      self.assertFalse(Settings._is_in_dict({'a':{'b':'c','f':'g'},'d':'e'}, {'d':['e'],'a':{'f':['g'],'b':['h','i']}}))

      self.assertTrue(Settings._is_in_dict(
         {'a': ['b', ['c']], 'd': 'f'},
         {'d': ['e', 'f'], 'a': ['x', ['c', 'g'], 'b', 'h']}))
      self.assertFalse(Settings._is_in_dict(
         {'a': ['b', ['c']]},
         {'d': ['e', 'f'], 'a': ['x', 'c', ['g', 'i'], 'h', 'b']}))
      self.assertFalse(Settings._is_in_dict(
         {'a': ['b', ['c']]},
         {'d': ['e', 'f'], 'a': ['x', ['c', 'g', 'i'], 'h']}))
      self.assertTrue(Settings._is_in_dict(
         {'a':[{'b':'c'}]},
         {'a':[{'d','e'},{'b':'c'}]}
      ))
      self.assertTrue(Settings._is_in_dict(
         {'a': {'b':'c'}},
         {'a': [{'b':'c'}]}
      ))
Exemplo n.º 37
0
 def test_is_in_list(self):
    self.assertTrue(Settings._is_in_list(['x','y'], ['a','y','c','x']))
    self.assertTrue(Settings._is_in_list([['x']], [['z'], ['x','y']]))
    self.assertTrue(Settings._is_in_list([['x']], [['z'], ['x','a']]))
    self.assertFalse(Settings._is_in_list([['x']], [['z'], ['b','a']]))
    self.assertTrue(Settings._is_in_list([['x']], [['z'], ['b','a'], ['y','x']]))
    self.assertTrue(Settings._is_in_list([['y']], [['z'], ['b','a'], ['y','x']]))
    self.assertFalse(Settings._is_in_list([['c']], [['z'], ['b','a'], ['y','x']]))
    self.assertFalse(Settings._is_in_list([['c','x']], [['z'], ['b','a'], ['y','x']]))
    self.assertFalse(Settings._is_in_list([['c','x']], [['z'], ['b','c','a'], ['y','x']]))
    self.assertTrue(Settings._is_in_list([['c','x']], [['z'], ['b','c','a'], ['y','x','z','c','f']]))
    self.assertTrue(Settings._is_in_list([['c','x','z']], [['z'], ['b','c','a'], ['y','x','z','c','f']]))
    self.assertFalse(Settings._is_in_list([['c','x','b']], [['z'], ['b','c','a'], ['y','x','z','c','f']]))
    self.assertTrue(Settings._is_in_list([[[[['a'], ['y']]]]], [[[[['a', 'b', 'c', 'y', 'z']]]]]))
    self.assertFalse(Settings._is_in_list([[[['a'], ['y']]]], [[[[['a', 'b', 'c', 'y', 'z']]]]]))
    self.assertTrue(Settings._is_in_list([[[[['a','c'], ['y']]]]], [[[[['y', 'z'], ['a', 'b', 'c']]]]]))
    self.assertFalse(Settings._is_in_list([[[['a','c'], ['y']]]], [[[[['y','z'],['a', 'b', 'c']]]]]))
    self.assertFalse(Settings._is_in_list([[[[['a','y'], ['c']]]]], [[[[['y', 'z'], ['a', 'b', 'c']]]]]))
Exemplo n.º 38
0
 def test_is_in_prim(self):
    self.assertTrue(Settings._is_in_prim('z', ['x', 'y', 'z']))
    self.assertTrue(Settings._is_in_prim('x', ['x', 'y', 'z']))
    self.assertTrue(Settings._is_in_prim('y', ['x', 'y', 'z']))
    self.assertFalse(Settings._is_in_prim('a', ['x', 'y', 'z']))
Exemplo n.º 39
0
   def test_ctor(self):
      Settings({'foo': 0}, {'foo': [0, 1]})
      Settings({'foo': 1}, {'foo': [0, 1]})
      Settings({'foo': 0, 'bar': 'barval'},
                   {'foo': [0, 1], 'bar': ['barval', 'barval2']})
      Settings({'foo': 0, 'bar': 'barval2'},
                   {'foo': [0, 1], 'bar': ['barval', 'barval2']})

      with self.assertRaises(InvalidSettingError):
         Settings({'foo': 1}, {'foo': [0, 2]})
      with self.assertRaises(InvalidSettingError):
         Settings({'foo': 0, 'bar': 'barval'},
                      {'foo': [0, 1], 'bar': ['barval1', 'barval2']})

      with self.assertRaises(InvalidSettingError):
         Settings({'foo': 0, 'bar': 'barr'}, {'foo': [1, 0], 'bar': []})

      Settings({'foo':['a','b']}, {'foo':['a','b','c','d']})
      Settings({'foo':[['a','b']]}, {'foo':[['c','d'],['b','a']]})
      Settings({'foo':[['a']]}, {'foo':[['c','d'],['a','b']]})
      Settings({'foo':[['b']]}, {'foo':[['c','d'],['a','b']]})
      Settings({'foo':[['b'], ['a']]}, {'foo':[['c','d'],['a','b']]})
      Settings({'foo':[['b'], ['d']]}, {'foo':[['c','d'],['a','b']]})
      Settings({'foo':[['b'], []]}, {'foo':[['c','d'],['a','b']]})

      Settings({'foo':{'bar':'a'}}, {'foo':{'bar':['b','a']}})
      Settings({'foo':{'bar':'a'}}, {'foo':[{'baz':['c','d']},{'bar':['b','a']}]})

      with self.assertRaises(InvalidSettingError):
         Settings({'foo':{'bar':'a'}}, {'foo':[{'baz':['c','d']},{'bar':['b','a'],'mu':['e','f']}]})
      Settings({'foo':{'bar':'a','mu':'e'}}, {'foo':[{'baz':['c','d']},{'bar':['b','a'],'mu':['e','f']}]})
      Settings({'foo':{'baz':'d'}}, {'foo':[{'baz':['c','d']},{'bar':['b','a'],'mu':['e','f']}]})

      with self.assertRaises(InvalidSettingError):
         Settings({'foo':[['b','d']]}, {'foo':[['c','d'],['b','a']]})

      Settings(
         {'foo': [{'bar': 3}, {'baz': 4}]},
         {'foo': [
            {'bar': [4, 3]},
            {'baz': [4, 5]},
            {'mu': [6, 7]}
         ]})

      Settings(
         {'foo': {'bar': 'baz'}},
         {'foo': [{'bar': ['mu', 'baz']}]})
Exemplo n.º 40
0
 def test_is_in_prim_order(self):
    Settings._validity_check({'foo':'foov'},{'foo':['foov','*:bool',r'\d+:re']})
    Settings._validity_check({'foo':True},{'foo':['foov','*:bool',r'\d+:re']})
    Settings._validity_check({'foo':3},{'foo':['foov','*:bool',r'\d+:re']})
    Settings._validity_check({'foo':'True'},{'foo':[r'True:re','*:bool']})
    Settings._validity_check({'foo':False},{'foo':[r'True:re','*:bool']})
    with self.assertRaises(InvalidSettingError):
       Settings._validity_check({'foo':False},{'foo':[r'True:re']})
Exemplo n.º 41
0
   def test_is_regex_match(self):
      self.assertTrue(Settings._is_regex_match('foo', r'\w+:re'))
      self.assertTrue(Settings._is_regex_match('foo', r'F\w:re:I'))
      self.assertFalse(Settings._is_regex_match('foo', r'F\w$:re:I'))
      self.assertTrue(Settings._is_regex_match('foo', r'F\w+:re:I '))
      with self.assertRaises(InvalidRegexError):
         self.assertTrue(Settings._is_regex_match('foo', r'F\w+:re:I Z'))
      with self.assertRaises(InvalidRegexError):
         self.assertTrue(Settings._is_regex_match('foo', r'F\w+:re:i'))
      self.assertFalse(Settings._is_regex_match("f\no", r'...:re'))
      self.assertTrue(Settings._is_regex_match("f\no", r'...:re:S'))
      self.assertFalse(Settings._is_regex_match("f\no", r'F..:re:S'))
      self.assertFalse(Settings._is_regex_match("f\no", r'F..:re:I'))
      self.assertTrue(Settings._is_regex_match("f\no", r'F..:re:IS'))
      self.assertTrue(Settings._is_regex_match("f\no", r'F..:re:SI'))

      with self.assertRaises(InvalidSettingError):
         Settings._validity_check({'foo': 'bar'}, {'foo': r'B\w+:re'})
      Settings._validity_check({'foo': 'bar'}, {'foo': r'B\w:re:I'})
      Settings._validity_check({'foo': 'b\nr'}, {'foo': r'B.\w:re:IS'})
      with self.assertRaises(InvalidSettingError):
         Settings._validity_check({'foo': 'b\nr'}, {'foo': r'B.\w:re:I'})
      Settings._validity_check({'foo':{'baz':'b\nr'}}, {'foo':{'baz':r'B.\w:re:IS'}})

      Settings._validity_check({'foo':345}, {'foo':r'\d+:re'})
      Settings._validity_check({'foo':True}, {'foo':r'True:re'})
      Settings._validity_check({'foo':False}, {'foo':r'False:re'})
      Settings._validity_check({'foo':3.4}, {'foo':r'\d+(\.\d+)?:re'})
      Settings._validity_check({'foo':34}, {'foo':r'\d+(\.\d+)?:re'})
Exemplo n.º 42
0
import sys, threading, webbrowser

try:
    from .lib.info import __pkgname__, __description__, __version__
    from .lib.backwardcompat import *
    from .lib.dump import plain
    from .lib.settings import Settings
except:
    from lib.info import __pkgname__, __description__, __version__
    from lib.backwardcompat import *
    from lib.dump import plain
    from lib.settings import Settings


s = Settings()
s.saveEnv()


class ScrolledText(tk.Frame):
    def __init__(self, parent=None):
        tk.Frame.__init__(self, parent)

        self.text = tk.Text(self, relief=tk.SUNKEN)
        self.text.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.YES)

        sbar = tk.Scrollbar(self)
        sbar.pack(fill=tk.Y, side=tk.RIGHT)
        sbar.config(command=self.text.yview)

        self.text.config(yscrollcommand=sbar.set)
Exemplo n.º 43
0
   def test_wildcard_validity(self):
      self.assertTrue(Settings._is_wildcard_match('foo', '*'))
      self.assertTrue(Settings._is_wildcard_match(3, '*'))
      self.assertTrue(Settings._is_wildcard_match(False, '*'))
      self.assertTrue(Settings._is_wildcard_match(3.5, '*'))

      self.assertTrue(Settings._is_wildcard_match('foo', '*:str'))
      self.assertFalse(Settings._is_wildcard_match('foo', '*:bool'))
      self.assertTrue(Settings._is_wildcard_match(True, '*:bool'))
      self.assertFalse(Settings._is_wildcard_match(3, '*:bool'))
      self.assertTrue(Settings._is_wildcard_match(3, '*:int'))
      self.assertFalse(Settings._is_wildcard_match(3.5, '*:int'))
      self.assertTrue(Settings._is_wildcard_match(3.5, '*:float'))
      self.assertFalse(Settings._is_wildcard_match('foo', '*:float'))

      with self.assertRaises(InvalidWildcardError):
         Settings._is_wildcard_match(3.5, '*:foo')

      self.assertTrue(Settings._is_in_prim('foo', '*'))
      self.assertTrue(Settings._is_in_prim('foo', '*:str'))
      self.assertFalse(Settings._is_in_prim('foo', '*:bool'))

      Settings._validity_check({'foo':'bar'}, {'foo':'*'})
      Settings._validity_check({'foo':'bar'}, {'foo':'*:str'})
      with self.assertRaises(InvalidSettingError):
         Settings._validity_check({'foo':'bar'}, {'foo':'*:bool'})
      Settings._validity_check({'foo':'bar'}, {'foo':['*:int','*:str']})
Exemplo n.º 44
0
 def openSettings(self):
     if self.settingsForm is None:
         self.settingsForm = Settings(self)
     self.settingsForm.show()
Exemplo n.º 45
0
 def onLoadDefault(self):
     self.s = Settings()
     self.showInfo()
Exemplo n.º 46
0
def main():
    conf = Settings(getcwd()+"/pool.json")
    conf.run_async_checks()
    BindServer(ip='10.20.30.53', resolver=conf.resolve)
Exemplo n.º 47
0
class MainFrame(QtGui.QMainWindow):
    def __init__(self, args=None):
        super(MainFrame, self).__init__()

        # Загружаем элементы окна
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Восстанавливаем состояние окна
        self.settings = QtCore.QSettings(company_section, app_section)
        self.restoreGeometry(self.settings.value("geometry"))
        self.restoreState(self.settings.value("windowState"))

        # Настройки
        self.s = Settings()
        self.s.saveEnv()

        # Добавляем свой виджет
        verticalLayout = QtGui.QVBoxLayout(self.ui.widget)
        verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.ui.gragWidget = DragWidget(self.ui.widget, self.settings, self.s)
        self.ui.gragWidget.setObjectName("gragWidget")
        verticalLayout.addWidget(self.ui.gragWidget)

        # Читаем из директории с базой данных данные о задачах
        self.loadScheme()


# События


    def OnAbout(self):
        msg  = u"{0}\n".format(__description__)
        msg += u"Version: {0}\n\n".format(__version__)

        msg += u"Author: Stan <*****@*****.**>\n"
        msg += u"License: MIT\n\n"

        msg += u"Python: {0}\n".format(sys.version)
        msg += u"PySide: {0}\n".format(__version__)
        msg += u"Qt: {0}\n".format(QtCore.__version__)
        QtGui.QMessageBox.about(None, "About", msg)


    def OnAbout_Qt(self):
        QtGui.QApplication.aboutQt()


    def closeEvent(self, event):
        # Сохраняем состояние окна
        self.settings.setValue("geometry", self.saveGeometry())
        self.settings.setValue("windowState", self.saveState())

        # Сохраняем данные о задачах
        self.saveScheme()
        event.accept()


# Основной функционал


    def loadScheme(self):
        tasks = self.s.get('tasks', [])
        for task in tasks:
            draw_task(self.ui.gragWidget, task)


    def saveScheme(self):
        tasks = []
        for task in self.ui.gragWidget.tasks_list():
            task_dict = {}
            for key, value in task.items():
                if isinstance(value, (simple_types, collections_types, dict)):
                    task_dict[key] = value
            tasks.append(task_dict)
        self.s.set('tasks', tasks)


# Сервисные функции


    def set_status(self, message=''):
        if isinstance(message, (list, tuple)):
            message = u"{0} и др. значения".format(message[0])
        self.sb_message = message
        self.ui.statusbar.showMessage(self.sb_message)
Exemplo n.º 48
0
class AppUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("tkSettings")

        ### Menu ###

        self.menubar = tk.Menu(self)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(command=self.onLoadDefault, label="Load default")
        menu.add_command(command=self.onLoadFile, label="Load file")
        menu.add_separator()
        menu.add_command(command=self.quit, label="Exit")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=menu)
        menu.add_command(command=self.onCleanData, label="Clean data")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Batch import", menu=menu)
        menu.add_command(command=self.onBatch1, label="File to file")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Help", menu=menu)
        menu.add_command(command=self.onAbout, label="About")

        self.config(menu=self.menubar)

        ### Widgets ###

        # Frame with Buttons
        self.frame1 = tk.Frame(self)

        button = tk.Button(self.frame1, text="Settings")
        button.pack()
        button.bind("<Button-1>", self.onShowSettings)

        button = tk.Button(self.frame1, text="Save test data")
        button.pack()
        button.bind("<Button-1>", self.onSaveTestData)

        button = tk.Button(self.frame1, text="Import from module")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModule)

        button = tk.Button(self.frame1, text="Import from module to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromModuleToBranch)

        button = tk.Button(self.frame1, text="Import from dir")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDir)

        button = tk.Button(self.frame1, text="Import from dir to branch")
        button.pack()
        button.bind("<Button-1>", self.onImportFromDirToBranch)

        # Text Widget
        dFont1 = Font(family="Courier", size=9)
        self.text1 = tk.Text(self, font=dFont1)
        self.text1_y = tk.Scrollbar(self, orient=tk.VERTICAL,
                                    command=self.text1.yview)
        self.text1['yscrollcommand'] = self.text1_y.set

        # Status Widget
        self.status = tk.StringVar()
        label1 = tk.Label(self, textvariable=self.status, anchor=tk.W)
        self.setStatus()

        ### Grid widgets ###

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1, minsize=120)
        self.grid_columnconfigure(1, weight=5, minsize=400)
        self.grid_columnconfigure(2)

        self.frame1.grid(row=0, column=0, sticky='nwes')
        self.text1.grid(row=0, column=1, sticky='nwes')
        self.text1_y.grid(row=0, column=2, sticky='nwes')

        self.grid_rowconfigure(1)
        label1.grid(row=1, column=0, columnspan=4, sticky='nwes')

        ### Initial ###

        self.onLoadDefault()

    def appendText(self, text=""):
        self.text1.insert(tk.INSERT, "{0}\n".format(plain(text)))

    def setText(self, text=""):
        self.text1.delete(1.0, tk.END)
        self.appendText(text)

    def setStatus(self, text=""):
        status = sys.executable
        if text:
            status += " :: " + text
        self.status.set(status)

    def showInfo(self):
        self.setText("System:")
        self.appendText(self.s.get_systems())
        self.appendText("Settings:")
        self.appendText(self.s.get_dict())
        self.setStatus(self.s.get_filename())

    ### From menu ###

    def onAbout(self):
        text = """{0}\n{1}\nVersion {2}\n
Python: {3}
Package: {4}
""".format(__pkgname__, __description__, __version__,
           sys.version, __package__)
        showinfo("About", text)

    def onLoadDefault(self):
        self.s = Settings()
        self.showInfo()

    def onLoadFile(self):
        initialdir = os.path.expanduser("~")
        filename = askopenfilename(initialdir=initialdir, filetypes=[
                       ('Config files', '*.pickle'),
                       ('All files', '*.*'),
                   ])
        if filename:
            self.s = Settings(filename=filename)
            self.showInfo()

    def onCleanData(self):
        response = askquestion("Clean data", "Are you sure you want to "
                   "permanently delete all information from the config?")
        if response == 'yes':
            self.s.clean()
            self.showInfo()

    def onBatch1(self):
        dfilename = askdirectory()
        if dfilename:

            pickles = []
            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    basename = os.path.basename(filename)
                    root, ext = os.path.splitext(basename)
                    logging.debug(root)
                    BRANCH = Settings(root)
                    pickles.append(BRANCH.get_filename())

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            message = "Processed pickles:\n" + plain(pickles) + "\n\n" +\
                      "Note: Empty pickles was not created!"
            showinfo("Info", message)
            self.setText()
            self.setStatus()

    ### From buttons ###

    def onShowSettings(self, event):
        propertyDialog(self.s.get_dict())

    def onSaveTestData(self, event):
        self.s.saveEnv()
        self.s.set_path('test_instance', '$')
        self.s.set_path('test_home',     '~')
        self.s.set_path('test_location', '~~',  True)
        self.s.set_path('test_app',      '~~~', True)
        self.showInfo()

    def onImportFromModuleToBranch(self, event):
        self.onImportFromModule(event, tobranch=True)

    def onImportFromModule(self, event, tobranch=False):
        filename = askopenfilename(filetypes=[
                       ('Python files', '*.py'),
                       ('All files', '*.*'),
                   ])
        if filename:
            module = import_file(filename)
            if module:
                if tobranch:
                    branch = module.__name__
                    BRANCH = self.s.get_group(branch)
                else:
                    BRANCH = self.s

                for i in dir(module):
                    if i[0] != '_':
                        value = getattr(module, i)
                        if isinstance(value, all_types):
                            BRANCH.set(i, value)

                self.showInfo()

    def onImportFromDirToBranch(self, event):
        self.onImportFromDir(event, tobranch=True)

    def onImportFromDir(self, event, tobranch=False):
        dfilename = askdirectory()
        if dfilename:
            basename = os.path.basename(dfilename)
            logging.debug(basename)
            ROOT = self.s   # Settings(basename)

            for filename in glob.glob(os.path.join(dfilename, '*.py')):
                module = import_file(filename)
                if module:
                    if tobranch:
                        branch = module.__name__
                        BRANCH = self.s.get_group(branch)
                    else:
                        BRANCH = self.s

                    for i in dir(module):
                        if i[0] != '_':
                            value = getattr(module, i)
                            if isinstance(value, all_types):
                                BRANCH.set(i, value)

            self.showInfo()
Exemplo n.º 49
0
class WebinyNotifier(QtGui.QApplication, QObject):
    processMonitorLog = ''

    def __init__(self, args):
        QtGui.QApplication.__init__(self, args)
        QObject.__init__(self, args)
        self.setQuitOnLastWindowClosed(False)
        self.tray = Tray(parent=self)
        self.settingsForm = None
        self.logForm = None
        self.settings = SettingsObj()
        # Connect slot so Listener can forward request data to main thread
        self.listener = Listener()
        self.connect_slots(self.listener)
        self.listener.start()
        self.exec_()

    def restartListener(self):
        print "Restarting listener..."
        self.listener.stop()
        self.listener = Listener()
        self.connect_slots(self.listener)
        self.listener.start()

    def connect_slots(self, sender):
        self.connect(sender, QtCore.SIGNAL('newNotification'), self.newNotification)

    def newNotification(self, params):
        # Store new request
        request = Request()
        request.createFromNodeJs(params)

        # Notification balloon
        if bool(self.settings.show_balloon) and bool(self.settings.log_levels[request.getLevel()]['balloon']):
            message = "[" + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + "] New notification received!"
            Debugger.log('Showing tray message: ' + message)
            self.tray.showMessage('Webiny Notifier', message, QtGui.QSystemTrayIcon.Information, 10000000)
        self.refreshRequestsModel()

    def openSettings(self):
        if self.settingsForm is None:
            self.settingsForm = Settings(self)
        self.settingsForm.show()

    def openLog(self):
        """
        if self.logForm is None:
            self.logForm = Log()
        self.logForm.show()
        """

    def refreshRequestsModel(self):
        if hasattr(self, "mainWindow"):
            self.mainWindow.refreshRequestModel()

    def exitApp(self):
        del self.tray
        self.listener.stop()
        self.quit()

    def balloonClicked(self):
        Debugger.log('Balloon clicked')
        if not hasattr(self, "mainWindow"):
            self.mainWindow = MainWindow(self)
        if not self.mainWindow.isVisible():
            self.mainWindow.show()

        if self.mainWindow.isMinimized():
            self.mainWindow.showNormal()

        self.mainWindow.activateWindow()
        self.mainWindow.selectFirstRow()

    def iconClicked(self, reason):
        if reason == 2:
            Debugger.log('Tray icon clicked')
            if not hasattr(self, "mainWindow"):
                self.mainWindow = MainWindow(self)
                self.mainWindow.activateWindow()
            if self.mainWindow.isVisible():
                self.mainWindow.hide()
            else:
                self.mainWindow.show()
                self.mainWindow.activateWindow()
Exemplo n.º 50
0
    def __init__(self, args, parent=None):
        self._running = False
        self.args = args
        self.settings = Settings()
        self.net = Networking(self)
        BufferUtils.set_app(self)
        self.scene = Scene(self)
        self.plugins = PluginLoader()
        self.mixer = Mixer(self)

        # Create the default layer.
        default_playlist = Playlist(self, self.args.playlist, 'last_playlist',
                                    subdir = 'Music')
        default_audiolist = Audiolist(self, self.args.audiobehaviors, 'last_audiolist',
                                      subdir = 'Music')
        default_layer = MusicLayer(self)
        default_layer.set_playlist(default_playlist)
        default_layer.set_audiolist(default_audiolist)
        default_layer.setForeground()
        self.mixer.add_layer(default_layer)

        if self.args.speech_layer or self.args.all:
            speech_playlist = Playlist(self, self.args.speech_playlist,
                                       'last_speech_playlist', subdir = 'Speech')
            speech_audiolist = Audiolist(self, self.args.speech_audiobehaviors,
                                         'last_speech_audiolist', subdir = 'Speech')
            speech_layer = SpeechLayer(self)
            speech_layer.set_playlist(speech_playlist)
            speech_layer.set_audiolist(speech_audiolist)
            speech_layer.setBackground()
            self.mixer.add_layer(speech_layer)

        if self.args.leap_layer or self.args.all:
            leap_playlist = Playlist(self, self.args.leap_playlist,
                                     'last_leap_playlist', subdir = 'Leap')
            leap_audiolist = Audiolist(self, self.args.leap_audiobehaviors,
                                       'last_leap_audiolist', subdir = 'Leap')
            leap_layer = LeapLayer(self)
            leap_layer.set_playlist(leap_playlist)
            leap_layer.set_audiolist(leap_audiolist)
            leap_layer.setBackground()
            self.mixer.add_layer(leap_layer)
            

        self.scene.warmup()

        self.aubio_connector = None
        if not self.args.noaudio:
            self.aubio_connector = AubioConnector()
            self.aubio_connector.onset_detected.connect(self.mixer.onset_detected)

        self.osc_server = None
        if not self.args.noosc:
            self.osc_server = OscServer(
                self.args.osc_port, self.args.mixxx_osc_port, self.mixer)
            self.osc_server.start()

        if self.args.preset:
            log.info("Setting constant preset %s" % args.preset)
            self.mixer.set_constant_preset(args.preset)

        QtCore.QThread.__init__(self, parent)
Exemplo n.º 51
0
cycle_counter = 0

# Define stepper sequence
sequence = [
    [1,0,0,0],
    [1,1,0,0],
    [0,1,0,0],
    [0,1,1,0],
    [0,0,1,0],
    [0,0,1,1],
    [0,0,0,1],
    [1,0,0,1],
]

# Find best camera settings
settings = Settings()
auto_settings = settings.get_auto()

# Find closest allowed ISO
speed = auto_settings['iso']
speeds = [100, 200, 320, 400, 500, 640, 800]
iso = 800
minimum_diff = float('inf')
for value in speeds:
    diff = abs(speed - value)
    if diff <= minimum_diff:
        minimum_diff = diff
        iso = value
auto_settings['iso'] = iso

# Setup camera for capture