コード例 #1
0
def genListParamExp(lstParam, inputName, cstyle):
    strExp = ''
    sumName = GenTools.randCStyleName() if (cstyle
                                            == 'c') else GenTools.randTFName()

    if inputName != '':
        sumName = inputName

    if inputName == '':
        if lstParam['valType'] == 'int' or lstParam[
                'valType'] == 'long' or lstParam[
                    'valType'] == 'unsigned int' or lstParam[
                        'valType'] == 'unsigned long':
            strExp = strExp + 'long ' + sumName + ' = 0;\n\n'
        else:
            strExp = strExp + 'double ' + sumName + ' = 0.0;\n\n'

    strExp = strExp + 'for(unsigned i = 0; i < ' + lstParam[
        'valName'] + '.size(); i++) {\n'
    strExp = strExp + genSampleParamExp([{
        'valType': lstParam['valType'],
        'valName': lstParam['valName'] + '[i]'
    }], sumName, cstyle)
    strExp = strExp + '}\n'

    return strExp
コード例 #2
0
def genStaticFunc():
    strExp = ''
    strTemp = '${RETURN_TYPE} ${NAME}(${PARAM});'
    funcNumber = random.randint(3, 10)
    funList = [
    ]  # lst = [{'rt': returnType, 'name': functionName, 'prmlst': paramList, 'prmexp': void}]
    for _ in range(funcNumber):
        paramList = []  # lst = [{'valType': 'int', 'valName': 'member'}]
        funcName = 'out' + GenTools.randCStyleName()
        returnType = allValueTypeList[random.randint(
            0,
            len(allValueTypeList) - 2)] + '*'
        paramType = 'int'
        paramName = 'len_' + GenTools.randCStyleName()
        paramExp = paramType + '& ' + paramName
        if returnType == 'bool*':
            returnType = 'char*'

        funcExp = ''.join(
            Template(strTemp).substitute(RETURN_TYPE=returnType,
                                         NAME=funcName,
                                         PARAM=paramExp))
        strExp = strExp + funcExp + '\n\n\n'

        paramList.append({'valType': paramType, 'valName': paramName})
        funList.append({
            'rt': returnType,
            'name': funcName,
            'prmlst': paramList,
            'prmexp': paramExp
        })
    return {'exp': strExp, 'funlst': funList}
コード例 #3
0
def genCppClassFile(projectName, number, path):
    tplHFile = open(r'./tpl/GenTempCpp.h.tpl', 'r')
    strHTpl = tplHFile.read()
    tplHFile.close()

    tplCppFile = open(r'./tpl/GenTempCpp.cpp.tpl', 'r')
    strCppTpl = tplCppFile.read()
    tplCppFile.close()

    classInfo = [
    ]  # lst = [{'name': className, 'prop': property, 'member': memberFunction}]

    for _ in range(number):
        className = GenTools.randClassNameByModuleName(projectName)

        # property
        propertyInfo = genClassMemberProperty()
        propertyFuncExp = genGetterAndSetterPropertyFunction(propertyInfo)
        propertyFuncDefineExp = genGetterAndSetterPropertyFunctionDefine(
            className, propertyInfo)
        propertyInitExp = genInitProperty(propertyInfo)
        propertyDeletExp = genDeleteProperty(propertyInfo)

        memberFunctionInfo = genClassMemberFunc(className)
        memberFunctionDefineExp = genClassMemberFuncDefine(
            className, memberFunctionInfo, propertyInfo)

        strHExp = ''.join(
            Template(strHTpl).substitute(CLASS_NAME=className,
                                         PUBLIC_FUNC=propertyFuncExp +
                                         memberFunctionInfo['exp'],
                                         CLASS_MEMBER=propertyInfo['exp']))
        propertyDeletExp = propertyDeletExp if (
            propertyDeletExp != '') else '// add your logic here'
        strCppExp = ''.join(
            Template(strCppTpl).substitute(
                HEAD_FILE_NAME=className,
                CLASS_NAME=className,
                MEMBER_INIT_CODE=propertyInitExp,
                DELETE_MEMBER_CODE=propertyDeletExp,
                MEMBER_FUNC_DEFINE=propertyFuncDefineExp +
                memberFunctionDefineExp))

        hfile = open(path + className + '.h', 'w')
        hfile.write(strHExp)
        hfile.close()

        cppfile = open(path + className + '.cpp', 'w')
        cppfile.write(strCppExp)
        cppfile.close()

        classInfo.append({
            'name': className,
            'prop': propertyInfo,
            'member': memberFunctionInfo
        })
    return classInfo
