Ejemplo n.º 1
0
def main():
    """It's the main function. You call this to start the bot."""
    try:
        settings.load()
    except (FileNotFoundError or IOError or json.decoder.JSONDecodeError):
        settings.save()
    try:
        settings.manager["OAUTH_TOKEN_DISCORD"]
    except KeyError:
        print(
            "Please enter an OAuth token for this bot, so it can sign into Discord."
        )
        settings.manager["OAUTH_TOKEN_DISCORD"] = input("> ")
    try:
        settings.manager["SUPPORT_GUILD"]
    except KeyError:
        print(
            "Please enter a support guild link for this bot. You may leave it blank."
        )
        settings.manager["SUPPORT_GUILD"] = input("> ")
    logger.info("Warming up...")
    extensions = settings.manager.get("EXTENSIONS",
                                      settings.DEFAULT_EXTENSIONS)

    for extension in extensions:
        logger.info(f"Loading extension {extension}")
        try:
            bot.load_extension(extension)
            logger.info(f"Extension {extension} loaded")
        except Exception as error:
            logger.warning(f"Extension {extension} seems to be broken")
            logger.warning(error)

    bot.run(settings.manager["OAUTH_TOKEN_DISCORD"])
Ejemplo n.º 2
0
 def load_motion_list(self, path):
     print("Importing Animation Set")
     self.populate_animSet(path)
     self.settings.DEFAULT_DIR_KEY = os.path.dirname(path)
     self.lastDir = self.settings.DEFAULT_DIR_KEY
     self.append_recent_file(path)
     settings.save(self.settings)
Ejemplo n.º 3
0
	def handle_option(self, choice):
		if choice == 0: # if we want to wipe our saves...
			self.dlog.show_choices(["Yes, wipe all of my saves.", "No, I want to keep my saves."])
			self.handle_c = self.handle_wipe
		elif choice == 5: # ...or return to the main menu, we should not use our start_options() function for our toggles.
			self.update_func = self.update
			settings.save()

			sub_bg_pos = (MENU_POS[0], settings.screen_y-self.dlog.dlog_height+MENU_POS[1])
			sub_bg =  self.titlescreen.bg.subsurface(pygame.Rect(
													sub_bg_pos, (self.dlog.dlog_width, self.dlog.dlog_height) ))
			self.surf.blit(sub_bg, sub_bg_pos)

			self.g.sounds['openMenu'].play()
			self.show()
		else: # otherwise, we should activate our toggle switch and refresh the options menu
			if choice == 1:
				settings.option_music = not settings.option_music
				music.play(-1)
				if not settings.option_music: music.fadeout(500)
			elif choice == 2: settings.option_sound = not settings.option_sound
			elif choice == 3: settings.parallax = not settings.parallax
			elif choice == 4:
				fullscreen = pygame.FULLSCREEN if settings.fullscreen else 0 #if fullscreen is turned on in the settings, enable it
				self.g.screen = pygame.display.set_mode((settings.screen_x*settings.screen_scale, settings.screen_y*settings.screen_scale), fullscreen) #recreate the window to draw on
			self.start_options()
Ejemplo n.º 4
0
    def _dispatch_builtin_command(self, command):
        self._reset()
        magic, category, key, value = command.split(':')
        if magic == 'builtin':
            if category == 'settings':
                try:
                    value = eval(value)
                except e:
                    logging.exception(e)
                    return False
                if key == 'romanrule':
                    self._charbuf.compile(value)
                    self._charbuf_alter.compile(value)
                elif key == 'use_title':
                    title.setenabled(value)
                settings.set(key, value)
                settings.save()
                return True
            elif category == 'task':
                if key == 'switch':
                    window_id = int(value)
                    if window_id == 0:
                        self._session.blur_process()
                    else:
                        self._draw_nothing(self._output)
                        self._inputmode.reset()
                        self._reset()
                        self._screen.taskswitch(window_id)

            return False
        return False
Ejemplo n.º 5
0
 async def delete(self, ctx, key: str):
     """Delete a value in the bot's settings by key. Bot owner only."""
     try:
         del settings.manager[key]
     except KeyError:
         raise commands.UserInputError("You entered an invalid key!")
     settings.save()
     await ctx.send(f"`{key}` removed from settings.")
Ejemplo n.º 6
0
 def auto_accept(self, num, value):
     settings = Settings.get_instance()
     tox_id = self.profile.friend_public_key(num)
     if value:
         settings['auto_accept_from_friends'].append(tox_id)
     else:
         settings['auto_accept_from_friends'].remove(tox_id)
     settings.save()
Ejemplo n.º 7
0
    def _static_processing(self):

        self.logger.info("Static processing thread starting")
        idx = -1

        # resume processing with the last image the user looked at
        last_img = settings.get('processing/last_img', None)
        for i, image_name in enumerate(self.images):
            if image_name == last_img:
                self.idx = i
                break

        while True:

            with self.condition:

                # wait until the user hits a key
                while idx == self.idx and not self.do_stop and not self.do_refresh:
                    self.condition.wait()

                if self.do_stop:
                    break

                idx = self.idx
                self.do_refresh = False

            # if the index is valid, then process an image
            if idx < len(self.images) and idx >= 0:

                image_name = self.images[idx]

                self.logger.info("Opening %s" % image_name)

                img = cv2.imread(image_name)
                if img is None:
                    self.logger.error("Error opening %s: could not read file" %
                                      (image_name))
                    self.camera_widget.set_error()
                    self.idx += self.idx_increment
                    continue

                try:
                    target_data = self.detector.process_image(img)
                except:
                    logutil.log_exception(self.logger,
                                          'error processing image')
                    self.camera_widget.set_error(img)
                else:
                    settings.set('processing/last_img', image_name)
                    settings.save()

                    self.logger.info('Finished processing')

                    # note that you cannot typically interact with the UI
                    # from another thread -- but this function is special
                    self.camera_widget.set_target_data(target_data)

        self.logger.info("Static processing thread exiting")
Ejemplo n.º 8
0
def init():
    stats = RunStats(start=datetime.datetime.now(),
                     batch_count=0,
                     last_update=datetime.datetime.now())
    stats.save()

    settings = Settings(doc_topic_score_threshold=1,
                        doc_topic_scaled_score=True)
    settings.save()
