Beispiel #1
0
def settings():
    if request.method == 'POST':
        setting = request.form.get('setting')
        value = request.form.get('value_0')
        # strip whitespaces
        value = value.replace(' ', '')
        if not setting or not value:
            abort(400)
        
        if setting not in config.options():
            abort(400)

        config.set(setting, value)
        return redirect(url_for('admin_settings'))

    # load settings
    setting_list = [
        'facebook_integration', 'facebook_app_id', 'facebook_app_secret',
        'feedback_address', 'imprint_uri', 'account_activation',
        'posts_per_page', 'templates', 'default_template', 'debug',
        'setup', 'file_extensions', 'max_file_size', 'registration',
        'posts_per_page_options', 'upload_destination'
    ]
    settings = {}
    for setting in setting_list:
        settings[setting] = config.get(setting)

    return render_template('admin/settings.html', settings=settings)
Beispiel #2
0
def get_config_str(section='', options='', config=None):
    if section != '':
        try:
            size_s = int(section)
        except ValueError as e:
            section = section
        else:
            if config != None and size_s >= 0 and size_s < len(config):
                section = config.sections()[size_s]
            else:
                section = section
    else:
        raise ValueError('错误使用')
    if options != '':
        try:
            size_o = int(options)
        except ValueError as e:
            options = options
        else:
            if config.has_section(section) and size_o >= 0 and size_o < len(
                    config[section]):
                options = config.options(section)[size_o]
            else:
                options = options
    return [section, options]
Beispiel #3
0
def pre_render_template(name):
    """ Replace config strings in the template and return the result. """
    template = psblog.readfile(name)
    for opt, val in config.options().items():
        if type(val) is not str:
            val = str(val)
        template = template.replace("%%%"+opt+"%%%", val)
    return template
 def __init__(self, simu, testNo, ch_number) :
     threading.Thread.__init__(self)
     self.__simu = simu
     self.__testNo = int(float(testNo))
     self.__saveTestNo = self.__testNo
     self.__ch_number = ch_number
     now = datetime.datetime.now()
     report_name = str("CH" + str(int(float(self.__ch_number))) + "_" + self.__testName[self.__testNo]) + "_" + str( now.strftime("%Y_%m_%d_%H_%M") )
     report_full_path = os.path.abspath(os.path.join(config.options().output_current_dir, report_name) )
     self.__testTools = TestTools(self, self.__simu, self.__testNo, self.__ch_number, report_full_path)
     self.__testTools.writeReport(" ", now, self.__testName[self.__testNo])
Beispiel #5
0
def set_configuration_file(configuration_file):
    """Set configuration file and reset all configuration options.

    Arguments:

      configuration_file -- name of the configuration file, basestring, or
        'None' (in which case nothing happens)

    """
    import config
    if configuration_file is not None:
        for o in config.options():
            o.reset()
        config.config_file = configuration_file
        config.read_configuration_file(configuration_file)
Beispiel #6
0
def main():
    options = config.options()

    artificial_inst = lambda filenames: artificialdata.rsa_dataset(
        nrow=options.mat_size,
        ncol=options.mat_size,
        allow_ambiguities=options.ambiguities)
    instance_function = (
        artificial_inst if options.artificial else
        (lambda filenames: inst.get_generation_instances(
            filenames, options.max_gen_length))
        if options.generation else inst.get_plural_instances
        if 'plural' in options.data_dir else inst.get_singular_instances)

    evaluate(options, instance_function=instance_function)
Beispiel #7
0
def set_configuration_file(configuration_file):
    """Set configuration file and reset all configuration options.

    Arguments:

      configuration_file -- name of the configuration file, basestring, or
        'None' (in which case nothing happens)

    """
    import config
    if configuration_file is not None:
        for o in config.options():
            o.reset()
        config.config_file = configuration_file
        config.read_configuration_file(configuration_file)
Beispiel #8
0
def main():
    options = config.options()

    instance_function = (inst.get_generation_instances if options.generation
                         else inst.get_plural_instances if 'plural'
                         in options.data_dir else inst.get_singular_instances)

    evaluate_all(dirnames=(options.data_dir, ),
                 features=(featurefunctions.phi(options.features), ),
                 instance_function=instance_function,
                 cv=options.cv,
                 random_splits=options.random_splits,
                 T=options.sgd_max_iters,
                 l2_coeff=options.l2_coeff,
                 eta=options.sgd_eta,
                 verbose=options.verbose,
                 typ='speaker' if options.generation else 'listener')