コード例 #4
0
def genClassMemberFunc(className):
    strExp = ''
    funList = [
    ]  # lst = [{'rt': returnType, 'name': functionName, 'prmlst': paramList, 'prmexp': void}]
    strTemplate = '${RETURN} ${NAME}(${PARAM});'
    for _ in range(random.randint(5, 50)):
        paramList = []  # lst = [{'valType': 'int', 'valName': 'member'}]
        strReturnType = allValueTypeList[random.randint(
            0,
            len(allValueTypeList) - 2)]  #排除vector
        if random.randint(0, 3) == 0:
            strReturnType = 'void'
        strFuncName = GenTools.randMemberFuncName(className)

        strParamExp = ''
        paramNumber = random.randint(0, 5)
        for i in range(paramNumber):
            strParamType = allValueTypeList[random.randint(
                0,
                len(allValueTypeList) - 2)]  #排除vector
            strParamName = GenTools.randTFName()
            strParamExp = strParamExp + strParamType + ' ' + strParamName
            if i < paramNumber - 1:
                strParamExp = strParamExp + ','
            paramList.append({
                'valType': strParamType,
                'valName': strParamName
            })
        if strParamExp == '':
            strParamExp = 'void'
        strFunExp = '\t' + ''.join(
            Template(strTemplate).substitute(RETURN=strReturnType,
                                             NAME=strFuncName,
                                             PARAM=strParamExp)) + '\n'
        strExp = strExp + strFunExp
        funList.append({
            'rt': strReturnType,
            'name': strFuncName,
            'prmlst': paramList,
            'prmexp': strParamExp
        })
    return {'exp': strExp, 'funlst': funList}
コード例 #5
0
def genClassMemberProperty():
    strExp = ''
    valueList = []  # lst = [{'valType': 'int', 'valName': 'member'}]
    strTemplate = '${MEMBER_TYPE} ${MEMBER_NAME};'
    memberNumber = random.randint(5, 50)
    for _ in range(memberNumber):
        strValType = allValueTypeList[random.randint(0,
                                                     len(allValueTypeList) -
                                                     2)]  #排除vector
        strValName = GenTools.randMemberPropertyName(strValType)
        if strValType == 'vector':
            strValType = 'std::vector<' + allValueTypeList[random.randint(
                0,
                len(allValueTypeList) - 3)] + '>'
        strExp = strExp + '\t' + ''.join(
            Template(strTemplate).substitute(MEMBER_TYPE=strValType,
                                             MEMBER_NAME=strValName)) + '\n'
        valueList.append({'valType': strValType, 'valName': strValName})
    return {'exp': strExp, 'mbrlst': valueList}
コード例 #6
0
def genStaticGlobalFile(projectName, number, path):
    tplHFile = open(r'./tpl/GenStaticDataCppCode.h.tpl', 'r')
    strHTpl = tplHFile.read()
    tplHFile.close()

    tplCppFile = open(r'./tpl/GenStaticDataCppCode.cpp.tpl', 'r')
    strCppTpl = tplCppFile.read()
    tplCppFile.close()

    classInfo = [
    ]  # lst = [{'name': className, 'prop': property, 'member': memberFunction}]

    for _ in range(number):
        className = GenTools.randCStyleName()

        staticInfo = genStaticFunc()
        staticFuncExp = genStaticFuncDefine(staticInfo)

        strHExp = ''.join(
            Template(strHTpl).substitute(DATA_FUNCTION=staticInfo['exp']))
        strCppExp = ''.join(
            Template(strCppTpl).substitute(HEAD_FILE_NAME=className,
                                           FUNCTION_DEFINE=staticFuncExp))

        hfile = open(path + className + '.h', 'w')
        hfile.write(strHExp)
        hfile.close()

        cppfile = open(path + className + '.cpp', 'w')
        cppfile.write(strCppExp)
        cppfile.close()
        classInfo.append({
            'name': className,
            'prop': 'none',
            'member': staticInfo
        })
    return classInfo