Ejemplo n.º 9
0
 def _static_processing(self):
     
     self.logger.info("Static processing thread starting")
     idx = -1
     
     # resume processing with the last image the user looked at
     last_img = settings.get('processing/last_img', None)
     for i, image_name in enumerate(self.images):
         if image_name == last_img:
             self.idx = i
             break 
     
     while True:
     
         with self.condition:
             
             # wait until the user hits a key
             while idx == self.idx and not self.do_stop and not self.do_refresh:
                 self.condition.wait()
             
             if self.do_stop:
                 break
             
             idx = self.idx
             self.do_refresh = False
                 
         # if the index is valid, then process an image
         if idx < len(self.images) and idx >= 0:
             
             image_name = self.images[idx]
             
             self.logger.info("Opening %s" % image_name)
             
             img = cv2.imread(image_name)
             if img is None:
                 self.logger.error("Error opening %s: could not read file" % (image_name))
                 self.camera_widget.set_error()
                 self.idx += self.idx_increment
                 continue
             
             try:
                 target_data = self.detector.process_image(img)
             except:
                 logutil.log_exception(self.logger, 'error processing image')
                 self.camera_widget.set_error(img)
             else:
                 settings.set('processing/last_img', image_name)
                 settings.save()
                 
                 self.logger.info('Finished processing')
             
                 # note that you cannot typically interact with the UI
                 # from another thread -- but this function is special
                 self.camera_widget.set_target_data(target_data)
         
     self.logger.info("Static processing thread exiting")
Ejemplo n.º 10
0
def main():
    vista.init()
    vista.addsplash()
    pygame.display.set_caption(_("Obb is loading.... Please wait"))
    noise.nexttrack()
    if settings.restart:
        game.restart()
    else:
        game.load()
    context.push(play.Play())
    clock = pygame.time.Clock()
    savetime = settings.savetimer
    while context.top():
        dt = clock.tick(settings.maxfps) * 0.001 * settings.gamespeed
        dt = min(dt, 1.0 / settings.minfps)
        con = context.top()
        events = pygame.event.get()
        keys = pygame.key.get_pressed()
        mousepos = pygame.mouse.get_pos()
        buttons = pygame.mouse.get_pressed()

        if settings.autosave:
            savetime -= dt
            if savetime < 0:
                game.save()
                settings.save()
                savetime = settings.savetimer

        for event in events:
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                if settings.saveonquit:
                    settings.save()
                    game.save()
                pygame.quit()
                return
            if event.type == KEYDOWN and event.key == K_F12:
                vista.screencap()
            if event.type == KEYDOWN and event.key == K_F3:
                settings.showfps = not settings.showfps

        con.think(dt, events, keys, mousepos, buttons)
        con.draw()
        if settings.showfps:
            t = pygame.time.get_ticks() * 0.001
            if int(t / 5.0) != int((t - dt) / 5.0):  # Update once every 5 seconds
                fpsstring = "%.1ffps" % clock.get_fps()
                try:
                    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024
                    fpsstring += " %sMB" % mem
                except:
                    pass
                pygame.display.set_caption("Obb - %s" % fpsstring)
                if settings.fullscreen:
                    print(fpsstring)
        else:
            pygame.display.set_caption("Obb")
Ejemplo n.º 11
0
 async def changeGame(self,
                      name=None,
                      type=discord.ActivityType.playing,
                      save=True):
     log.info(f"Changing game presence to '{name}' with type {type}")
     settings["gamePlaying"] = {"name": name, "type": int(type)}
     if name:
         await self.change_presence(
             activity=discord.Activity(name=name, type=type))
     if save:
         settingsModule.save()
Ejemplo n.º 12
0
 async def restart(self, ctx):
     """Restart the bot. Only the bot owner can use this."""
     confirm = await helpers.yes_no(ctx, ctx.bot)
     if not confirm:
         return
     message = "Bot is going for restart NOW!"
     logger.warning(message)
     await ctx.send(message)
     await ctx.bot.logout()
     settings.save()
     os.execv(sys.executable, [sys.executable] + sys.argv + ["&"])
Ejemplo n.º 13
0
    def ok_callback(self):
        values = self.save_settings()
        if values is None:
            return
        for name, value in values.items():
            settings.set(name, value)
        settings.save()
        if self.callback:
            self.callback()

        self.close()
Ejemplo n.º 14
0
 def add_recent_file(self, url):
     # Add url to the top of the recent file list.
     assert url
     import settings
     recent = settings.get('recent_documents')
     if url in recent:
         recent.remove(url)
     recent.insert(0, url)
     if len(recent) > NUM_RECENT_FILES:
         recent = recent[:NUM_RECENT_FILES]
     settings.set('recent_documents', recent)
     settings.save()
Ejemplo n.º 15
0
	def finish(self):
		newres = not self.resbuttons.buttonmap[settings.size].selected
		newwin = not self.wbuttons.buttonmap[settings.fullscreen].selected
		for buttonset in self.buttonsets:
			for button in buttonset.buttons:
				if button.selected:
					button.confirm()
		context.pop()
		settings.save()
		settings.load()
		if newres or newwin:
			vista.init()
