def initialize():
    settings.getSettings()

    if not settings.settings['Database']:
        logger.log('Please provide a location for the Database')
        return

    # Do this early so we can use it anywhere
    LikedSavedDatabase.initializeFromSettings(settings.settings)
def Bot():
    GAME = Trade()
    while True:
        try:
            line = input()
        except (KeyboardInterrupt, EOFError):
            break
        av = line.split()
        if (GAME.settings.full is False):
            getSettings(GAME, av)
        else:
            getCommands(GAME, av)
Пример #3
0
    def openFileDialog(self):
        """
        Open file dialog and handle the directory selected.

        """
        dirName = QFileDialog.getExistingDirectory(
            self, 'Locate Directory',
            getSettings()['defaultFolder'])
        if dirName:
            # Set the directory above the chosen one as the new default
            qDir = QDir(dirName)
            qDir.cdUp()
            getSettings()['defaultFolder'] = qDir.absolutePath()

            self.loadDirContents(dirName)
Пример #4
0
def getConfig():
    config = settings.getSettings()
    config['General settings']['start_time'] = data.getDateStr()
    logFile = os.path.join(
        Path(config['General settings']['data_path']),
        config['General settings']['data_filename'].format(
            **config['General settings']) + '.log')
    logging.basicConfig(filename=logFile,
                        level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    # group = 'Stimuli settings'
    # for k in ['eccentricities', 'orientations', 'stimulus_position_angles']:
    # 	if isinstance(config[group][k], str):
    # 		config[group][k] = [float(v) for v in config[group][k].split(' ')]
    # 	else:
    # 		config[group][k] = [float(config[group][k])]

    config['sitmulusTone'] = getSound('600Hz_square_25.wav', 600, .185)
    config['positiveFeedback'] = getSound('1000Hz_sine_50.wav', 1000, .077)
    config['negativeFeedback'] = getSound('300Hz_sine_25.wav', 300, .2)
    config['gazeTone'] = getSound('hurt.wav', 200, .2)

    return config
Пример #5
0
 def run(self):
     logging.basicConfig(level=logging.WARN)
     logger = logging.getLogger("ScreepsMarketd")
     logger.setLevel(logging.WARN)
     settings = getSettings()
     screepsapi = ScreepsMarketStats(u=settings['screeps_username'], p=settings['screeps_password'], ptr=settings['screeps_ptr'])
     screepsapi.run_forever()
Пример #6
0
 def run(self):
     logging.basicConfig(level=logging.WARN)
     logger = logging.getLogger("ScreepsStats")
     logger.setLevel(logging.WARN)
     settings = getSettings()
     screepsapi = ScreepsMemoryStats()
     screepsapi.run_forever()
Пример #7
0
 def getScreepsAPI(self):
     if not self.__api:
         settings = getSettings()
         self.__api = screepsapi.API(u=settings['screeps_username'],
                                     p=settings['screeps_password'],
                                     ptr=settings['screeps_ptr'])
     return self.__api
Пример #8
0
    def create_svn_silent_client():
        qpath = getSettings().fileName()
        import os
        settingpath = os.path.dirname(qpath)
        svnsettingpath = os.path.join(settingpath,'svn')
        if not os.path.exists(svnsettingpath):
            os.mkdir(svnsettingpath)
        client = pysvn.Client(svnsettingpath)
        client.set_store_passwords(False)
        client.set_auth_cache(True)
        client.set_interactive(False)
        
        def get_login( realm, username, may_save ):
            return False, '', '', False

        
        def ssl_server_trust_prompt(trust_dict ):
            return True, True, True
        
        # client.callback_cancel
        # client.callback_get_log_message
        client.callback_get_login = get_login
        # client.callback_notify = callback_notify
        # client.callback_ssl_client_cert_prompt 
        client# .callback_ssl_client_cert_password_prompt = ssl_client_cert_password_prompt
        client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt        
        return client
Пример #9
0
def settingsMenu():
    getSettingsValues = settings.getSettings()

    layout = [[
        sg.Text('Camera', font=layoutFont),
        sg.In(getSettingsValues[0], font=layoutFont)
    ],
              [
                  sg.Text('User ID', font=layoutFont),
                  sg.In(getSettingsValues[1], font=layoutFont)
              ],
              [
                  sg.Text('Authorization Key', font=layoutFont),
                  sg.In(getSettingsValues[2], font=layoutFont)
              ], [sg.Button('Save'), sg.Button('Exit')]]

    window = sg.Window("Settings", layout, modal=True)

    while True:
        event, values = window.read()
        if event == 'Exit' or event == sg.WINDOW_CLOSED:
            break
        if event == 'Save':
            settings.changeSettings(values[0], values[1], values[2])
            window.close()

    window.close()
Пример #10
0
    def create_svn_silent_client():
        qpath = getSettings().fileName()
        import os
        settingpath = os.path.dirname(qpath)
        svnsettingpath = os.path.join(settingpath, 'svn')
        if not os.path.exists(svnsettingpath):
            os.mkdir(svnsettingpath)
        client = pysvn.Client(svnsettingpath)
        client.set_store_passwords(False)
        client.set_auth_cache(True)
        client.set_interactive(False)

        def get_login(realm, username, may_save):
            return False, '', '', False

        def ssl_server_trust_prompt(trust_dict):
            return True, True, True

        # client.callback_cancel
        # client.callback_get_log_message
        client.callback_get_login = get_login
        # client.callback_notify = callback_notify
        # client.callback_ssl_client_cert_prompt
        client  # .callback_ssl_client_cert_password_prompt = ssl_client_cert_password_prompt
        client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
        return client
Пример #11
0
 def getScreepsAPI(self):
     if not self.__api:
         settings = getSettings()
         self.__api = screepsapi.API(token=settings['screeps_token'],
                                     ptr=settings['screeps_ptr'],
                                     host=settings["host"],
                                     secure=settings["secure"])
     return self.__api
Пример #12
0
 def getApiClient(self):
     if not self.apiclient:
         settings = getSettings()
         self.apiclient = screepsapi.API(u=settings['screeps_username'],
                                         p=settings['screeps_password'],
                                         ptr=settings['screeps_ptr'],
                                         host=settings['screeps_host'])
     return self.apiclient
Пример #13
0
 def run(self):
     logging.basicConfig(level=logging.WARN)
     logger = logging.getLogger("ScreepsStats")
     logger.setLevel(logging.WARN)
     settings = getSettings()
     screepsconsole = ScreepsConsole(token=settings['screeps_token'],
                                     ptr=settings['screeps_ptr'])
     screepsconsole.start()
Пример #14
0
    def accept(self):
        """
        Save the selected values.

        """
        suggestedArtist = unicode(self.metadata['artist'])
        submittedArtist = unicode(self.artistLineEdit.text()).strip()

        defaults = {
            'preferred_name': submittedArtist,
            'genre': unicode(self.genreLineEdit.text()).strip()
        }

        # If the entered name has little similarity to the original,
        # assume the detected artist was completely wrong and is not
        # synonymous with the submitted artist name.
        diff = difflib.SequenceMatcher(None, suggestedArtist.lower(),
                                       submittedArtist.lower())

        getSettings().setArtistDefaults(
            suggestedArtist if suggestedArtist and diff.ratio() > 0.5 else
            submittedArtist, defaults)

        if submittedArtist:
            self.metadata['artist'] = submittedArtist
        else:
            self.metadata['artist'] = ''

        self.metadata['defaults'] = defaults

        qDate = self.dateEdit.date()
        self.metadata['date'] = datetime.date(qDate.year(), qDate.month(),
                                              qDate.day())
        self.metadata['location'] = unicode(self.locationLineEdit.text())
        self.metadata['venue'] = unicode(self.venueLineEdit.text())
        self.metadata['comments'] = unicode(
            self.commentsTextEdit.toPlainText())
        self.metadata['tracklist'] = [
            unicode(self.tracklistTableWidget.item(1, i).text())
            for i in range(-1,
                           self.tracklistTableWidget.rowCount() - 1)
        ]

        self.metadata['title'] = unicode(self.titleLineEdit.text())
        self.close()
        ChooseCoverDialog(self.metadata, parent=self.parentWidget()).exec_()
Пример #15
0
 def create_svn_client():
     qpath = str(getSettings().fileName())
     import os
     settingpath = os.path.dirname(qpath)
     svnsettingpath = os.path.join(settingpath,'svn')
     if not os.path.exists(svnsettingpath):
         os.makedirs(svnsettingpath)
     client = pysvn.Client(svnsettingpath)
     client.set_store_passwords(True)
     client.set_auth_cache(True)
     
     def get_login( realm, username, may_save ):
         if svn_client_gui_parent is None : 
             print 'Login is None'
             return False, '', '', False
         import logindialog
         dialog = qt.QtGui.QDialog(svn_client_gui_parent)
         widget = logindialog.Ui_LoginDialog()
         widget.setupUi(dialog)
         dialog.setWindowTitle(realm)
         widget.loginEdit.setText(username)
         if dialog.exec_() != qt.QtGui.QDialog.Accepted:
             return False, '', '', False
         else:
             return True, str(widget.loginEdit.text()), str(widget.passEdit.text()), True
         
     def ssl_client_cert_password_prompt( realm, may_save ):
         if svn_client_gui_parent is None : return False, '', False
         import logindialog
         dialog = qt.QtGui.QDialog(svn_client_gui_parent)
         widget = logindialog.Ui_LoginDialog()
         widget.setupUi(dialog)
         dialog.setWindowTitle(realm)
         widget.loginLabel.setText('Domain')
         widget.loginEdit.setText(realm)
         if dialog.exec_() != qt.QtGui.QDialog.Accepted:
             return False, '', False
         else:
             return True,  str(widget.passEdit.text()), True
         
     #def callback_notify(event_dict):
     #    client.parent.lpystudio.statusBar().showMessage(str(event_dict))
      
     def ssl_server_trust_prompt(trust_dict ):
         if svn_client_gui_parent is None: return True, True, True
         msg = 'The authenticity of host "%s" can\' t be established.\nRSA key fingerprint is %s.\nValid from %s to %s.\nCertified by %s.\nAccept ?'
         msg = msg % (trust_dict['hostname'], trust_dict['finger_print'],trust_dict['valid_from'],trust_dict['valid_until'],trust_dict['issuer_dname'])
         ok = QMessageBox.question(svn_client_gui_parent,'RSA Authentification of '+trust_dict['realm'], msg, QMessageBox.Ok,QMessageBox.Cancel )
         return ok == QMessageBox.Ok, True, True
     
     # client.callback_cancel
     # client.callback_get_log_message
     client.callback_get_login = get_login
     # client.callback_notify = callback_notify
     # client.callback_ssl_client_cert_prompt 
     client.callback_ssl_client_cert_password_prompt = ssl_client_cert_password_prompt
     client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt        
     return client
Пример #16
0
 def run(self):
     logging.basicConfig(level=logging.WARN)
     logger = logging.getLogger("ScreepsStats")
     logger.setLevel(logging.WARN)
     settings = getSettings()
     screepsconsole = ScreepsConsole(user=settings['screeps_username'],
                                     password=settings['screeps_password'],
                                     ptr=settings['screeps_ptr'])
     screepsconsole.start()
Пример #17
0
 def __init__(self, u=None, p=None, ptr=False, host=None, secure=True):
     self.user = u
     self.password = p
     self.ptr = ptr
     self.processed_ticks = {}
     settings = getSettings()
     self.prefix = settings['es_prefix']
     ELASTICSEARCH_HOST = settings['elasticsearch_host']
     self.es = Elasticsearch([ELASTICSEARCH_HOST])
Пример #18
0
    def getConsoleListWalker(self):
        if not self.listWalker:
            self.listWalker = consoleWalker([self.getWelcomeMessage()])
            config = settings.getSettings()
            if 'max_buffer' in config:
                self.listWalker.max_buffer = config['max_buffer']
            else:
                self.listWalker.max_buffer = 200000

        return self.listWalker
Пример #19
0
    def getConsoleListWalker(self):
        if not self.listWalker:
            self.listWalker = consoleWalker([self.getWelcomeMessage()])
            config = settings.getSettings()
            if 'max_buffer' in config:
                self.listWalker.max_buffer = config['max_buffer']
            else:
                self.listWalker.max_buffer = 200000

        return self.listWalker
Пример #20
0
    def setUp(self):
        self.app = QApplication(sys.argv)
        self.settings = getSettings('test')
        self.settings.settings.clear()
        self.settings.artistDefaults.clear()
        self.settings.artistNames.clear()
        self.settings.completed.clear()
        self.settings['defaultArt'] = 'Visicon'

        self.queuedialog = QueueDialog()
Пример #21
0
    def __init__(self, metadata, parent=None):
        """
        @type  metadata: dict
        @param metadata: The dict returned by parsetxt.TxtParser.parseTxt()
        
        """
        super(ConfirmMetadataDialog, self).__init__(parent)
        self.metadata = metadata
        self.setupUi(self)
        self.setWindowFlags(Qt.Window)
        self.playing = False  # The track currently playing (0-indexed)

        artistDefaults = getSettings().getArtistDefaults(metadata['artist'])
        if artistDefaults:
            self.artistLineEdit.setText(artistDefaults['preferred_name'] \
                .decode('utf_8'))
        else:
            self.artistLineEdit.setText(metadata['artist'])

        pyDate = metadata['date']
        if pyDate == None:
            pyDate = datetime.date.today()
        self.dateEdit.setDate(QDate(pyDate.year, pyDate.month, pyDate.day))
        self.locationLineEdit.setText(metadata['location'])
        self.venueLineEdit.setText(metadata['venue'])
        self.titleLineEdit.setText(metadata['title'] if 'title' in
                                   metadata else '')
        if artistDefaults and 'genre' in artistDefaults:
            self.genreLineEdit.setText(artistDefaults['genre'])

        self.tracklistTableWidget.setRowCount(len(metadata['tracklist']))
        self.tracklistTableWidget.setColumnCount(1)
        self.tracklistTableWidget.setColumnWidth(0, 2000)
        # Don't label the column header
        self.tracklistTableWidget.setHorizontalHeaderLabels([''])
        self.connect(self.tracklistTableWidget.verticalHeader(),
                     SIGNAL('sectionPressed(int)'), self.playOrStopSelected)

        self.playButtonIcon = QIcon(
            QPixmap(data.path + '/' + 'media' + '/' + 'play.png'))
        self.stopButtonIcon = QIcon(
            QPixmap(data.path + '/' + 'media' + '/' + 'stop.png'))

        for track, title in enumerate(metadata['tracklist']):
            playItem = QTableWidgetItem(str(track + 1))
            playItem.setIcon(self.playButtonIcon)
            self.tracklistTableWidget.setVerticalHeaderItem(track, playItem)
            nameItem = QTableWidgetItem(title)
            if metadata['audioFiles'][track] in metadata['md5_mismatches']:
                nameItem.setBackground(QBrush(QColor(255, 255, 0)))
                nameItem.setToolTip(
                    'MD5 hash does not match.  File may be corrupted.')
            self.tracklistTableWidget.setItem(track, 0, nameItem)
        self.commentsTextEdit.setText(metadata['comments'])
Пример #22
0
    def removeCompletedRecordings(self):
        """
        Remove items that have been set as completed from the queue.

        """
        for recording in self.validRecordings:
            if getSettings().isCompleted(recording['metadata']['hash']):
                self.queueListWidget.takeItem(
                    self.queueListWidget.row(recording['item']))
                key = recording['metadata']['dir'].absolutePath()
                del self.queueItemData[key]
Пример #23
0
    def loadingComplete(self):
        """
        Called when the LoadShowsThread has completed.
        If a single show is loaded, will bring up the confirm metadata
        dialog.  If multiple shows loaded, will add them to the queue.

        """
        # Single show
        if hasattr(self, 'metadata') and self.metadata:
            isCompleted = getSettings().isCompleted(self.metadata['hash'])
            if isCompleted:
                basename = os.path.basename(
                    unicode(self.metadata['dir'].absolutePath()))
                if self.convertAgainPrompt(basename):
                    getSettings().removeCompleted(self.metadata['hash'])
                else:
                    return
            ConfirmMetadataDialog(self.metadata, self).exec_()
        # Multiple shows
        elif hasattr(self, 'metadataList') and self.metadataList:
            for metadata in self.metadataList:
                isCompleted = getSettings().isCompleted(metadata['hash'])
                if isCompleted:
                    basename = os.path.basename(
                        unicode(metadata['dir'].absolutePath()))
                    if self.convertAgainPrompt(basename):
                        getSettings().removeCompleted(metadata['hash'])
                    else:
                        continue
                self.addToQueue(metadata)
Пример #24
0
def main():
    face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    classifier = load_model('EmotionDetectionModel.h5')
    class_labels = ['Angry', 'Happy', 'Neutral', 'Sad']
    cameraSettings = settings.getSettings()
    camera = int(cameraSettings[0])
    cap = cv2.VideoCapture(camera)

    emotions = []

    while len(emotions) < 70:
        ret, frame = cap.read()
        frame = cv2.flip(frame, 1)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_classifier.detectMultiScale(
            gray,
            scaleFactor=1.3,
            minNeighbors=6,
            minSize=(60, 60),
            flags=cv2.CASCADE_SCALE_IMAGE
        )

        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            roi_gray = cv2.resize(roi_gray, (48, 48), interpolation=cv2.INTER_AREA)

            if np.sum([roi_gray]) != 0:
                roi = roi_gray.astype('float') / 255.0
                roi = img_to_array(roi)
                roi = np.expand_dims(roi, axis=0)

                preds = classifier.predict(roi)[0]
                label = class_labels[preds.argmax()]
                label_position = (x, y)
                cv2.putText(frame, label, label_position, cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3)
                emotions.append(label)
            else:
                cv2.putText(frame, 'No Face Found', (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3)

        # uncomment to show camera feed
        # cv2.imshow('Emotion Detector', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

    finalEmotion = mode(emotions)
    print(finalEmotion)
    createPlaylist.main(finalEmotion)
Пример #25
0
    def manageBufferHistory(self):
        path = expanduser('~') + '/.screeps_history'
        with open(path, 'r') as myfile:
            file_contents = myfile.read()
            file_contents_line = file_contents.splitlines()
            num_lines = len(file_contents_line)
            config = settings.getSettings()
            if 'max_history' in config:
                max_scroll = config['max_history']
            else:
                max_scroll = 200000

            if num_lines > max_scroll:
                truncate = num_lines - max_scroll
                list_copy = file_contents_line[:]
                list_copy = [s + "\n" for s in list_copy]
                open(path, 'w').writelines(list_copy[truncate+1:])
Пример #26
0
    def manageBufferHistory(self):
        path = expanduser('~') + '/.screeps_history'
        with open(path, 'r') as myfile:
            file_contents = myfile.read()
            file_contents_line = file_contents.splitlines()
            num_lines = len(file_contents_line)
            config = settings.getSettings()
            if 'max_history' in config:
                max_scroll = config['max_history']
            else:
                max_scroll = 200000

            if num_lines > max_scroll:
                truncate = num_lines - max_scroll
                list_copy = file_contents_line[:]
                list_copy = [s + "\n" for s in list_copy]
                open(path, 'w').writelines(list_copy[truncate+1:])
Пример #27
0
    def restoreDefaults(self):
        self.albumTitleFormatLineEdit.setText(getSettings().defaults['albumTitleFormat'])
        
        if getSettings().defaults['defaultArt'] == 'Image File => Identicon':
            self.defaultArtRadioButtonImageFileIdenticon.setChecked(True)
        elif getSettings().defaults['defaultArt'] == 'Image File => Visicon':
            self.defaultArtRadioButtonImageFileVisicon.setChecked(True)
        elif getSettings().defaults['defaultArt'] == 'Visicon':
            self.defaultArtRadioButtonVisicon.setChecked(True)
        else:
            self.defaultArtRadioButtonIdenticon.setChecked(True)
    
        self.checkForUpdatesCheckBox.setChecked(getSettings().defaults['checkForUpdates'])
        self.sendErrorReportsCheckBox.setChecked(getSettings().defaults['sendErrorReports'])
        self.verifyMd5HashesCheckBox.setChecked(getSettings().defaults['verifyMd5Hashes'])

        defaultAddToITunesPath = getSettings().getDetectedAddToITunesPath()
        if defaultAddToITunesPath:
            self.addToITunesPathTextEdit.setText(defaultAddToITunesPath)

        # Select the value saved in settings
        self.dateFormatComboBox.setCurrentIndex(
            self.dateFormatComboBox.findData(getSettings().defaults['dateFormat'])
        )
Пример #28
0
    def accept(self):
        getSettings()['albumTitleFormat'] = unicode(self.albumTitleFormatLineEdit.text())
        getSettings()['dateFormat'] = unicode(self.dateOptionsFormat[self.dateFormatComboBox.currentIndex()])

        for value, button in self.defaultArtRadioButtons.iteritems():
            if button.isChecked():
                getSettings()['defaultArt'] = value

        getSettings()['checkForUpdates'] = self.checkForUpdatesCheckBox.isChecked()
        
        getSettings()['sendErrorReports'] = self.sendErrorReportsCheckBox.isChecked()

        getSettings()['verifyMd5Hashes'] = self.verifyMd5HashesCheckBox.isChecked()
        
        getSettings()['addToITunesPath'] = unicode(self.addToITunesPathTextEdit.toPlainText())

        self.parentWidget().refreshQueue()
        self.close()
Пример #29
0
    def __init__(self, parent=None):
        super(SettingsDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(Qt.Window)
        self.resize(0, 0) # fixes problem of the window being too big on Windows

        self.albumTitleFormatLineEdit.setText(getSettings()['albumTitleFormat'])

        self.defaultArtRadioButtons = {
            'Identicon'                 : self.defaultArtRadioButtonIdenticon,
            'Visicon'                   : self.defaultArtRadioButtonVisicon,
            'No Cover Art'              : self.defaultArtRadioButtonNoCoverArt,
            'Image File => Identicon'   : self.defaultArtRadioButtonImageFileIdenticon,
            'Image File => Visicon'     : self.defaultArtRadioButtonImageFileVisicon,
            'Image File => No Cover Art': self.defaultArtRadioButtonImageFileNoCoverArt
        }

        for value, button in self.defaultArtRadioButtons.iteritems():
            if getSettings()['defaultArt'] == value:
                button.setChecked(True)
                break

        if getSettings()['checkForUpdates']:
            self.checkForUpdatesCheckBox.setChecked(True)

        if getSettings()['sendErrorReports']:
            self.sendErrorReportsCheckBox.setChecked(True)

        if getSettings()['verifyMd5Hashes']:
            self.verifyMd5HashesCheckBox.setChecked(True)

        self.addToITunesPathTextEdit.setText(getSettings()['addToITunesPath'])

        # Set the ComboBox values
        for index, display in enumerate(self.dateOptionsDisplay):
            self.dateFormatComboBox.addItem(display, self.dateOptionsFormat[index])

        # Select the value saved in settings
        self.dateFormatComboBox.setCurrentIndex(
            self.dateFormatComboBox.findData(getSettings()['dateFormat'])
        )
Пример #30
0
	def __init__(self):
		settings.getSettings()
		print "index"+settings.ES_INDEX_NAME
Пример #31
0
    def on_message(self, ws, message):
        if (message.startswith('auth ok')):
            ws.send('subscribe user:'******'/console')
            return

        if (message.startswith('time')):
            return

        if (message.startswith('gz')):
            try:
                decoded = b64decode(message[3:])
                message = zlib.decompress(decoded, 0)
            except:
                print("Unexpected error:", sys.exc_info())
                return

        data = json.loads(message)

        if 'shard' in data[1]:
            shard = data[1]['shard']
        else:
            shard = 'shard0'


        if 'messages' in data[1]:
            stream = []

            messages = data[1]["messages"]
            if 'log' in messages:
                stream.extend(messages['log'])

            if 'results' in messages:
                results = messages['results']
                results = map(lambda x:'<type="result">'+x+'</type>',results)
                stream.extend(results)

            message_count = len(stream)

            if message_count > 0:
                config = settings.getSettings()
                # Make sure the delay doesn't cause an overlap into other ticks
                if 'smooth_scroll' in config and config['smooth_scroll'] is True:
                    message_delay = 0.2 / message_count
                    if message_delay > 0.07:
                        message_delay = 0.07
                else:
                    message_delay = 0.00001

                for line in stream:
                    if self.format == 'color':
                        line_parsed = '%s: %s' % (shard, parseLine(line))
                    elif self.format == 'json':
                        line_parsed = json.dumps({'line':line,'shard':shard})
                    else:
                        line_parsed = '%s: %s' % (shard, tagLine(line))

                    print(line_parsed)
                    sys.stdout.flush()
                    sleep(message_delay) # sleep for smoother scrolling
            return
        else:
            if 'error' in data[1]:
                #line = '<'+data[1]['error']
                line = "<severity=\"5\" type=\"error\">" + data[1]['error'] + "</font>"
                if self.format == 'color':
                    line_parsed = '%s: %s' % (shard, parseLine(line))
                elif self.format == 'json':
                    line_parsed = json.dumps({'line':line,'shard':shard})
                else:
                    line_parsed = '%s: %s' % (shard, tagLine(line))

                print(line_parsed)
                return
            else:
                print('undiscovered protocol feature')
                print(json.dumps(message))

        print('on_message', message)
Пример #32
0
            confirm_queue.append(tick)

        for (indexname, docs) in data_by_indices.items():
            helpers.bulk(self.es, docs)
        self.confirm(confirm_queue, shard)

    def confirm(self, ticks, shard):
        javascript_clear = 'Stats.removeTick(' + json.dumps(
            ticks, separators=(',', ':')) + ');'
        sconn = self.getScreepsAPI()
        sconn.console(javascript_clear, shard)

    def clean(self, datadict):
        newdict = {}
        for key, value in datadict.items():
            if key == 'tick':
                newdict[key] = int(value)
            else:
                try:
                    newdict[key] = float(value)
                except:
                    newdict[key] = value
        return datadict


if __name__ == "__main__":
    settings = getSettings()
    screepsconsole = ScreepsMemoryStats(token=settings['screeps_token'],
                                        ptr=settings['screeps_ptr'])
    screepsconsole.run_forever()
Пример #33
0
 def getScreepsAPI(self):
     if not self.__api:
         settings = getSettings()
         self.__api = screepsapi.API(u=settings['screeps_username'],p=settings['screeps_password'],ptr=settings['screeps_ptr'])
     return self.__api
Пример #34
0
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options

from settings import getSettings
settings = getSettings()

if 'CACHE_ROOT' in settings:
    cache_root = settings['CACHE_ROOT']
else:
    cache_root = '/tmp/screepsstats'

cache_opts = {
    'cache.type': 'file',
    'cache.data_dir': cache_root + '/data',
    'cache.expire': 3600,
    'cache.lock_dir': cache_root + '/lock'
}

cache = CacheManager(**parse_cache_config_options(cache_opts))
Пример #35
0
def main(emotion):
    getSettings = settings.getSettings()
    SPOTIFY_USER_ID = getSettings[1].replace('\n', '')
    SPOTIFY_AUTHORIZATION_TOKEN = getSettings[2].replace('\n', '')

    happy_playlist_id = "1h90L3LP8kAJ7KGjCV2Xfd"
    sad_playlist_id = "37i9dQZF1DX7qK8ma5wgG1"
    neutral_playlist_id = "4PFwZ4h1LMAOwdwXqvSYHd"
    angry_playlist_id = "3uaOn723EyF8eF7GhtJkyD"
    x = 0

    spotify_client = SpotifyClient(SPOTIFY_AUTHORIZATION_TOKEN,
                                   SPOTIFY_USER_ID)

    if emotion == 'Happy':
        playlist_list = spotify_client.get_playlist()
        playlist_id = happy_playlist_id
    elif emotion == 'Sad':
        playlist_list = spotify_client.get_playlist()
        playlist_id = sad_playlist_id
    elif emotion == 'Neutral':
        playlist_list = spotify_client.get_playlist()
        playlist_id = neutral_playlist_id
    elif emotion == 'Angry':
        playlist_list = spotify_client.get_playlist()
        playlist_id = angry_playlist_id
    else:
        print("Invalid emotion entered")
        quit()

    # spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
    #                                os.getenv("SPOTIFY_USER_ID"))

    playlist_musics = spotify_client.get_playlist_songs(playlist_id)
    # for index, track in enumerate(playlist_musics):
    # print(f"{index+1} - {track}")

    if emotion == 'Happy':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 100))
            x += 1
    elif emotion == 'Sad':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 60))
            x += 1
    elif emotion == 'Neutral':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 85))
            x += 1
    elif emotion == 'Angry':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 100))
            x += 1

    seed_tracks = [playlist_musics[int(index) - 1] for index in indexes]

    recommended_tracks = spotify_client.get_track_recommendations(seed_tracks)

    if emotion == 'Happy':
        playlist_name = "Happy Playlist"
    elif emotion == 'Sad':
        playlist_name = "Sad Playlist"
    elif emotion == 'Neutral':
        playlist_name = "Neutral Playlist"
    elif emotion == 'Angry':
        playlist_name = "Angry Playlist"

    playlist = spotify_client.create_playlist(playlist_name)
    print(f"Playlist '{playlist.name}' was created successfully.")

    spotify_client.populate_playlist(playlist, recommended_tracks)
    print(
        f"Recommended tracks successfully uploaded to playlist '{playlist.name}'"
    )