コード例 #7
0
def genCallClassCode(classInfo, refClassLst, useClassLst, stsClassInfo,
                     strFmt):
    tplFile = open(r'./tpl/CallClassCode.tpl', 'r')
    strTpl = tplFile.read()
    tplFile.close()

    strCallExp = ''

    # 调用成员函数生成判断逻辑
    strLogicContent = ''
    logicParamList = []  # lst = [{'valType': 'int', 'valName': name}]
    callClassPropTpl = '${FMT}${CLASS_NAME} ${PROP_NAME};\n${FMT}${PARAM} = ${PROP_NAME}.out${PROP}();'
    for _ in range(random.randint(2, 5)):
        strName = GenTools.randTFName()
        strType = valueTypeList2[random.randint(0, len(valueTypeList2) - 1)]
        for i in range(len(useClassLst)):
            clsinf = useClassLst[i]
            subLogicExp = ''
            for j in range(len(clsinf['prop']['mbrlst'])):
                prop = clsinf['prop']['mbrlst'][j]
                if ((strType in integerValueTypeList) and
                    (prop['valType']
                     in integerValueTypeList)) or strType == prop['valType']:
                    propName = GenTools.randTFName()
                    subLogicExp = (strFmt if (strLogicContent != '') else
                                   '') + strType + ' ' + strName + ' = 0;\n'
                    subLogicExp = subLogicExp + ''.join(
                        Template(callClassPropTpl).substitute(
                            FMT=strFmt,
                            CLASS_NAME=clsinf['name'],
                            PROP_NAME=propName,
                            PARAM=strName,
                            PROP=prop['valName'])) + '\n\n'
                    strLogicContent = strLogicContent + subLogicExp
                    break
            if subLogicExp != '':
                break
        logicParamList.append({'valType': strType, 'valName': strName})
    strLogic = ''
    strAdd = ''
    for i in range(len(logicParamList)):
        prm = logicParamList[i]
        strLogic = strLogic + prm['valName']
        strAdd = strAdd + prm['valName']
        if i < len(logicParamList) - 1:
            strAdd = strAdd + ' + '
            strLogic = strLogic + (' && ' if
                                   (random.randint(0, 1) > 0) else '|')
    # 调用函数生成初始化程序
    strCallContent = ''
    callClassPropTplSet = '${FMT}${HAND_NAME}->in${PROP}(${SET_PARAM});'
    memberName = ''.join(
        Template('p${RETURN_CLASS}').substitute(
            RETURN_CLASS=classInfo['name']))
    propInfo = classInfo['prop']['mbrlst'][random.randint(
        0,
        len(classInfo['prop']['mbrlst']) - 1)]
    strCallContent = strCallContent + ''.join(
        Template(callClassPropTplSet).substitute(FMT=strFmt,
                                                 HAND_NAME=memberName,
                                                 PROP=propInfo['valName'],
                                                 SET_PARAM=strAdd))

    strCallExp = ''.join(
        Template(strTpl).substitute(LOGIC_CONTENT=strLogicContent,
                                    LOGIC=strLogic,
                                    CALL_CONTENT=strCallContent,
                                    FMT=strFmt))

    return strCallExp