Ejemplo n.º 16
0
	def start_up(self):
		hello = ["Hello!", "Hi!", "Onii-chan!", "Senpai!", "Hisashiburi!", "Welcome!", "Okaerinasai!", "Welcome back!", "Hajimemashite!"]
		self.notification_bar.add_text("{} Please don't hesitate to report any bugs you find.".format(hello[random.randint(0, len(hello)-1)])+
								 " Go to Settings -> About -> Bug Reporting for more info!")
		level = 5
		def normalize_first_time():
			settings.set(level, 'Application', 'first time level')
			settings.save()

		def done(status=True):
			gallerydb.DatabaseEmitter.RUN = True
			if app_constants.FIRST_TIME_LEVEL != level:
				normalize_first_time()
			if app_constants.ENABLE_MONITOR and\
				app_constants.MONITOR_PATHS and all(app_constants.MONITOR_PATHS):
				self.init_watchers()
				if app_constants.LOOK_NEW_GALLERY_STARTUP:
					if self.manga_list_view.gallery_model.db_emitter.count == app_constants.GALLERY_DATA:
						self.scan_for_new_galleries()
					else:
						self.manga_list_view.gallery_model.db_emitter.DONE.connect(self.scan_for_new_galleries)
			self.download_manager = pewnet.Downloader()
			app_constants.DOWNLOAD_MANAGER = self.download_manager
			self.download_manager.start_manager(4)

		if app_constants.FIRST_TIME_LEVEL < 4:
			log_i('Invoking first time level {}'.format(4))
			settings.set([], 'Application', 'monitor paths')
			settings.set([], 'Application', 'ignore paths')
			app_constants.MONITOR_PATHS = []
			app_constants.IGNORE_PATHS = []
			settings.save()
			done()
		elif app_constants.FIRST_TIME_LEVEL < 5:
			log_i('Invoking first time level {}'.format(5))
			app_widget = misc.ApplicationPopup(self)
			app_widget.note_info.setText("<font color='red'>IMPORTANT:</font> Application restart is required when done")
			app_widget.restart_info.hide()
			self.admin_db = gallerydb.AdminDB()
			self.admin_db.moveToThread(app_constants.GENERAL_THREAD)
			self.admin_db.DONE.connect(done)
			self.admin_db.DONE.connect(lambda: app_constants.NOTIF_BAR.add_text("Application requires a restart"))
			self.admin_db.DONE.connect(self.admin_db.deleteLater)
			self.admin_db.DATA_COUNT.connect(app_widget.prog.setMaximum)
			self.admin_db.PROGRESS.connect(app_widget.prog.setValue)
			self.admin_db_method_invoker.connect(self.admin_db.rebuild_db)
			self.admin_db_method_invoker.connect(app_widget.show)
			app_widget.adjustSize()
			db_p = os.path.join(os.path.split(database.db_constants.DB_PATH)[0], 'sadpanda.db')
			self.admin_db_method_invoker.emit(db_p)
		else:
			done()
Ejemplo n.º 17
0
 async def halt(self, ctx):
     """Halt the bot. Only the bot owner can use this."""
     confirm = await helpers.yes_no(ctx, ctx.bot)
     if not confirm:
         return
     if ctx.invoked_with == "kys":
         message = "Dead! x.x"
     else:
         message = "Bot is going for halt NOW!"
     logger.warning(message)
     await ctx.send(message)
     await ctx.bot.logout()
     settings.save()
Ejemplo n.º 18
0
 async def updateChannel(self, channel: discord.VoiceChannel):
     if type(channel) == int:
         channel = self.get_channel(channel)
         if not channel:  # Indicates the channel no longer exists, or we have no permissions
             return log.error("Channel no longer exists to join")
     else:  # If we aren't updating from string, change our saved string
         settings["voiceChannel"] = channel.id
         settingsModule.save()
     self.channel = channel
     if self.vc and self.vc.channel != channel:
         await self.vc.move_to(channel)
     else:
         await self.createVoiceClient()
Ejemplo n.º 19
0
    def save(self) -> None:
        """
    Saves the region of interest to disk

    The ensures that the region of interest persists across multiple executions. Additionally, it allows multiple
    pipelines to share the same region of interest for a given source.

    :return: void
    """

        new_settings = settings.config_dict()
        new_settings[self._pipeline.source] = copy.deepcopy(self._roi)
        settings.save(settings.SettingsCategories.INPUT,
                      settings.InputSettings.ROI, new_settings)
Ejemplo n.º 20
0
 async def load(self, ctx, extension_name: str):
     """Enable the use of an extension.
     
     Only the bot owner can use this."""
     ctx.bot.load_extension(extension_name)
     settings.manager.setdefault("EXTENSIONS", settings.DEFAULT_EXTENSIONS)
     if extension_name not in settings.manager["EXTENSIONS"]:
         settings.manager["EXTENSIONS"].append(extension_name)
         message = f"Extension {extension_name} loaded."
     else:
         message = f"Extension {extension_name} is already loaded. :<"
     await ctx.send(message)
     logger.info(message)
     settings.save()
Ejemplo n.º 21
0
def on_closing():

    if (settings.my_thread is not None):
        print("we stop thread stream")
        settings.is_streaming = False
        settings.my_thread.join()

    if (settings.key_thread is not None):
        settings.is_keylisten = False
        settings.key_thread.join()

    settings.save()

    root.destroy()
Ejemplo n.º 22
0
    def test_save_settings(self):
        with fake_settings(settings1) as (mod_settings, settings):
            settings.conf_file = CONFIG_DIR + '/new.conf'
            settings['default_duration'] = 35
            settings['verify_ssl'] = True
            settings.save()

        with open(CONFIG_DIR + '/new.conf') as f:
            saved = f.read()
            with fake_settings(saved) as (mod_settings, settings):
                # changes saved?
                self.assertEqual(settings['default_duration'], '35')
                self.assertEqual(settings['verify_ssl'], True)
                # no out of thin air changes?
                self.assertEqual(settings['audio_output'], 'hdmi')
Ejemplo n.º 23
0
 def savesettings(self):
     #Saves the settings in a file using the save function to settings.py
     self.savelocal()
     
     settings.playercolors = self.playercolors
     settings.graphics = self.graphics
     settings.keybinds = self.keybinds
     settings.sound = self.sound
     settings.game = self.game
     
     settings.save()
     
     tkmb.showinfo("Save", "Restarting menu to save settings.")
     self.running = False
     self.menu.destroy()
Ejemplo n.º 24
0
    def test_save_settings(self):
        with fake_settings(settings1) as (mod_settings, settings):
            settings.conf_file = CONFIG_DIR + '/new.conf'
            settings['default_duration'] = 35
            settings['verify_ssl'] = True
            settings.save()

        with open(CONFIG_DIR + '/new.conf') as f:
            saved = f.read()
            with fake_settings(saved) as (mod_settings, settings):
                # changes saved?
                self.assertEqual(settings['default_duration'], '35')
                self.assertEqual(settings['verify_ssl'], True)
                # no out of thin air changes?
                self.assertEqual(settings['audio_output'], 'hdmi')
