Best Python code snippet using autotest_python
variables_service.py
Source:variables_service.py  
1import os2import re3import dotenv4from prettytable import PrettyTable5from project_alignment_optimizer.program.constants import *6dotenv_file = dotenv.find_dotenv('config.env')7dotenv.load_dotenv(dotenv_file)8def getVariableIntEnv(key):9    return int(os.environ[key])10def getVariableFloatEnv(key):11    return float(os.environ[key])12def getVariableStrEnv(key):13    return os.environ[key]14def setVariableEnv(key, value):15    dotenv.set_key(dotenv_file, key, str(value))16def validateKey(key, value):17    if key == MATCH:18        return validateInt(value)19    elif key == MISMATCH:20        return validateInt(value)21    elif key == FILE_FORMAT:22        return validateTypeRange(key, value)23    elif key == MIN_SEQUENCES:24        return validatePositiveInt(value)25    elif key == DB_HOMOLOGOUS_SEQUENCES:26        return validateTypeRange(key, value)27    elif key == N_HOMOLOGOUS_SEQUENCES:28        return validatePositiveInt(value)29    elif key == ADMIT_HOMOLOGOUS:30        return validateTypeRange(key, value)31    elif key == PURIFY_START:32        return validatePositiveInt(value)33    elif key == PURIFY_END:34        return validatePositiveInt(value)35    elif key == GAPOPEN:36        return validateFloat(value)37    elif key == GAPEXT:38        return validateFloat(value)39    elif key == MATRIX:40        return True, None41    else:42        return False, 'Error'43def validateInt(value):44    if value == None or value == '':45        message = f"No new value was inserted."46        return False, message47    isInt = re.match("[-+]?\d+$", value)48    if not isInt:49        message = f"The new value: '{value}' is not valid as an integer."50        return False, message51    return True, None52def validateFloat(value):53    if value == None or value == '':54        message = f"No new value was inserted."55        return False, message56    isInt = re.match("[-+]?\d*\.?\d*$", value)57    if not isInt:58        message = f"The new value: '{value}' is not valid as a float."59        return False, message60    return True, None61def validatePositiveInt(value):62    if value == None or value == '':63        message = f"No new value was inserted."64        return False, message65    isInt, message = validateInt(value)66    if not isInt:67        return isInt, message68    ivalue = int(value)69    if ivalue < 0:70        message = f"The new value: '{ivalue}' is not a valid positive integer value."71        return False, message72    return True, None73def validateTypeRange(key, value):74    if value == None or value == '':75        message = f"No new value was inserted."76        return False, message77    isInt, message = validateInt(value)78    if not isInt:79        return isInt, message80    ivalue = int(value)81    dictTypes = getDictTypes(key)82    if not ivalue in dictTypes.keys():83        message = f"The new value: '{ivalue}' is not a valid type. ({dictTypes})"84        return False, message85    return True, None86def getDictTypes(key):87    for name, description, type in ALL_ENV_VARIABLES_WITH_DESCRIPTION:88        if name == key:89            return type90    return None91def getDictVariablesValues():92    dictVariablesValues = {}93    # Recorre todas las variables del .env94    for variable_env in ALL_ENV_VARIABLES_INT:95        # Agrego al dict con el value tipo int96        dictVariablesValues[variable_env] = int(os.environ[variable_env])97    for variable_env in ALL_ENV_VARIABLES_FLOATS:98        # Agrego al dict con el value tipo float99        dictVariablesValues[variable_env] = float(os.environ[variable_env])100    for variable_env in ALL_ENV_VARIABLES_STRINGS:101        # Agrego al dict con el value tipo str102        dictVariablesValues[variable_env] = os.environ[variable_env]103    return dictVariablesValues104def getDictVariablesWithAllInfo():105    dictVariablesInfo = {}106    # Recorre todas las variables del .env107    for name, description, type in ALL_ENV_VARIABLES_WITH_DESCRIPTION:108        tempDict = {}109        tempDict['CURRENT_VALUE'] = getValueVariable(name)110        tempDict['DEFAULT_VALUE'] = RESET_VALUES[name]111        tempDict['DESCRIPTION'] = description112        tempDict['TYPE'] = type113        dictVariablesInfo[name] = tempDict114    return dictVariablesInfo115def getValueVariable(variableName):116    if variableName in ALL_ENV_VARIABLES_STRINGS:117        return os.environ[variableName]118    if variableName in ALL_ENV_VARIABLES_INT:119        return int(os.environ[variableName])120    if variableName in ALL_ENV_VARIABLES_FLOATS:121        return float(os.environ[variableName])122    123    return None124    125def getAllVariablesTable(args):126    table = PrettyTable(['Key', 'Current value'])127    table.align = 'l' # Align a la izquierda l -> left128    dictVariables = getDictVariablesWithAllInfo()129    table.add_row([PATH, args.file])130    table.add_row([QUERY_SEQUENCE_HEADER, args.query_sequence_header])131    if args.homologous_sequences_path is not None:132        table.add_row([HOMOLOGOUS_SEQUENCES_PATH, PATHLIB_ABSOLUTE + args.homologous_sequences_path])133    else:134        table.add_row([HOMOLOGOUS_SEQUENCES_PATH, '-'])135    for variable_env_name in dictVariables.keys():136        if dictVariables[variable_env_name]['TYPE']:137            current_value = dictVariables[variable_env_name]['CURRENT_VALUE']138            type_info = dictVariables[variable_env_name]['TYPE'][current_value]139            current_value_with_type = f"{current_value} ({type_info})"140            table.add_row([ variable_env_name, current_value_with_type ])141        else:142            table.add_row([ variable_env_name, dictVariables[variable_env_name]['CURRENT_VALUE'] ])143    return table144def getAllVariablesTableWithDescription():145    table = PrettyTable(['Key', 'Current value', 'Default Value', 'Description'])146    table.align = 'l' # Align a la izquierda l -> left147    dictVariablesWithDescription = getDictVariablesWithAllInfo()148    for variable_env_name in dictVariablesWithDescription.keys():149        variable_info = dictVariablesWithDescription[variable_env_name]150        table.add_row([variable_env_name, variable_info['CURRENT_VALUE'],variable_info['DEFAULT_VALUE'] ,variable_info['DESCRIPTION']])151    return table152def config_set_key_new_value(args):153    key_upper = args.key.upper()154    if key_upper in ALL_ENV_VARIABLES:155        isValidKey, message = validateKey(key_upper, args.value)156        if isValidKey:157            setVariableEnv(key_upper, args.value)158            message = f"Key '{key_upper}' was modified correctly, new value = {args.value}."159            return True, message160        else:161            return False, message162    else:163        message= f"Key Unrecognized, valid keys:{ALL_ENV_VARIABLES}"164        return False, message165def isValidHomologousSequencesPath(args):166    admit_homologous = getVariableIntEnv(ADMIT_HOMOLOGOUS)167    168    if args.homologous_sequences_path is not None and admit_homologous != True:169        return False170    171    return True172def resetDefaultValues():173    setVariableEnv(MATCH, RESET_VALUES[MATCH])174    setVariableEnv(MISMATCH, RESET_VALUES[MISMATCH])175    setVariableEnv(FILE_FORMAT, RESET_VALUES[FILE_FORMAT])176    setVariableEnv(MIN_SEQUENCES, RESET_VALUES[MIN_SEQUENCES])177    setVariableEnv(DB_HOMOLOGOUS_SEQUENCES, RESET_VALUES[DB_HOMOLOGOUS_SEQUENCES])178    setVariableEnv(N_HOMOLOGOUS_SEQUENCES, RESET_VALUES[N_HOMOLOGOUS_SEQUENCES])179    setVariableEnv(ADMIT_HOMOLOGOUS, RESET_VALUES[ADMIT_HOMOLOGOUS])180    setVariableEnv(PURIFY_START, RESET_VALUES[PURIFY_START])181    setVariableEnv(PURIFY_END, RESET_VALUES[PURIFY_END])182    setVariableEnv(GAPOPEN, RESET_VALUES[GAPOPEN])183    setVariableEnv(GAPEXT, RESET_VALUES[GAPEXT])...rapl_fs.py
Source:rapl_fs.py  
...49        energy_value = random.random()50        self.fs.create_file(domain_dir_name + '/energy_uj', contents=str(energy_value) + '\n')51        self.domains_energy_file[domain_id] = domain_dir_name + '/energy_uj'52        self.domains_current_energy[domain_id] = energy_value53    def reset_values(self):54        for key in self.domains_energy_file:55            new_val = random.random()56            self.domains_current_energy[key] = new_val57            with open(self.domains_energy_file[key], 'w') as energy_file:58                energy_file.write(str(new_val) + '\n')59    def get_device_type(self):60        return RaplDevice61@pytest.fixture62def empty_fs(fs):63    """64    filesystem describing a machine with one CPU but no RAPL API65    """66    return RaplFS(fs)67@pytest.fixture68def fs_pkg_one_socket(fs):69    """70    filesystem describing a machine with one CPU and RAPL API for package71    """72    rapl_fs = RaplFS(fs)73    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')74    rapl_fs.reset_values()75    return rapl_fs76@pytest.fixture77def fs_pkg_dram_one_socket(fs):78    """79    filesystem describing a machine with one CPU and RAPL API for package and dram80    """81    rapl_fs = RaplFS(fs)82    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')83    rapl_fs.add_domain(DRAM_0_DIR_NAME, 'dram', 'dram_0')84    rapl_fs.reset_values()85    return rapl_fs86@pytest.fixture87def fs_pkg_psys_one_socket(fs):88    """89    filesystem describing a machine with one CPU and RAPL API for package and psys90    """91    rapl_fs = RaplFS(fs)92    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')93    rapl_fs.add_domain('/sys/class/powercap/intel-rapl/intel-rapl:1', 'psys', 'psys')94    rapl_fs.reset_values()95    return rapl_fs96@pytest.fixture97def fs_pkg_dram_core_one_socket(fs):98    """99    filesystem describing a machine with one CPU and RAPL API for package dram and core100    """101    rapl_fs = RaplFS(fs)102    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')103    rapl_fs.add_domain(DRAM_0_DIR_NAME, 'dram', 'dram_0')104    rapl_fs.add_domain(CORE_0_DIR_NAME, 'core', 'core_0')105    rapl_fs.reset_values()106    return rapl_fs107@pytest.fixture108def fs_pkg_dram_uncore_one_socket(fs):109    """110    filesystem describing a machine with one CPU and RAPL API for package dram and core111    """112    rapl_fs = RaplFS(fs)113    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')114    rapl_fs.add_domain(DRAM_0_DIR_NAME, 'dram', 'dram_0')115    rapl_fs.add_domain(CORE_0_DIR_NAME, 'uncore', 'uncore_0')116    rapl_fs.reset_values()117    return rapl_fs118@pytest.fixture119def fs_pkg_two_socket(fs):120    """121    filesystem describing a machine with two CPU and RAPL API for package122    """123    rapl_fs = RaplFS(fs)124    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')125    rapl_fs.add_domain(SOCKET_1_DIR_NAME, 'package-1', 'package_1')126    rapl_fs.reset_values()127    return rapl_fs128@pytest.fixture129def fs_pkg_dram_two_socket(fs):130    """131    filesystem describing a machine with two CPU and RAPL API for package and dram132    """133    rapl_fs = RaplFS(fs)134    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')135    rapl_fs.add_domain(SOCKET_1_DIR_NAME, 'package-1', 'package_1')136    rapl_fs.add_domain(DRAM_0_DIR_NAME, 'dram', 'dram_0')137    rapl_fs.add_domain(DRAM_1_DIR_NAME, 'dram', 'dram_1')138    rapl_fs.reset_values()139    return rapl_fs140@pytest.fixture141def fs_pkg_psys_two_socket(fs):142    """143    filesystem describing a machine with two CPU and RAPL API for package144    """145    rapl_fs = RaplFS(fs)146    rapl_fs.add_domain(SOCKET_0_DIR_NAME, 'package-0', 'package_0')147    rapl_fs.add_domain(SOCKET_1_DIR_NAME, 'package-1', 'package_1')148    rapl_fs.add_domain('/sys/class/powercap/intel-rapl/intel-rapl:2/name', 'psys', 'psys')149    rapl_fs.reset_values()...fix.py
Source:fix.py  
1# -*- encoding: utf-8 -*-2'''3@File    :   fix.py4@Time    :   2021/06/26 16:04:545@Author  :   E-11 æä½³è¯ 6@Version :   1.07@Contact :   974879729@qq.com8'''9# here put the import lib10import os11import sqlite312import configparser13from Database.my_config_parser import MyConfigParser14from Database.opt_policy_db import select_all15def get_reset_value(conn):16    reset_values = {}17    records = select_all(conn, 'test')18    for record in records:19        item_id = record[0]20        item_name = record[1]21        current_val = record[2]22        recommend_comment = record[4]23        recommend_val = record[5]24        result = record[7]25        if result == 'æ£æ¥ä¸éè¿':26            print("\n***", item_name, ": ", current_val, "***")27            print("ä¿®æ¹å»ºè®®ï¼", recommend_comment)28            print("ä¿®æ¹å»ºè®®å¼/åºé´ï¼", recommend_val)29            reset_values[item_name] = input("请è¾å
¥ä¿®æ¹å¼ï¼")30    return reset_values31def fix(reset_values):32    # 读åé
ç½®æä»¶33    cfg_file_path = "../Database/config.inf"34    config = MyConfigParser()35    config.read(cfg_file_path, encoding='utf-16')36    try:37        i = 038        for item_name in reset_values.keys():39            config.set("System Access", item_name, reset_values[item_name])40            i += 141    except configparser.Error:42        print("failed to reset "+item_name+" to "+reset_values[item_name])43    # åå
¥é
ç½®æä»¶44    config.write(open("config.inf", "w", encoding='utf-16'))45    # å©ç¨seceditç导å
¥åè½ï¼è®©æ´æ¹åçé
ç½®çæ46    os.popen('secedit /import /db fix.sdb /cfg '+cfg_file_path)47    os.popen('secedit /configure /db fix.sdb /cfg '+cfg_file_path)48def recover():49    # os.popen('secedit /import /db recover.sdb /cfg config-backup.inf')50    os.popen('secedit /configure /db recover.sdb /cfg config-backup.inf')51def fix_main():52    conn = sqlite3.connect('../Database/policy.db')53    reset_values = get_reset_value(conn)54    fix(reset_values)55    conn.close()56if __name__ == '__main__':57    # fix_main()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