Beispiel #9
0
    def __init__(self, station_list=None):
        super().__init__("Radio Player Menu")
        if station_list is None:
            station_list = []

        for i in range(len(station_list)):
            if i < maxitems():  # The very first item is the exit option, so not "<=".
                self.add_menu_item(
                    MenuItem(
                        i,
                        "{:<30}".format(station_list[i]["name"][:30]) + " " +  # force 35 character fixed length
                        "{:<5}".format(station_list[i]["codec"][:5]) + " " +   # force 5 character fixed length
                        "{:<5}".format(station_list[i]["bitrate"][:5]) + " " +
                        station_list[i]["url"],
                        lambda url=station_list[i]["url"]: subprocess.run([player(), options(), url])
                    )
                )
            else:
                break
Beispiel #10
0
Datei: log.py Projekt: Gawen/ezpy
def init(level = None):
    LEVELS = {
        "debug": DEBUG, 
        "info": INFO, 
        "warning": WARNING,
        "critical": CRITICAL,
    }
    
    level = level if level is not None else LEVELS[config.get("log", "default", "INFO").lower()]
    
    basicConfig()
    getLogger().setLevel(level)

    # Set level loggers
    for logger in config.options("log"):
        if logger == "default":
            continue

        logger_level = config.get("log", logger, level)

        getLogger(logger).setLevel(LEVELS[logger_level.lower()])
Beispiel #11
0
def main():
    display_info = pygame.display.Info()
    config_options = config.options()
    entity_variables = entity.Variables(display_info)
    fullscreen_class = renderer.FullScreen(config_options, entity_variables)
    config_colors = config.colors()
    config_fonts = config.fonts(config_options)
    config_rects_game = config.rects_game(config_options)
    config_rects_mainMenu = config.rects_mainMenu(config_options, config_colors, config_fonts)
    config_rects_gameMenu = config.rects_gameMenu(config_options, config_colors, config_fonts)
    config_rects_worldGen_menu = config.rects_worldGen_menu(config_options)
    UIcontrolor_class = UIHandler.UIController()

    button_class = config.buttons()

    gameDisplay = pygame.display.set_mode((config_options.width, config_options.height), flags=pygame.NOFRAME, depth=0, display=config_options.display) #(size), flags, depth, display
    pygame.display.set_caption(config_options.screen_title)
    clock = pygame.time.Clock()

    while entity_variables.mainloop:
        #get event input from pygame
        entity_variables.events = pygame.event.get()

        #=======================================================================================================================================================================================#
        if config_options.displayer_choser == "MainMenu":

            #get if this is the first frame in temp_first_frame_of_new_menu
            entity_variables.temp_first_frame_of_new_menu = entity_variables.first_frame_of_new_menu
            entity_variables.first_frame_of_new_menu = False

            #event class
            event_class_mainMenu = eventHandler.events_dict(entity_variables, config_options, config_rects_mainMenu, button_class)

            #UI
            UIcontrolor_class.mainMenu(config_options, entity_variables)

            #render
            renderer.MainMenu(gameDisplay, config_rects_mainMenu, config_colors, config_options, config_fonts, entity_variables)

        #=======================================================================================================================================================================================#
        elif config_options.displayer_choser == "game":

            #get if this is the first frame in temp_first_frame_of_new_menu
            entity_variables.temp_first_frame_of_new_menu = entity_variables.first_frame_of_new_menu
            entity_variables.first_frame_of_new_menu = False

            #event class
            event_class_game = eventHandler.events_dict(entity_variables, config_options, config_rects_game, button_class)

            #UI
            UIcontrolor_class.game(config_options, entity_variables)

            if UIcontrolor_class.testPressed:
                print("start test button")

                worldGenerator_class = worldGenerator.World(config_options, entity_variables)
                print("does nothing right now")

                print("end test button")

            #playerController class
            playerController_class = playerController.movement(entity_variables, config_rects_game, config_options)

            #player animation class
            player_animation_chooser_class = sprintLoader.player_animation_chooser(playerController_class, entity_variables, config_options)
            config_rects_game.player_sprite = player_animation_chooser_class.player_sprite

            #render
            renderer.game(gameDisplay, config_rects_game, config_colors, config_options, config_fonts, entity_variables)

        #=======================================================================================================================================================================================#
        elif config_options.displayer_choser == "GameMenu":

            #get if this is the first frame in temp_first_frame_of_new_menu
            entity_variables.temp_first_frame_of_new_menu = entity_variables.first_frame_of_new_menu
            entity_variables.first_frame_of_new_menu = False

            #event class
            event_class_gameMenu = eventHandler.events_dict(entity_variables, config_options, config_rects_gameMenu, button_class)

            #UI
            UIcontrolor_class.gameMenu(config_options, entity_variables)

            #render
            renderer.GameMenu(gameDisplay, config_rects_gameMenu, config_colors, config_options, config_fonts, entity_variables)

        #=======================================================================================================================================================================================#
        else:
            print("config_options.displayer_choser type not supported -->" + str(config_options.displayer_choser) + "<-- types that are suported: game, MainMenu")


        entity_variables.deltatime = clock.tick(config_options.fps) #delta time is x milliseconds since the previous call