Ejemplo n.º 25
0
def segment(settings_file):

    version = '2016-7-12'

    print "Loading settings from %s..." % settings_file
    runs = settings.parse(settings_file)

    for i, run in enumerate(runs):

        print('Segment - running configuration %d of %d from %s'
              % (i+1, len(runs), settings_file))

        # Get list of images in directory
        image_list = images.list_files(run['directory'], run['input_ext'])

        # Set up additonal run parameters
        run['image_file_label'] = 'th=%05.4f_size=%04.0fu-%04.0fu' % (run['threshold'],
                                                                      run['minimum_size'],
                                                                      run['maximum_size'])

        run['image_label'] = contruct_image_label(run, version)

        if not os.path.exists(run['full_output']):
            os.makedirs(run['full_output'])

        top_image_filename = image_list[-1]
        objects, _ = setup_object_boxes(top_image_filename, run)

        if run['mode'] == 'final':

            # sanity check to avoid creating unnecessary file
            if len(objects) > 10000:
                sys.exit('Over 10,000 objects are identified in the image, are you sure you want to continue?')

            print('Saving Settings into %s' % run['full_output'])
            settings.save(run.copy())

            # last plane in some image samples is not a true focus plane
            if run['skip_last_plane']:
                final_list = image_list[:-1]
            else:
                final_list = image_list

            # Loop over the planes we're interested in, load an image, then process it
            for plane_num, plane_image_filename in enumerate(final_list):

                final(plane_image_filename, objects, run, plane_num)
Ejemplo n.º 26
0
def main():
    settings.load()
    midi.setupMidiPorts()
    octatrack_pages.setup()
    setupLaunchpad()
    triggerOctatackMidiDump()
    gotoSavedSelectedPage()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        pass
    finally:
        print('\n')
        print('save settings . . .')
        settings.save()
        print('exit.')
Ejemplo n.º 27
0
	def start_up(self):
		# TODO: Remove in beta
		level = 4
		def normalize_first_time():
			settings.set(level, 'Application', 'first time level')
			settings.save()

		def done(status=True):
			gallerydb.DatabaseEmitter.RUN = True
			if gui_constants.FIRST_TIME_LEVEL != level:
				normalize_first_time()
			if gui_constants.ENABLE_MONITOR and\
				gui_constants.MONITOR_PATHS and all(gui_constants.MONITOR_PATHS):
				self.init_watchers()
				if gui_constants.LOOK_NEW_GALLERY_STARTUP:
					if self.manga_list_view.gallery_model.db_emitter.count == gui_constants.GALLERY_DATA:
						self.scan_for_new_galleries()
					else:
						self.manga_list_view.gallery_model.db_emitter.DONE.connect(self.scan_for_new_galleries)
			self.download_manager = pewnet.Downloader()
			gui_constants.DOWNLOAD_MANAGER = self.download_manager
			self.download_manager.start_manager(4)

		if gui_constants.FIRST_TIME_LEVEL < 3:
			log_i('Invoking first time level {}'.format(level))
			app_widget = misc.ApplicationPopup(self)
			self.admin_db = gallerydb.AdminDB()
			self.admin_db.moveToThread(gui_constants.GENERAL_THREAD)
			self.admin_db.DONE.connect(done)
			self.admin_db.DONE.connect(self.admin_db.deleteLater)
			self.admin_db.DATA_COUNT.connect(app_widget.prog.setMaximum)
			self.admin_db.PROGRESS.connect(app_widget.prog.setValue)
			self.admin_db_method_invoker.connect(self.admin_db.rebuild_galleries)
			self.admin_db_method_invoker.connect(app_widget.show)
			app_widget.adjustSize()
			self.admin_db_method_invoker.emit()
		elif gui_constants.FIRST_TIME_LEVEL < 4:
			log_i('Invoking first time level {}'.format(level))
			settings.set([], 'Application', 'monitor paths')
			settings.set([], 'Application', 'ignore paths')
			gui_constants.MONITOR_PATHS = []
			gui_constants.IGNORE_PATHS = []
			settings.save()
			done()
		else:
			done()
Ejemplo n.º 28
0
 async def uload(self, ctx, extension_name: str):
     """Disable the use of an extension.
     
     Only the bot owner can use this."""
     prompt = await helpers.yes_no(ctx, ctx.bot)
     if not prompt:
         return
     ctx.bot.unload_extension(extension_name)
     settings.manager.setdefault("EXTENSIONS", settings.DEFAULT_EXTENSIONS)
     try:
         settings.manager["EXTENSIONS"].remove(extension_name)
     except ValueError:
         message = f"Extension {extension_name} is already unloaded. :<"
     else:
         message = f"Extension {extension_name} unloaded."
     await ctx.send(message)
     logger.info(message)
     settings.save()
Ejemplo n.º 29
0
def main(args):
    if args.mobileclient:
        from gmusicapi import Mobileclient
        api = Mobileclient(debug_logging=True)
        settings['google']['mobileclient'] = api.perform_oauth(
            open_browser=True).to_json()
    elif args.musicmanager:
        from gmusicapi import Musicmanager
        api = Musicmanager(debug_logging=True)
        settings['google']['musicmanager'] = api.perform_oauth(
            open_browser=True).to_json()
    elif args.youtube:
        from ytmusicapi import YTMusic
        api = YTMusic()
        settings['youtube']['headers'] = api.setup() if (
            args.headers_raw is None) else api.setup(
                headers_raw=args.headers_raw)
    settings.save()
Ejemplo n.º 30
0
 async def rload(self, ctx, extension_name: str):
     """Reload an already-loaded extension.
     
     Only the bot owner can use this."""
     settings.manager.setdefault("EXTENSIONS", settings.DEFAULT_EXTENSIONS)
     if extension_name in settings.manager["EXTENSIONS"]:
         ctx.bot.unload_extension(extension_name)
         try:
             ctx.bot.load_extension(extension_name)
         except Exception as error:
             message = f"An error occurred while trying to reload {extension_name}! x.x"
             exception = traceback.format_exc()
             logger.warning(exception)
         else:
             message = f"Extension {extension_name} reloaded."
     else:
         message = f"Extension {extension_name} not currently loaded; please load it. :<"
     await ctx.send(message)
     logger.info(message)
     settings.save()
Ejemplo n.º 31
0
import sys
import settings

if __name__ == "__main__":
    if sys.argv[1] == "youtube":
        from ytmusicapi import YTMusic
        api = YTMusic()
        settings['youtube']['headers'] = api.setup()
    settings.save()