def runLikedSavedDownloader(pipeConnection):
    if pipeConnection:
        logger.setPipe(pipeConnection)

    settings.getSettings()

    if (not settings.settings['Use_cached_submissions']
            and not settings.hasTumblrSettings()
            and not settings.hasRedditSettings()):
        logger.log(
            'Please provide Tumblr or Reddit account details settings.txt')
        return

    imgurAuth = None
    if (settings.settings['Should_download_albums']
            and settings.hasImgurSettings()):
        imgurAuth = imageSaver.ImgurAuth(
            settings.settings['Imgur_client_id'],
            settings.settings['Imgur_client_secret'])
    else:
        logger.log(
            'No Imgur Client ID and/or Imgur Client Secret was provided, or album download is not'
            ' enabled. This is required to download imgur albums. They will be ignored. Check'
            ' settings.txt for how to fill in these values.')

    logger.log('Output: ' + settings.settings['Output_dir'])

    # TODO: Only save one post for early out. Only save once all downloading is done
    redditRequestOnlyNewSavedCache = None
    redditRequestOnlyNewLikedCache = None
    if settings.settings['Reddit_Try_Request_Only_New']:
        redditRequestOnlyNewSavedCache = submission.readCacheSubmissions(
            settings.settings['Reddit_Try_Request_Only_New_Saved_Cache_File'])
        redditRequestOnlyNewLikedCache = submission.readCacheSubmissions(
            settings.settings['Reddit_Try_Request_Only_New_Liked_Cache_File'])

    tumblrRequestOnlyNewCache = None
    if settings.settings['Tumblr_Try_Request_Only_New']:
        tumblrRequestOnlyNewCache = submission.readCacheSubmissions(
            settings.settings['Tumblr_Try_Request_Only_New_Cache_File'])

    submissions = []

    if settings.settings['Use_cached_submissions']:
        logger.log('Using cached submissions')
        submissions += submission.readCacheSubmissions(
            settings.settings['Reddit_cache_file'])
        submissions += submission.readCacheSubmissions(
            settings.settings['Tumblr_cache_file'])
    else:
        if settings.hasRedditSettings():
            redditSubmissions, redditComments, earlyOutPoints = redditScraper.getRedditUserLikedSavedSubmissions(
                settings.settings['Username'],
                settings.settings['Password'],
                settings.settings['Client_id'],
                settings.settings['Client_secret'],
                request_limit=settings.settings['Reddit_Total_requests'],
                saveLiked=settings.settings['Reddit_Save_Liked'],
                saveSaved=settings.settings['Reddit_Save_Saved'],
                earlyOutPointSaved=redditRequestOnlyNewSavedCache,
                earlyOutPointLiked=redditRequestOnlyNewLikedCache,
                unlikeLiked=settings.settings['Reddit_Unlike_Liked'],
                unsaveSaved=settings.settings['Reddit_Unsave_Saved'])

            # Cache them in case it's needed later
            submission.writeCacheSubmissions(
                redditSubmissions, settings.settings['Reddit_cache_file'])

            # Set new early out points
            submission.writeCacheSubmissions(
                [earlyOutPoints[0]], settings.
                settings['Reddit_Try_Request_Only_New_Saved_Cache_File'])
            submission.writeCacheSubmissions(
                [earlyOutPoints[1]], settings.
                settings['Reddit_Try_Request_Only_New_Liked_Cache_File'])

            submissions += redditSubmissions

            # For reddit only: write out comments to separate json file
            if settings.settings['Reddit_Save_Comments']:
                submission.saveSubmissionsAsJson(
                    redditComments, settings.settings['Output_dir'] + u'/' +
                    'Reddit_SavedComment_Submissions_' +
                    time.strftime("%Y%m%d-%H%M%S") + '.json')
                submission.saveSubmissionsAsHtml(
                    redditComments, settings.settings['Output_dir'] + u'/' +
                    'Reddit_SavedComment_Submissions_' +
                    time.strftime("%Y%m%d-%H%M%S") + '.html')
                logger.log('Saved ' + str(len(redditComments)) +
                           ' reddit comments')

        if settings.hasTumblrSettings():
            tumblrSubmissions, earlyOutPoint = tumblrScraper.getTumblrUserLikedSubmissions(
                settings.settings['Tumblr_Client_id'],
                settings.settings['Tumblr_Client_secret'],
                settings.settings['Tumblr_Client_token'],
                settings.settings['Tumblr_Client_token_secret'],
                likeRequestLimit=settings.settings['Tumblr_Total_requests'],
                requestOnlyNewCache=tumblrRequestOnlyNewCache)

            # Cache them in case it's needed later
            submission.writeCacheSubmissions(
                tumblrSubmissions, settings.settings['Tumblr_cache_file'])

            # Set new early out point
            submission.writeCacheSubmissions(
                [earlyOutPoint],
                settings.settings['Tumblr_Try_Request_Only_New_Cache_File'])

            submissions += tumblrSubmissions

        # Write out a .json file with all of the submissions in case the user wants the data
        submission.saveSubmissionsAsJson(
            submissions, settings.settings['Output_dir'] + u'/' +
            'AllSubmissions_' + time.strftime("%Y%m%d-%H%M%S") + '.json')

    logger.log('Saving images. This will take several minutes...')
    unsupportedSubmissions = imageSaver.saveAllImages(
        settings.settings['Output_dir'],
        submissions,
        imgur_auth=imgurAuth,
        only_download_albums=settings.settings['Only_download_albums'],
        skip_n_percent_submissions=settings.
        settings['Skip_n_percent_submissions'],
        soft_retrieve_imgs=settings.settings['Should_soft_retrieve'],
        only_important_messages=settings.settings['Only_important_messages'])

    # Write out a .json file listing all of the submissions the script failed to download
    submission.saveSubmissionsAsJson(
        unsupportedSubmissions, settings.settings['Output_dir'] + u'/' +
        'UnsupportedSubmissions_' + time.strftime("%Y%m%d-%H%M%S") + '.json')

    if settings.settings['Should_soft_retrieve']:
        logger.log(
            '\nYou have run the script in Soft Retrieve mode - if you actually\n'
            'want to download images now, you should change SHOULD_SOFT_RETRIEVE\n'
            'to False in settings.txt')

    if pipeConnection:
        logger.log(scriptFinishedSentinel)
        pipeConnection.close()