def main() :

    options = config.options()
    options.new_output_dir()
    
    # Create logger
    loggername = os.path.join(options.output_dir, "simulator.log")
    myLogger = Logger.Logger(loggername)
    
    print "\nLog file: %s\n" % (loggername)

    # Create simulator with logger
    sim = ATOOMSim("ATOOM",
          "ATOOM",
         myLogger)

    # SCOE Database
    myScoeDb = scoedb.ScoeDatabase.ScoeDatabase(options.bds_ocoe_path, myLogger, sim.GetTimeKeeper(), None)
    sim.AddService(myScoeDb)
    
    # thread management
    threadMngr = ThreadManager.GetGlobalThreadManager()
    thListener = ThreadListenerImpl()
    threadMngr.AddThreadListener(thListener)
#     print "K2 scheduler loop thread id: %d" % threadMngr.GetSchedLoopThreadId()
      
    # Call generated code for instance creation, wiring and overload
    ATOOM.InitSimulator(sim)
      
    # Models Instances 
    config_models.InitSimulator( sim, options )

    # Tracers & logs settings
    config_tracer_logger.SetTracers( sim, options )
    config_tracer_logger.SetLogs( sim, myLogger, options )
        
    # Check connections are ok
    sim.CheckConnections()
    
    # K2 Profiler
    sim.SetProfileFlag(options.profiler_enabled)

    # Init the models
    sim.InitializeInternal()
    
    sim.SetRealTimeOvertaking ( True )
    sim.SetRealTimeSpeedFactor(1.0, 10 * MILLIS)
        
    # Enable Monitoring
    sim.CallActivationRoutine("PS60.routine.SetMonitoring",(True))
    sim.CallActivationRoutine("PS150.routine.SetMonitoring",(True))
    sim.CallActivationRoutine("CH1.routine.SetMonitoring",(True))
    sim.CallActivationRoutine("CH2.routine.SetMonitoring",(True))
    #sim.CallActivationRoutine("BECKHOFF.routine.SetMonitoring",(True))
       
    # Turn logging feature of the OVP/OCP module OFF
    sim.CallActivationRoutine("CH1.routine.SetLog",(0,0))
    sim.CallActivationRoutine("CH2.routine.SetLog",(0,0))
	
    # start xmlrpc
    print "\n",
    print "Starting simulation server for MMI: http://%s:%s" % (options.XmlRpcIP, options.XmlRpcPort)
    sim_thread = RemoteSimulatorThread(sim, "", options.XmlRpcPort)
    sim_thread.start()
    
    # wait 2 s to be sure the RemoteSimulator xmlRpcServer is started
    time.sleep(2.0)
    print "\n" 
    print "The SCOE is ready\n"
    
    # wait until simulation ends
    sim_thread.join()
    
    print "\n"
    print "The SCOE has been terminated\n"
####################################################################################
    
    config_models.dump_profile_data( sim, options )