Ejemplo n.º 32
0
	# cleanup and shutdown code
	logging.getLogger().info("Shutting Down. Signalling other worker threads.")
	for thread in threading.enumerate():
		if thread == threading.current_thread():
			continue
		else:
			try:
				logging.getLogger().info("Canceling thread %s." % thread.getName())
				thread.cancel()
			except AttributeError, e:
				#logging.getLogger().info("%s respone: %s" % (thread.getName(), str(e)))
				pass

	cherrypy.engine.exit()

	settings.save('settings.ini')

def start_article_download():

	for thread in threading.enumerate():
		if thread is ArticleWorker and thread.isAlive() or thread is ArticleProducer and thread.isAlive():
			logging.getLogger().info("ArticleProducer/Worker still running. Won't start another.")
			return

	producer = ArticleProducer()
	producer.start()

	worker = ArticleWorker(producer)
	worker.start()

def main():
Ejemplo n.º 33
0
 def change_setting(v):
     settings.set(k, v)
     settings.save()
Ejemplo n.º 34
0
		def set_search_strict(b):
			app_constants.GALLERY_SEARCH_STRICT = b
			settings.set(b, 'Application', 'gallery search strict')
			settings.save()
Ejemplo n.º 35
0
Archivo: db.py Proyecto: Sandy4321/tmv
def init():
    stats = RunStats(start=datetime.datetime.now(), batch_count=0, last_update=datetime.datetime.now())
    stats.save()
    
    settings = Settings(doc_topic_score_threshold=1, doc_topic_scaled_score=True)
    settings.save()
Ejemplo n.º 36
0
def think(dt, events, kpress, mpos):

	global alpha, playing, ending, lastsave
	if playing and not ending:
		alpha = min(2 * dt + alpha, 1)
	elif ending:
		alpha -= 2 * dt
		if alpha <= -6:
			hud.endtitle.settext()
			if not hud.endtitle:
				state.removesave()
				scene.pop()
				return
	else:
		alpha -= 2 * dt
		if alpha <= 0:
			scene.pop()
			return
	sound.setvolume(alpha)

	lastsave += dt
	if settings.savetime is not None and lastsave > settings.savetime:
		lastsave = 0
		state.save()

	if kpress[K_ESCAPE]:
		state.save()
		scene.pop()
		scene.pop()
		playing = False

	dx = ((kpress[K_RIGHT]) - (kpress[K_LEFT])) * dt
	dy = ((kpress[K_UP]) - (kpress[K_DOWN])) * dt
	dr = ((kpress[K_e] or kpress[K_d]) - (kpress[K_a])) * dt
	dA = ((kpress[K_COMMA] or kpress[K_w]) - (kpress[K_o] or kpress[K_s])) * dt

	for event in events:
		if event.type == QUIT:
			state.save()
			scene.pop()
			scene.pop()
			playing = False
		if event.type == MOUSEBUTTONDOWN:
			if event.button == 4:
				camera.zoom /= 1.08
			elif event.button == 5:
				camera.zoom *= 1.08
			else:
				px, py = mpos
				if hud.click((px, settings.sy - py)):
					continue
				p = camera.screentoworld((settings.sx - px, settings.sy - py))
				if p and cursor.tobuild:
					phat = p.norm()
					if state.canbuild(cursor.tobuild, phat) and not state.builderror(cursor.tobuild):
						f = camera.eye().rej(phat).norm()
						state.build(cursor.tobuild(p.norm(), f))
						cursor.tobuild = None
					else:
						sound.play("error")
				elif cursor.pointingto:
					if cursor.unbuild:
						state.unbuild(cursor.pointingto)
					elif cursor.disable:
						state.toggleenable(cursor.pointingto)
				else:
					cursor.dragging = True
		if event.type == MOUSEBUTTONUP:
			cursor.dragging = False
		if event.type == MOUSEMOTION:
			relx, rely = event.rel
			if event.buttons[0]:
				dx -= relx * settings.dragfactor / settings.sy
				dy += rely * settings.dragfactor / settings.sy
			if event.buttons[2]:
				dr -= relx * settings.dragfactor / settings.sy
				dA += rely * settings.dragfactor / settings.sy
#			camera.seek((0, 0, 1))
		if event.type == KEYDOWN and event.key == K_CAPSLOCK:
			settings.swaparrows = not settings.swaparrows
		if event.type == KEYDOWN and event.key == K_F3 and settings.unlocked >= 99:
			if settings.level == 3:
				scene.pushunder(scenes.final)
			ending = True
			hud.endtitle.settext("Mission Complete")
		if event.type == KEYDOWN and event.key == K_F12:
			graphics.screenshot()
		if event.type == KEYDOWN and event.key == K_INSERT:
			camera.zoom /= 1.2
		if event.type == KEYDOWN and event.key == K_DELETE:
			camera.zoom *= 1.2
		if event.type == KEYDOWN and event.key == K_SPACE:
			things.Asteroid(100)

	camera.zoom = min(max(camera.zoom, 30), 200)


	if bool(kpress[K_LSHIFT]) != bool(settings.swaparrows):
		dx, dy, dr, dA = dr, dA, dx, dy
	
	camera.move(40. * dx / state.R, 40. * dy / state.R, 2.5 * dr, 0.7 * dA)
	camera.think(dt)
			

	px, py = mpos
	hud.point((px, settings.sy - py))

	dtobj = dt * settings.speedup

	for obj in state.thinkers():
		obj.think(dtobj)

	hud.think(dt)
	state.think(dtobj)
	
	hud.setstatus()

	if not ending:
		if state.checklose():
			ending = True
			hud.endtitle.settext("Mission Failed")
		elif state.checkwin(dt):
			if settings.level == 3:
				scene.pushunder(scenes.final)
			sound.play("success")
			ending = True
			hud.endtitle.settext("Mission Complete")
			settings.unlocked = max(settings.unlocked, settings.level + 1)
			settings.save()
Ejemplo n.º 37
0
def _save_subs_prefs(subs):
  if 'lang' in subs:
    settings.save('subtitles', {'lang':subs['lang']})
Ejemplo n.º 38
0
 def change_setting():
     settings.set(k, v)
     settings.save()
     l.show = True
Ejemplo n.º 39
0
 def destroy(self):
     settings.set('view_window_geometry', super().geometry())
     settings.save()
     super().destroy()
Ejemplo n.º 40
0
def saveAndQuit():
	settings.save()
	root.destroy()
