Exemplo n.º 1
0
def initGestures():
	global gesturesFileExists, iniGestures
	if profileFileExists and gesturesBDPath() != '?':
		log.debug('Main gestures map found')
		confGen = gesturesBDPath()
		confspec = config.ConfigObj("", encoding="UTF-8", list_values=False)
		iniGestures = config.ConfigObj(confGen, configspec=confspec, indent_type="\t", encoding="UTF-8")
		result = iniGestures.validate(Validator())
		if result is not True:
			log.exception("Malformed configuration file")
			gesturesFileExists = False
		else: gesturesFileExists = True
	else:
		if curBD != "noBraille": log.warn('No main gestures map (%s) found' % gesturesBDPath(1))
		gesturesFileExists = False
	if gesturesFileExists:
		for g in iniGestures["globalCommands.GlobalCommands"]:
			if isinstance(
					iniGestures["globalCommands.GlobalCommands"][g],
					list):
				for h in range(
						len(iniGestures["globalCommands.GlobalCommands"][g])):
					iniGestures[inputCore.normalizeGestureIdentifier(
						str(iniGestures["globalCommands.GlobalCommands"][g][h]))] = g
			elif ('kb:' in g and g not in ["kb:alt', 'kb:control', 'kb:windows', 'kb:control', 'kb:applications"] and 'br(' + curBD + '):' in str(iniGestures["globalCommands.GlobalCommands"][g])):
				iniGestures[inputCore.normalizeGestureIdentifier(str(
					iniGestures["globalCommands.GlobalCommands"][g])).replace('br(' + curBD + '):', '')] = g
	return gesturesFileExists, iniGestures
 def onProfiles(self, evt=None):
     if len(self.profilesList) == 0: return
     curProfile = self.profilesList[self.profiles.GetSelection()]
     self.addonGesturesPrfofile = config.ConfigObj(
         '%s/baum/%s/profile.ini' % (configBE.profilesDir, curProfile),
         encoding="UTF-8")
     self.generalGesturesProfile = config.ConfigObj(
         '%s/baum/%s/gestures.ini' % (configBE.profilesDir, curProfile),
         encoding="UTF-8")
     if self.addonGesturesPrfofile == {}:
         wx.CallAfter(
             gui.messageBox,
             _("Unable to load this profile. Malformed or inaccessible file"
               ), self.title, wx.OK | wx.ICON_ERROR)
Exemplo n.º 3
0
def loadConf():
    global curBD, gesturesFileExists, profileFileExists, iniProfile
    curBD = braille.handler.display.name
    try:
        brlextConf = config.conf["brailleExtender"].copy()
    except configobj.validate.VdtValueError:
        config.conf["brailleExtender"]["updateChannel"] = "dev"
        brlextConf = config.conf["brailleExtender"].copy()
    if "profile_%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["profile_%s" % curBD] = "default"
    if "tabSize_%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["tabSize_%s" % curBD] = 2
    if "leftMarginCells__%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["leftMarginCells_%s" % curBD] = 0
    if "rightMarginCells_%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["rightMarginCells_%s" % curBD] = 0
    if "autoScrollDelay_%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["autoScrollDelay_%s" % curBD] = 3000
    if "keyboardLayout_%s" % curBD not in brlextConf.keys():
        config.conf["brailleExtender"]["keyboardLayout_%s" % curBD] = "?"
    confGen = (r"%s\%s\%s\profile.ini" %
               (profilesDir, curBD,
                config.conf["brailleExtender"]["profile_%s" % curBD]))
    if (curBD != "noBraille" and os.path.exists(confGen)):
        profileFileExists = True
        confspec = config.ConfigObj("", encoding="UTF-8", list_values=False)
        iniProfile = config.ConfigObj(confGen,
                                      configspec=confspec,
                                      indent_type="\t",
                                      encoding="UTF-8")
        result = iniProfile.validate(Validator())
        if result is not True:
            log.exception("Malformed configuration file")
            return False
    else:
        if curBD != "noBraille": log.warn("%s inaccessible" % confGen)
        else: log.debug("No braille display present")

    limitCellsRight = int(
        config.conf["brailleExtender"]["rightMarginCells_%s" % curBD])
    if (backupDisplaySize - limitCellsRight <= backupDisplaySize
            and limitCellsRight > 0):
        braille.handler.displaySize = backupDisplaySize - limitCellsRight
    if not noUnicodeTable: loadPreferedTables()
    if config.conf["brailleExtender"]["inputTableShortcuts"] not in tablesUFN:
        config.conf["brailleExtender"]["inputTableShortcuts"] = '?'
    if config.conf["brailleExtender"]["features"]["roleLabels"]:
        loadRoleLabels(config.conf["brailleExtender"]["roleLabels"].copy())
    return True