Пример #37
0
 def getApiClient(self):
     if not self.apiclient:
         settings = getSettings()
         self.apiclient = ScreepsConnection(u=settings['screeps_username'],p=settings['screeps_password'],ptr=settings['screeps_ptr'])
     return self.apiclient
Пример #38
0
        if len(sys.argv) < 3:
            server = 'main'
        else:
            server = sys.argv[2]
        settings.removeConnection(server)
        sys.exit(0)

    connectionSettings = settings.getConnection(server)

    if not connectionSettings:
        if server == 'main' or server == 'ptr':
            legacyConfig = settings.getLegacySettings()
            if legacyConfig:
                if input("Upgrade settings file to the new format? (y/n) ") == "y":
                    settings.addConnection('main', legacyConfig['screeps_username'], legacyConfig['screeps_password'])
                    config = settings.getSettings()
                    config['smooth_scroll'] = legacyConfig['smooth_scroll']
                    config['max_scroll'] = legacyConfig['max_scroll']
                    config['max_history'] = legacyConfig['max_history']
                    settings.saveSettings(config)
                    connectionSettings = settings.getConnection(server)

    if not connectionSettings:
        if server is 'main':
            host = 'screeps.com'
            secure = True
        else:
            host = input("Host: ")
            secure = input("Secure (y/n) ") == "y"
        username = input("Username: "******"Password: ")