コード例 #8
0
def genClassMemberFuncDefine(className, funcInfo, propertyInfo):
    strExp = ''
    funcLst = funcInfo['funlst']
    tplFile = open(r'./tpl/CppMemberFunctionTemplate.tpl', 'r')
    strTpl = tplFile.read()
    tplFile.close()

    for i in range(len(funcLst)):
        func = funcLst[i]
        funcBody = ''

        prmLst = func['prmlst']
        prmVecLst = []

        if len(prmLst) == 0 or random.randint(0, 1) > 0:
            propLen = len(propertyInfo['mbrlst'])
            for _ in range(random.randint(3, propLen)):
                prop = propertyInfo['mbrlst'][random.randint(0, propLen - 1)]
                if 'std::vector' in prop['valType']:
                    prmVecLst.append(prop)
                else:
                    prmLst.append(prop)

        strSumName = GenTools.randTFName() if (
            random.randint(0, 1) > 0) else GenTools.randCStyleName()
        funcBody = funcBody + integerValueTypeList[random.randint(
            0,
            len(integerValueTypeList) - 1)] + ' ' + strSumName + ' = 0;\n\n'

        # 通过传入参数生成函数体
        if len(prmLst) > 0:
            funcBody = funcBody + genSampleParamExp(prmLst, strSumName, 'none')
            funcBody = funcBody + '\n'

        # 关联类成员变量
        if len(prmVecLst) > 0:
            for j in range(len(prmVecLst)):
                prmvec = prmVecLst[j]
                val = ''.join(
                    re.compile('<.*>').search(prmvec['valType']).group())
                param = {
                    'valType': ''.join(val[1:len(val) - 1]),
                    'valName': prmvec['valName']
                }
                funcBody = funcBody + genListParamExp(param, strSumName,
                                                      'none')
                funcBody = funcBody + '\n'

        funcBody = funcBody + '\n\n'

        # 最后一行
        if func['rt'] == 'void':
            prop = propertyInfo['mbrlst'][random.randint(
                0,
                len(propertyInfo['mbrlst']) - 1)]
            if 'std::vector' in prop['valType']:
                funcBody = funcBody + '\t' + prop[
                    'valName'] + '.push_back(' + strSumName + ');' + '\n\n'
            elif prop['valType'] == 'bool':
                funcBody = funcBody + '\t' + prop[
                    'valName'] + ' = ' + strSumName + ' > ' + str(
                        random.randint(0, 9999)) + ' ? true : false;\n\n'
            else:
                funcBody = funcBody + '\t' + prop[
                    'valName'] + ' = ' + '(' + prop[
                        'valType'] + ')' + strSumName + ';\n\n'
        else:
            funcBody = funcBody + '\treturn (' + func[
                'rt'] + ')' + strSumName + ';\n\n'

        funcExp = ''.join(
            Template(strTpl).substitute(RETURN_TYPE=func['rt'],
                                        CLASS_NAME=className,
                                        FUNCTION_NAME=func['name'],
                                        FUNCTION_PARAM_LIST=func['prmexp'],
                                        FUNCTION_BODY=funcBody))
        funcExp = funcExp + '\n\n'
        strExp = strExp + funcExp
    return strExp
コード例 #9
0
def genSampleParamExp(paramList, inputName, cstyle):
    strExp = ''
    sumName = GenTools.randCStyleName() if (cstyle
                                            == 'c') else GenTools.randTFName()
    if inputName != '':
        sumName = inputName

    if inputName == '':
        strExp = integerValueTypeList[random.randint(
            0,
            len(integerValueTypeList) - 1)] + ' ' + sumName + ' = 0;\n'

    # gen: sum = p1 + p2 + ...
    for i in range(len(paramList)):
        param = paramList[i]
        if param['valType'] != 'bool':
            if i == 0:
                strExp = strExp + '\t' + sumName + ' = ' + param[
                    'valName'] + ' '
            else:
                strExp = strExp + random.choice(
                    operTypeList) + ' ' + param['valName'] + ' '
        else:
            strBooleanValue = random.choice(strNumber)
            if i == 0:
                strExp = strExp + '\t' + sumName + ' = ' + strBooleanValue + ' '
            else:
                strExp = strExp + random.choice(
                    operTypeList) + ' ' + strBooleanValue + ' '
    strExp = strExp + ';\n\n'

    for i in range(len(paramList)):
        param = paramList[i]
        if param['valType'] == 'int' or param['valType'] == 'long' or param[
                'valType'] == 'char' or param[
                    'valType'] == 'unsigned int' or param[
                        'valType'] == 'unsigned long':
            expName = GenTools.randCStyleName() if (
                cstyle == 'c') else GenTools.randTFName()
            # int name = sum<<param
            exp = '\tint ' + expName + ' = ' + sumName + ' ' + random.choice(
                operTypeList) + ' ' + param['valName'] + ';\n'
            # 生成规则,后面完善
            if random.randint(0, 1) > 0:  # sum = sum + sum&val
                exp = exp + '\t' + sumName + ' = ' + sumName + ' + ' + sumName + '&' + expName + ';\n'
            else:  # value = sum|cos(val%rand) + sum&sin(val%rand)
                exp = exp + '\t' + sumName + ' = ' + sumName + '/' + 'cos(' + expName + " + " + (
                    random.choice(strNumber1) if (random.randint(0, 1) > 0)
                    else random.choice(strNumber0)) + ')' + ' + '
                exp = exp + sumName + '*' + 'sin(' + expName + '-' + (
                    random.choice(strNumber1) if (random.randint(0, 1) > 0)
                    else random.choice(strNumber0)) + ')'
                exp = exp + ';\n'
            strExp = strExp + exp + '\n\n'
        elif param['valType'] == 'double' or param['valType'] == 'float':
            expName = GenTools.randCStyleName() if (
                cstyle == 'c') else GenTools.randTFName()
            exp = '\tdouble ' + expName + ' = ' + sumName + random.choice(
                operTypeList
            ) + 'tan(' + param[
                'valName'] + ')' + ' + ' + sumName + '*' + '1.0/tan(' + param[
                    'valName'] + ');\n'
            exp = exp + '\t' + sumName + ' += ' + expName + ';\n\n'
            strExp = strExp + exp + '\n\n'
        elif param['valType'] == 'bool':
            exp = '\tif(' + param[
                'valName'] + ') {\n\t\t' + sumName + ' = ' + sumName + '<<' + str(
                    random.randint(1, 4)) + ';\n\t} else {\n\t\t'
            exp = exp + sumName + ' = ' + sumName + '<<' + str(
                random.randint(1, 4)) + ';\n\t}\n'
            strExp = strExp + exp + '\n\n'
    return strExp