Exemplo n.º 4
0
def main():
    # Create a new argument parser & parse the command line args
    parser = init_parser()
    args = parser.parse_args()

    # Parse the input YAML file & initialize global CONFIG 'constant'
    config.CONFIG = config.ConfigObj(args.input_file)

    # Initialize a new main log
    logger = log_config.init_logger('logs', 'main', level='debug')
    logger.info('Input file {}'.format(args.input_file))

    info_str = 'Function(s) to execute: {}'
    # Execute the specified function(s)
    if (args.function == 'all'):
        logger.info(info_str.format('freeze_emissions() & calc_emissions()'))
        freeze_emissions()
        calc_emissions()
    elif (args.function == 'freeze_emissions'):
        logger.info(info_str.format('freeze_emissions()'))
        freeze_emissions()
    elif (args.function == 'calc_emissions'):
        logger.info(info_str.format('calc_emissions()'))
        calc_emissions()
    else:
        raise ValueError(
            'Invalid function argument. Valid args are "all", "freeze_emissions", or "calc_emissions"'
        )
Exemplo n.º 5
0
 def setUp(self):
     # Vars needed for initialization
     self.f_init = 'input/config-test_frozen_sectors.yml'
     self.f_ef = 'H.BC_total_EFs_extended.csv'
     self.species = 'BC'
     # Set up global CONFIG constant
     config.CONFIG = config.ConfigObj(self.f_init)
Exemplo n.º 6
0
 def setUp(self):
     # Vars needed for initialization
     self.f_init = 'input/test-config.yml'
     self.f_ef = 'H.BC_total_EFs_extended.csv'
     self.species = 'BC'
     # Set up global CONFIG constant
     config.CONFIG = config.ConfigObj(self.f_init)
     self.ef_path = os.path.join(config.CONFIG.dirs['cmip6'], self.f_ef)
     # Create new EmissionFactorFile instance
     self.ef_obj = emission_factor_file.EmissionFactorFile(
         self.species, self.ef_path)
    def setUpClass(cls):
        """
        Set up everything we need to test the output from the driver.py emission
        freezing functions freeze_emissions() & calc_emissions()
        
        Since its pretty expensive in terms of time to call the freeze_emissions()
        & calc_emissions() functions, we'll use a setUpClass to set up what we
        need for the test methods since setUpClass only executes onces at the
        beginning of execution (versus a setUp method, which executes before
        every test method call).
        """
        super(TestFreezeAll, cls).setUpClass()
        test_log.info('--- In TestFreezeAll::setUpClass ---')
        cls.species = 'BC'
        cls.f_em_factors = 'H.BC_total_EFs_extended.csv'
        cls.config_file = 'input/config-test_frozen_sectors.yml'
        cls.f_previous = r'C:\Users\nich980\data\e-freeze\frozen-emissions\2020-01-02\intermediate-output\H.BC_total_EFs_extended.csv'
        test_log.debug('Test species...........{}'.format(cls.species))
        test_log.debug('Test EF file...........{}'.format(cls.f_em_factors))
        test_log.debug('Test CONFIG file.......{}'.format(cls.config_file))
        test_log.debug('Test control EF file...{}'.format(cls.f_previous))

        # Point the CONFIG intermediate output directory to tests/input/
        config.CONFIG = config.ConfigObj(cls.config_file)
        config.CONFIG.dirs['output'] = 'input'

        # Freeze the emissions factors and calculate the final frozen emissions
        test_log.debug('Executing driver.freeze_emissions()')
        driver.freeze_emissions()
        test_log.debug('Executing driver.calc_emissions()')
        driver.calc_emissions()

        # Read the frozen emissions in to a dataframe
        test_log.debug('Reading current frozen EF file into DataFrame')
        cls.f_frozen = os.path.join(config.CONFIG.dirs['output'],
                                    cls.f_em_factors)
        cls._current_df = pd.read_csv(cls.f_frozen, sep=',', header=0)

        # Read the un-edited control CMIP6 EF file
        test_log.debug('Reading previous/control EF file into DataFrame')
        cls._previous_df = pd.read_csv(cls.f_previous, sep=',', header=0)
Exemplo n.º 8
0
 def setUp(self):
     """Initialize TestInit attributes for use in test cases.
     Not a test case
     """
     self.f_init = 'input/test-config.yml'
     self.config = config.ConfigObj(self.f_init)
Exemplo n.º 9
0
 def initialize(self):
     self.pop = []
     for _ in range(self.popSize):
         curr = config.ConfigObj(mutRate=self.mutRate)
         self.pop.append(curr)
Exemplo n.º 10
0
"""
Initialize a global CONFIG constant for use in test_config.py

Matt Nicholson
10 Feb 2020
"""
import sys

# Insert src directory to Python path for importing
sys.path.insert(1, '../src')

import config

f_init = 'input/test-config.yml'

config.CONFIG = config.ConfigObj(f_init)

def update_config():
    config.CONFIG.freeze_isos = ['USA']
    config.CONFIG.freeze_year = 2020
    config.CONFIG.ceds_meta['year_first'] = -1
    config.CONFIG.ceds_meta['year_last'] = 42069
Exemplo n.º 11
0
import config
from Server.copter_table_models import CopterDataModel

cfg_server = config.ConfigObj('SERVER/config/spec/configspec_server.ini', list_values=False)
widths = {"copter_id": 150}
default_width = 100

default = {key: f"preset_param(default=list(True, {widths.get(key, default_width)}))"
           for key in CopterDataModel.columns}

cfg_server['TABLE']['PRESETS']['DEFAULT'] = default

cfg_server.write()
print('Server configspec updated')