Пример #39
0
#!/usr/bin/python3
import board, neopixel, time
import networkTables, settings, threading
from group import LEDSection, SectionGroup
from copy import deepcopy

import chassieStates

sett = settings.getSettings()

NUM_LED = 38 * 2
NEO_PIN = board.D18

pixels = neopixel.NeoPixel(NEO_PIN, NUM_LED, auto_write=False, brightness=0.25)
pixels.show()

tables = networkTables.tables()

frameLeft = LEDSection(pixels, 0, 38)
frameRight = LEDSection(pixels, 38, 76, inverted=True)

groups = {
    "frameLeft":
    frameLeft,
    "frameRight":
    frameRight,
    "frame":
    SectionGroup(frameLeft, frameRight),
    "frameCircle":
    SectionGroup(deepcopy(frameLeft),
                 deepcopy(frameRight).setInverted(False))
Пример #40
0
            server = 'main'
        else:
            server = sys.argv[2]
        settings.removeConnection(server)
        sys.exit(0)

    connectionSettings = settings.getConnection(server)

    if not connectionSettings:
        if server == 'main' or server == 'ptr':
            legacyConfig = settings.getLegacySettings()
            if legacyConfig:
                if raw_input("Upgrade settings file to the new format? (y/n) ") != "y":
                    sys.exit(-1)
                settings.addConnection('main', legacyConfig['screeps_username'], legacyConfig['screeps_password'])
                config = settings.getSettings()
                config['smooth_scroll'] = legacyConfig['smooth_scroll']
                config['max_scroll'] = legacyConfig['max_scroll']
                config['max_history'] = legacyConfig['max_history']
                settings.saveSettings(config)
                connectionSettings = settings.getConnection(server)

    if not connectionSettings:
        if server is 'main':
            host = 'screeps.com'
            secure = True
        else:
            host = raw_input("Host: ")
            secure = raw_input("Secure (y/n) ") == "y"
        username = raw_input("Username: "******"Password: ")