コード例 #10
0
def testGenTools():
    return GenTools.randMemberFuncName(
        'CCStyle') + '@@@@' + GenTools.randClassNameByModuleName(
            'CCStryle') + '@@@@' + GenTools.randMemberPropertyName(
                'int') + '@@@@' + GenTools.randCName('CCStyle')
コード例 #11
0
ファイル: GenHTMLMates.py プロジェクト: lwerdna/chess
        (bfen, line) = map(lambda x: str(x), row)

        m = re.match('^(.*?) ', line)
        if not m:
            raise Exception("WTF? can't get first move from %s" % line)

        hint = m.group(1)

        boardMap = CrazyLogic.fenToBoardMap(bfen)

        flipped = 0
        if boardMap['activePlayer'] == 'b':
            flipped = 1

        html = GenTools.boardMapToHtml(boardMap, flipped, imgPath)
        html += "<h2>Puzzle %d</h2>\n" % rowIdx
        html += "<hr>\n"

        if anki:
            html = re.sub('\n', '', html)
            html = '%s;figure it out?' % html

        puzzleArray.append(html)

    #if anki:
        #random.shuffle(puzzleArray)

    for p in puzzleArray:
        print p
# Test of data artificial data generation tools

import GenTools

mass = 700  # Mass of the car in lbs

sim = GenTools.DataGenerator(sim_time=5, logging=False)

sim.run_route_based("route.json")
print(sim.Battery.high_cell)
print(sim.Battery.low_cell)
# sim.run()
# Test program for testing other tools

import GenTools
import pyodbc

server = "CAE-FALL2019-CA\SUNSEEKER_Test"
database = "DataGenerationTestDB"
table = "Array"

if __name__ == '__main__':
    print("This worked, I guess")
    GenTools.write_database(server, database, table,
                            ('12:15:25', '615', '123', '5'))
    # conn = pyodbc.connect("Driver={SQL Server};"
    #                       "Server=CAE-FALL2019-CA\SUNSEEKER_Test;"
    #                       "Database=DataGenerationTestDB;"
    #                       "Trusted_Connection=yes;")
    # cursor = conn.cursor()
    # cursor.execute("""
    #                 INSERT INTO DataGenerationTestDB.dbo.Array (Time, Array_Power, Array_Voltage, Array_Current)
    #
    #                 VALUES
    #                 ('12:15:05', '600', '120', '5'),
    #                 ('12:15:10', '605', '121', '5'),
    #                 ('12:15:15', '610', '122', '5'),
    #                 ('12:15:20', '615', '123', '5')
    #                 """)
    conn.commit()

# def write_database(server, database, table, data):
#     print("attempting to connect")
コード例 #14
0
        (bfen, line) = map(lambda x: str(x), row)

        m = re.match('^(.*?) ', line)
        if not m:
            raise Exception("WTF? can't get first move from %s" % line)

        hint = m.group(1)

        boardMap = CrazyLogic.fenToBoardMap(bfen)

        flipped = 0
        if boardMap['activePlayer'] == 'b':
            flipped = 1

        html = GenTools.boardMapToHtml(boardMap, flipped, imgPath)
        html += "<h2>Puzzle %d</h2>\n" % rowIdx
        html += "<hr>\n"

        if anki:
            html = re.sub('\n', '', html)
            html = '%s;figure it out?' % html

        puzzleArray.append(html)

    #if anki:
    #random.shuffle(puzzleArray)

    for p in puzzleArray:
        print p