Ejemplo n.º 41
0
            logger.info(f'Generation: {t}; fitness: {best_fitness}')
            if best_fitness >= lowest_fitness:
                stale_generations_count += 1
                logger.debug(
                    f'It is a stale generation repeated {stale_generations_count} time'
                )
            else:
                logger.debug(
                    f"Best generation ever. Chromosome {best_chromosome} with fitness {best_fitness}"
                )
                logger.info(f"Generation: {t}; fitness: {best_fitness}. Best.")
                stale_generations_count = 0
                lowest_fitness = best_fitness
                winner_chromosome = best_chromosome

            populations.append(temporary_population)
            t += 1
            logger.debug("Going to the next generation")
            progress_bar.update()
            progress_bar.set_description(f"{lowest_fitness:9.2f}")
    except Exception as e:
        print(e)
    finally:
        plot(populations)
        # SAVE
        # save(populations, 'populations')
        save(winner_chromosome, 'winner_chromosome')
        save(lowest_fitness, 'lowest_fitness')
        save(settings, 'settings')
        increment_runid()
Ejemplo n.º 42
0
	def accept(self):
		set = settings.set

		# App / General / Gallery
		app_constants.SUBFOLDER_AS_GALLERY = self.subfolder_as_chapters.isChecked()
		set(app_constants.SUBFOLDER_AS_GALLERY, 'Application', 'subfolder as gallery')
		app_constants.EXTRACT_CHAPTER_BEFORE_OPENING = self.extract_gallery_before_opening.isChecked()
		set(app_constants.EXTRACT_CHAPTER_BEFORE_OPENING, 'Application', 'extract chapter before opening')
		app_constants.OPEN_GALLERIES_SEQUENTIALLY = self.open_galleries_sequentially.isChecked()
		set(app_constants.OPEN_GALLERIES_SEQUENTIALLY, 'Application', 'open galleries sequentially')
		app_constants.SCROLL_TO_NEW_GALLERIES = self.scroll_to_new_gallery.isChecked()
		set(app_constants.SCROLL_TO_NEW_GALLERIES, 'Application', 'scroll to new galleries')
		app_constants.MOVE_IMPORTED_GALLERIES = self.move_imported_gs.isChecked()
		set(app_constants.MOVE_IMPORTED_GALLERIES, 'Application', 'move imported galleries')
		if not self.move_imported_def_path.text() or os.path.exists(self.move_imported_def_path.text()):
			app_constants.IMPORTED_GALLERY_DEF_PATH = self.move_imported_def_path.text()
			set(app_constants.IMPORTED_GALLERY_DEF_PATH, 'Application', 'imported gallery def path')
		app_constants.OPEN_RANDOM_GALLERY_CHAPTERS = self.open_random_g_chapters.isChecked()
		set(app_constants.OPEN_RANDOM_GALLERY_CHAPTERS, 'Application', 'open random gallery chapters')
		app_constants.RENAME_GALLERY_SOURCE = self.rename_g_source_group.isChecked()
		set(app_constants.RENAME_GALLERY_SOURCE, 'Application', 'rename gallery source')
		app_constants.unrar_tool_path = self.path_to_unrar.text()
		set(app_constants.unrar_tool_path, 'Application', 'unrar tool path')
		# App / General / Search
		app_constants.ALLOW_SEARCH_REGEX = self.search_allow_regex.isChecked()
		set(app_constants.ALLOW_SEARCH_REGEX, 'Application', 'allow search regex')
		app_constants.SEARCH_AUTOCOMPLETE = self.search_autocomplete.isChecked()
		set(app_constants.SEARCH_AUTOCOMPLETE, 'Application', 'search autocomplete')
		if self.search_on_enter.isChecked():
			app_constants.SEARCH_ON_ENTER = True
		else:
			app_constants.SEARCH_ON_ENTER = False
		set(app_constants.SEARCH_ON_ENTER, 'Application', 'search on enter')
		# App / General / External Viewer
		if not self.external_viewer_path.text():
			app_constants.USE_EXTERNAL_VIEWER = False
			set(False, 'Application', 'use external viewer')
		else:
			app_constants.USE_EXTERNAL_VIEWER = True
			set(True, 'Application', 'use external viewer')
			app_constants._REFRESH_EXTERNAL_VIEWER = True
		app_constants.EXTERNAL_VIEWER_PATH = self.external_viewer_path.text()
		set(app_constants.EXTERNAL_VIEWER_PATH,'Application', 'external viewer path')
		# App / Monitor / misc
		app_constants.ENABLE_MONITOR = self.enable_monitor.isChecked()
		set(app_constants.ENABLE_MONITOR, 'Application', 'enable monitor')
		app_constants.LOOK_NEW_GALLERY_STARTUP = self.look_new_gallery_startup.isChecked()
		set(app_constants.LOOK_NEW_GALLERY_STARTUP, 'Application', 'look new gallery startup')
		app_constants.LOOK_NEW_GALLERY_AUTOADD = self.auto_add_new_galleries.isChecked()
		set(app_constants.LOOK_NEW_GALLERY_AUTOADD, 'Application', 'look new gallery autoadd')
		# App / Monitor / folders
		paths = []
		folder_p_widgets = self.take_all_layout_widgets(self.folders_layout)
		for x, l_edit in enumerate(folder_p_widgets):
			p = l_edit.text()
			if p:
				paths.append(p)

		set(paths, 'Application', 'monitor paths')
		app_constants.MONITOR_PATHS = paths
		# App / Monitor / ignore list
		paths = []
		ignore_p_widgets = self.take_all_layout_widgets(self.ignore_path_l)
		for x, l_edit in enumerate(ignore_p_widgets):
			p = l_edit.text()
			if p:
				paths.append(p)
		set(paths, 'Application', 'ignore paths')
		app_constants.IGNORE_PATHS = paths

		# Web / Downloader

		if self.archive_download.isChecked():
			app_constants.HEN_DOWNLOAD_TYPE = 0
		else:
			app_constants.HEN_DOWNLOAD_TYPE = 1
		set(app_constants.HEN_DOWNLOAD_TYPE, 'Web', 'hen download type')

		app_constants.DOWNLOAD_DIRECTORY = self.download_directory.text()
		set(app_constants.DOWNLOAD_DIRECTORY, 'Web', 'download directory')

		app_constants.TORRENT_CLIENT = self.torrent_client.text()
		set(app_constants.TORRENT_CLIENT, 'Web', 'torrent client')

		# Web / Metdata
		if self.default_ehen_url.isChecked():
			app_constants.DEFAULT_EHEN_URL = 'http://g.e-hentai.org/'
		else:
			app_constants.DEFAULT_EHEN_URL = 'http://exhentai.org/'
		set(app_constants.DEFAULT_EHEN_URL, 'Web', 'default ehen url')

		app_constants.REPLACE_METADATA = self.replace_metadata.isChecked()
		set(app_constants.REPLACE_METADATA, 'Web', 'replace metadata')

		app_constants.ALWAYS_CHOOSE_FIRST_HIT = self.always_first_hit.isChecked()
		set(app_constants.ALWAYS_CHOOSE_FIRST_HIT, 'Web', 'always choose first hit')

		app_constants.GLOBAL_EHEN_TIME = self.web_time_offset.value()
		set(app_constants.GLOBAL_EHEN_TIME, 'Web', 'global ehen time offset')

		app_constants.CONTINUE_AUTO_METADATA_FETCHER = self.continue_a_metadata_fetcher.isChecked()
		set(app_constants.CONTINUE_AUTO_METADATA_FETCHER, 'Web', 'continue auto metadata fetcher')

		app_constants.USE_JPN_TITLE = self.use_jpn_title.isChecked()
		set(app_constants.USE_JPN_TITLE, 'Web', 'use jpn title')

		app_constants.USE_GALLERY_LINK = self.use_gallery_link.isChecked()
		set(app_constants.USE_GALLERY_LINK, 'Web', 'use gallery link')

		# Web / ExHentai
		self.exprops.ipb_id = self.ipbid_edit.text()
		self.exprops.ipb_pass = self.ipbpass_edit.text()

		# Visual / Grid View / Tooltip
		app_constants.GRID_TOOLTIP = self.grid_tooltip_group.isChecked()
		set(app_constants.GRID_TOOLTIP, 'Visual', 'grid tooltip')
		app_constants.TOOLTIP_TITLE = self.visual_grid_tooltip_title.isChecked()
		set(app_constants.TOOLTIP_TITLE, 'Visual', 'tooltip title')
		app_constants.TOOLTIP_AUTHOR = self.visual_grid_tooltip_author.isChecked()
		set(app_constants.TOOLTIP_AUTHOR, 'Visual', 'tooltip author')
		app_constants.TOOLTIP_CHAPTERS = self.visual_grid_tooltip_chapters.isChecked()
		set(app_constants.TOOLTIP_CHAPTERS, 'Visual', 'tooltip chapters')
		app_constants.TOOLTIP_STATUS = self.visual_grid_tooltip_status.isChecked()
		set(app_constants.TOOLTIP_STATUS, 'Visual', 'tooltip status')
		app_constants.TOOLTIP_TYPE = self.visual_grid_tooltip_type.isChecked()
		set(app_constants.TOOLTIP_TYPE, 'Visual', 'tooltip type')
		app_constants.TOOLTIP_LANG = self.visual_grid_tooltip_lang.isChecked()
		set(app_constants.TOOLTIP_LANG, 'Visual', 'tooltip lang')
		app_constants.TOOLTIP_DESCR = self.visual_grid_tooltip_descr.isChecked()
		set(app_constants.TOOLTIP_DESCR, 'Visual', 'tooltip descr')
		app_constants.TOOLTIP_TAGS = self.visual_grid_tooltip_tags.isChecked()
		set(app_constants.TOOLTIP_TAGS, 'Visual', 'tooltip tags')
		app_constants.TOOLTIP_LAST_READ = self.visual_grid_tooltip_last_read.isChecked()
		set(app_constants.TOOLTIP_LAST_READ, 'Visual', 'tooltip last read')
		app_constants.TOOLTIP_TIMES_READ = self.visual_grid_tooltip_times_read.isChecked()
		set(app_constants.TOOLTIP_TIMES_READ, 'Visual', 'tooltip times read')
		app_constants.TOOLTIP_PUB_DATE = self.visual_grid_tooltip_pub_date.isChecked()
		set(app_constants.TOOLTIP_PUB_DATE, 'Visual', 'tooltip pub date')
		app_constants.TOOLTIP_DATE_ADDED = self.visual_grid_tooltip_date_added.isChecked()
		set(app_constants.TOOLTIP_DATE_ADDED, 'Visual', 'tooltip date added')
		# Visual / Grid View / Gallery
		app_constants.USE_EXTERNAL_PROG_ICO = self.external_viewer_ico.isChecked()
		set(app_constants.USE_EXTERNAL_PROG_ICO, 'Visual', 'use external prog ico')
		app_constants.DISPLAY_GALLERY_TYPE = self.gallery_type_ico.isChecked()
		set(app_constants.DISPLAY_GALLERY_TYPE, 'Visual', 'display gallery type')
		if self.gallery_text_elide.isChecked():
			app_constants.GALLERY_FONT_ELIDE = True
		else:
			app_constants.GALLERY_FONT_ELIDE = False
		set(app_constants.GALLERY_FONT_ELIDE, 'Visual', 'gallery font elide')
		app_constants.GALLERY_FONT = (self.font_lbl.text(), self.font_size_lbl.value())
		set(app_constants.GALLERY_FONT[0], 'Visual', 'gallery font family')
		set(app_constants.GALLERY_FONT[1], 'Visual', 'gallery font size')
		# Visual / Grid View / Colors
		if self.color_checker(self.grid_title_color.text()):
			app_constants.GRID_VIEW_TITLE_COLOR = self.grid_title_color.text()
			set(app_constants.GRID_VIEW_TITLE_COLOR, 'Visual', 'grid view title color')
		if self.color_checker(self.grid_artist_color.text()):
			app_constants.GRID_VIEW_ARTIST_COLOR = self.grid_artist_color.text()
			set(app_constants.GRID_VIEW_ARTIST_COLOR, 'Visual', 'grid view artist color')
		if self.color_checker(self.grid_label_color.text()):
			app_constants.GRID_VIEW_LABEL_COLOR = self.grid_label_color.text()
			set(app_constants.GRID_VIEW_LABEL_COLOR, 'Visual', 'grid view label color')

		# Advanced / Misc
		# Advanced / Misc / Grid View
		app_constants.SCROLL_SPEED = self.scroll_speed
		set(self.scroll_speed, 'Advanced', 'scroll speed')
		self.scroll_speed_changed.emit()
		app_constants.THUMBNAIL_CACHE_SIZE = self.cache_size
		set(self.cache_size[1], 'Advanced', 'cache size')
		QPixmapCache.setCacheLimit(self.cache_size[0]*
							 self.cache_size[1])


		# Advanced / General / Gallery Text Fixer
		app_constants.GALLERY_DATA_FIX_REGEX = self.g_data_regex_fix_edit.text()
		set(app_constants.GALLERY_DATA_FIX_REGEX, 'Advanced', 'gallery data fix regex')
		app_constants.GALLERY_DATA_FIX_TITLE = self.g_data_fixer_title.isChecked()
		set(app_constants.GALLERY_DATA_FIX_TITLE, 'Advanced', 'gallery data fix title')
		app_constants.GALLERY_DATA_FIX_ARTIST = self.g_data_fixer_artist.isChecked()
		set(app_constants.GALLERY_DATA_FIX_ARTIST, 'Advanced', 'gallery data fix artist')
		app_constants.GALLERY_DATA_FIX_REPLACE = self.g_data_replace_fix_edit.text()
		set(app_constants.GALLERY_DATA_FIX_REPLACE, 'Advanced', 'gallery data fix replace')

		# About / DB Overview
		app_constants.TAGS_TREEVIEW_ON_START = self.tags_treeview_on_start.isChecked()
		set(app_constants.TAGS_TREEVIEW_ON_START, 'Application', 'tags treeview on start')

		settings.save()
		self.close()