Beispiel #13
0
def main(argv=None):

    if not argv:
        argv = sys.argv

    usage = 'usage: muttlearn [options] [-o file] mbox1 [mbox2...]\n'\
            '       muttlearn [options]\n'\
            '       muttlearn -D\n'\
            '       muttlearn --output-only'

    version = u'muttlearn %s\nCopyright (C) 2010 Johannes Weißl\n'\
        'License GPLv3+: GNU GPL version 3 or later '\
        '<http://gnu.org/licenses/gpl.html>.\n'\
        'This is free software: you are free to change and redistribute it.\n'\
        'There is NO WARRANTY, to the extent permitted by law.' % __version__
    desc = 'muttlearn is an alternative to manually maintaining profiles in mutt. '\
        'It scans your mailboxes, learns how you want to write mails (e.g. '\
        'with which from address, what signature, what greeting, etc.) and '\
        'outputs send-hooks per recipient or group of recipients.'

    locale.setlocale(locale.LC_ALL, '')

    parser = optparse.OptionParser(usage=usage,
                                   version=version,
                                   description=desc,
                                   prog='muttlearn')

    parser.add_option('-o', dest='output', default=None, metavar='FILE',
        help='output file, "-" for stdout')
    parser.add_option('-D', dest='dump_vars', action='store_true', default=False,
        help='print the value of all configuration options to stdout.')
    parser.add_option('-F', dest='muttlearnrc', default=None, metavar='FILE',
        help='use alternative config file instead of ~/.muttlearnrc')
    parser.add_option('-v', '--verbose', dest='verbosity', action='count', default=0,
        help='be verbose (multiple times: more verbose)')
    parser.add_option('-p', '--progress', action='store_true', default=False,
        help='show progress')
    parser.add_option('--muttrc', default=None, metavar='FILE',
        help='use this file instead of ~/.muttrc to get mutt defaults')
    parser.add_option('-n', '--no-muttrc', dest='read_muttrc', action='store_false', default=True,
        help='do not read ~/.muttrc')
    parser.add_option('-C', '--rebuild-cache', action='store_true', default=False,
        help='rebuild message cache (slow)')
    parser.add_option('-c', '--clean-cache', action='store_true', default=False,
        help='remove unused messages from the cache')
    parser.add_option('--output-only', action='store_true', default=False,
        help='do not scan messages, just output (very fast)')

    options, args = parser.parse_args(argv[1:])

    log.verbosity = options.verbosity

    if not options.read_muttrc and options.muttrc:
        parser.error('-n and --muttrc cannot both be specified')

    config.init(conf_path=options.muttlearnrc,
                mutt_conf_path=options.muttrc,
                read_muttrc=options.read_muttrc)

    if options.dump_vars:
        config.dump()
        return

    if not options.output:
        options.output = config.get('output_file').encode(locale.getpreferredencoding())
    if not options.output:
        parser.error('no output file specified, use $output_file or -o')

    mailbox_paths = args if args else config.get_mailboxes()
    if not mailbox_paths:
        parser.error('no mailbox specified for learning!')


    acquire_lock()

    if options.rebuild_cache:
        use_cache = False
    else:
        use_cache = not config.db_needs_rebuilding()
    if not use_cache:
        options.clean_cache = True
        log.debug('rebuilding message cache (slow!)')
        config.save_to_cache()
    else:
        log.debug('using message cache (faster)')

    if options.output_only:
        #recipients = load_recipients()
        recipients = gen_recipients_from_cache(config.options(),
                                               progress=options.progress)
    else:
        scan.init(config.options())
    
        mailboxes = [scan.Mailbox(path, 'auto') for path in mailbox_paths]
    
        recipients = gen_recipients(mailboxes,
                                    config.options(),
                                    use_cache=use_cache,
                                    clean_cache=options.clean_cache,
                                    progress=options.progress)

        #save_recipients(recipients)

    if options.output == '-':
        outfile = sys.stdout
    else:
        try:
            outfile = open(options.output, 'wb')
        except IOError, e:
            log.error('error opening output file: %s', e)
Beispiel #14
0
                                    config.options(),
                                    use_cache=use_cache,
                                    clean_cache=options.clean_cache,
                                    progress=options.progress)

        #save_recipients(recipients)

    if options.output == '-':
        outfile = sys.stdout
    else:
        try:
            outfile = open(options.output, 'wb')
        except IOError, e:
            log.error('error opening output file: %s', e)


    mutt_out = output.MuttOutput(outfile, config.options())
    mutt_out.output_header()
    # result is sorted, so that larger address groups are matched later.
    # Also comparison of output files is easier when debugging.
    for addr in sorted(recipients, key=lambda x:(len(x),x)):
        mutt_out.output_recipient(recipients[addr])

    if options.output != '-':
        outfile.close()

    release_lock()

if __name__ == '__main__':
    sys.exit(main())