Ejemplo n.º 43
0
 def _save_config(self):
   settings.save("channels", self.settings)
Ejemplo n.º 44
0
		def normalize_first_time():
			settings.set(level, 'Application', 'first time level')
			settings.save()
Ejemplo n.º 45
0
def clickon(bname):
	soundname = buttons[bname].soundname
	if bname == "buildw":
		if mode == "main":
			buildwmode()
		elif mode == "buildw":
			soundname = "back"
			mainmode()
	elif bname == "buildb":
		if mode == "main":
			buildbmode()
		elif mode == "buildb":
			soundname = "back"
			mainmode()
	elif bname == "buildr":
		if mode == "main":
			buildrmode()
		elif mode == "buildr":
			soundname = "back"
			mainmode()
	elif bname.startswith("build"):
		cursor.tobuild = buttons[bname].btype
	if bname == "launch":
		if mode == "main":
			launchmode()
		elif mode == "launch":
			soundname = "back"
			mainmode()
	elif bname.startswith("launch"):
		if state.launcherror(buttons[bname].ltype):
			soundname = "error"
		else:
			state.launch(buttons[bname].ltype)
			soundname = "launch"

	if bname == "help":
		if mode == "main":
			soundname = "back"
			helpmode()
		elif mode == "help":
			mainmode()
	elif bname == "helpmission":
		labels["helppage"].settext(info.missionhelp[settings.level])
	elif bname.startswith("help"):
		labels["helppage"].settext(info.help[buttons[bname].helpname])

	if bname == "unbuild":
		if mode == "main":
			unbuildmode()
		elif mode == "unbuild":
			soundname = "back"
			mainmode()

	if bname == "unlaunch":
		if mode == "main":
			unlaunchmode()
		elif mode == "unlaunch":
			soundname = "back"
			mainmode()
	elif bname.startswith("unlaunch"):
		state.unlaunch(buttons[bname].ltype)

	if bname == "disable":
		if mode == "main":
			disablemode()
		elif mode == "disable":
			soundname = "back"
			mainmode()

	if bname == "back":
		soundname = "back"
		cursor.tobuild = None
		mainmode()
	
	if bname == "bcancel":
		soundname = "back"
		cursor.tobuild = None

	if bname == "quit":
		soundname = "back"
		quitmode()

	if bname == "abandonquit":
		soundname = "back"
		state.removesave()
		scene.top().playing = False

	if bname == "savequit":
		soundname = "back"
		state.save()
		scene.pop()
		scene.pop()

	if bname == "quitgame":
		scene.top().playing = False


	if bname.startswith("level"):
		scene.top().playing = False
		scene.top().selected = buttons[bname].n

	if bname == "selectlevel":
		if mode == "level":
			soundname = "back"
			menumode()
		else:
			levelmode()
	if bname == "options":
		if mode == "options":
			soundname = "back"
			menumode()
		else:
			optionsmode()
	if bname == "credits":
		if mode == "credits":
			soundname = "back"
			menumode()
		else:
			creditsmode()

	if bname == "soundtoggle":
		settings.sound = not settings.sound
		settings.save()
		sound.setvolume()
	if bname == "musictoggle":
		settings.music = not settings.music
		settings.save()
		sound.setvolume()
	if bname == "fullscreentoggle":
		settings.fullscreen = not settings.fullscreen
		settings.save()
	if bname == "wsizesmall":
		settings.wsize = 640, 360
		settings.save()
	if bname == "wsizemedium":
		settings.wsize = 854, 480
		settings.save()
	if bname == "wsizelarge":
		settings.wsize = 1280, 720
		settings.save()
	if bname == "wsizevlarge":
		settings.wsize = 1920, 1080
		settings.save()
	if mode == "options":
		buttons["soundtoggle"].words = "SOUND: %s" % ("ON" if settings.sound else "OFF")
		buttons["musictoggle"].words = "MUSIC: %s" % ("ON" if settings.music else "OFF")
		buttons["fullscreentoggle"].words = "FULLSCREEN: %s" % ("ON" if settings.fullscreen else "OFF")
		for sname in "small medium large vlarge".split():
			b = buttons["wsize" + sname]
			size = map(int, b.words.split()[-1].split("x"))
			b.color = (180, 255, 180) if tuple(size) == tuple(settings.wsize) else (180, 180, 180)

	sound.play(soundname)
Ejemplo n.º 46
0
def _save_subs_prefs(subs):
    if 'lang' in subs:
        settings.save('subtitles', {'lang': subs['lang']})
Ejemplo n.º 47
0
		def set_search_case(b):
			app_constants.GALLERY_SEARCH_CASE = b
			settings.set(b, 'Application', 'gallery search case')
			settings.save()