<commit_before>import racy
import racy.renv
import os
import os.path
from os.path import join as opjoin

# this dictionary contains all varibles for templates
dico_g = {
    'RACY_INSTALL_DIR': racy.renv.dirs.install,
    'RACY_SRC_DIR'    : racy.renv.dirs.code,
    'IDE_INSTALL_DIR' : opjoin(racy.renv.dirs.install, 'ide'),
    'WIX_INSTALL_DIR' : opjoin(racy.renv.dirs.install, 'wix'),
    'RACY_CMD'        : racy.get_racy_cmd(),
    'RACY_BIN_PATH'   : racy.renv.dirs.install_bin,
    'RACY_BUNDLE_PATH': racy.renv.dirs.install_bundle,
    'OS_NAME'         : racy.renv.system(), #windows, darwin, linux
    'SEP'             : os.sep,
    'PATHSEP'         : os.pathsep,
    'IDE_PLUGIN_PATH' : os.path.dirname(__file__),
    'WIX_PLUGIN_PATH' : os.path.dirname(__file__),
    'CALLING_PROJECT_TARGET' : '',
}

if os.name == 'nt':
    qt_default_dir = opjoin(os.environ['APPDATA'],'Nokia','qtcreator')
else:
    qt_default_dir = opjoin(os.path.expanduser("~"),'.config',
                                    'Nokia', 'qtcreator')

dico_prj_template = {
    'dico_ide':
    {
        'options':
        {
            'default_value': 'none',
            'allowed_value': ['none', 'eclipse', 'qtcreator', 'graphviz','vim','msvs'],
            'commandline_prj_opts': True,
            'descriptions_opts':
    """Preferencies formated project name.
    You can use this variable like this:
    $( VARIABLE )
    PRJ_NAME           : project base name.
    RACY_CMD           : racy command.
    PRJ_TYPE           : project type.
    OS_NAME            : os name.
    SEP                : os depend separator (/ or \\).
    PATHSEP            : path separator ( : ).
    CALLING_PROJECT    : the main project.
    PROJECT_SPLIT_PATH : list of element in prj_path,
                         the first element is the last directory
                         in RACY_SRC_DIR path.
    """,
        },

        'qtcreator' :
        {
            'dirs':
                [
                    ('QT_DIR'   ,'${IDE_INSTALL_DIR}/qtcreator/${PRJ_NAME}/'),
                    ('TPL_DIR' ,'${IDE_PLUGIN_PATH}/rc/qtcreator/'     ),
                    ('OS_DIR'   , qt_default_dir                   ),
                ]
            ,
            'template_prj':
                [

                    ('${TPL_DIR}/template.pro'     ,
                            '${QT_DIR}/${PRJ_NAME}.pro'     ),
                    ('${TPL_DIR}/template.pro.user',
                            '${QT_DIR}/${PRJ_NAME}.pro.user'),
                    ('${TPL_DIR}/template.qws'     ,
                            '${OS_DIR}/${PRJ_NAME}.qws'     ),
                ]

        },

        'eclipse' :
        {
            'dirs':
                [
                   ( 'EC_DIR'     , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/${PRJ_USER_FORMAT}/')
                   ),
                   ( 'LAUNCH_DIR' , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/.metadata/.plugins/'
                                      'org.eclipse.debug.core/.launches/')
                   ),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/eclipse/'       ),
                ]

            ,
            'template_prj':
                [
                    ('${TPL_DIR}/template.project'       ,
                        '${EC_DIR}/.project'               ),
                    ('${TPL_DIR}/template.cproject'      ,
                       '${EC_DIR}/.cproject'               ),
                    ('${TPL_DIR}/template_exec.launch' ,
                       '${LAUNCH_DIR}/exec.launch'         ),
                ]
         },

        'eclipse-inplace' :
        {
            'dirs':
                [
                   ( 'EC_DIR'     , ('${PRJ_ROOT_DIR}/')
                   ),
                   ( 'LAUNCH_DIR' , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/.metadata/.plugins/'
                                      'org.eclipse.debug.core/.launches/')
                   ),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/eclipse/'       ),
                ]

            ,
            'template_prj':
                [
                    ('${TPL_DIR}/template.project'       ,
                        '${EC_DIR}/.project'               ),
                    ('${TPL_DIR}/template.cproject'      ,
                       '${EC_DIR}/.cproject'               ),
                    ('${TPL_DIR}/template_exec.launch' ,
                       '${LAUNCH_DIR}/exec.launch'         ),
                ]
         },

         'graphviz' :
         {
            'dirs':
                [
                   ( 'GRAPHVIZ_DIR' , ('${IDE_INSTALL_DIR}/graphviz/'
                                     '${CALLING_PROJECT}/'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/graphviz/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/template.dot'            ,
                     '${GRAPHVIZ_DIR}/${CALLING_PROJECT}.dot'),
                ]
          },
         'vim' :
         {
            'dirs':
                [
                   ( 'VIM_DIR' , ('${IDE_INSTALL_DIR}/vim/'
                                     '${CALLING_PROJECT}/'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/vim/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/vim.tagslist'            ,
                     '${VIM_DIR}/.${PRJ_NAME}_tagslist'),
                    ('${TPL_DIR}/vim.project'            ,
                     '${VIM_DIR}/.${PRJ_NAME}_vimprj'),
                    ('${TPL_DIR}/tmp.tagslist'            ,
                     '${VIM_DIR}/tagslist'),
                    ('${TPL_DIR}/tmp.vimprj'            ,
                     '${VIM_DIR}/vimprj'),

                ]
          },
          'msvs' :
          {
              'dirs':
                [
                   ( 'MSVS_DIR' , ('${IDE_INSTALL_DIR}/msvs/'
                                     '${CALLING_PROJECT}/${PRJ_NAME}'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/msvs/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/temp.vcproj'            ,
                     '${MSVS_DIR}/${PRJ_NAME}.vcproj'),
                    ('${TPL_DIR}/user.template'            ,
                     '${MSVS_DIR}/${PRJ_NAME}.vcproj.user'),

                    ('${TPL_DIR}/temp.sln'            ,
                     '${IDE_INSTALL_DIR}/msvs/'
                           '${CALLING_PROJECT}/${CALLING_PROJECT}.sln'),
                ]
          }
    }
    ,
    'dico_prj_user_format':
    {
        'options':
        {
            'default_value' : '$(PRJ_TYPE)_$(PRJ_NAME)',
            'commandline_prj_opts': True,
            'commandline_opts': True,
            'descriptions_opts':"Create new developer project",
        },

    }
    ,
    'dico_create_prj':
    {
        'options':
        {
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'descriptions_opts':"Create new developer project",
        },
        'exec':
        {

            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/exec/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/main.cpp', '${SRC_DIR}/main.cpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]
        },
        'bundle':
        {

            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/bundle/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('RC_DIR', '${PRJ_PATH}/rc/'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),

                ],
            'template_prj':
                [
                    ('${TPL_DIR}/config.hpp', '${INCLUDE_DIR}/config.hpp'),
                    ('${TPL_DIR}/plugin.hpp', '${INCLUDE_DIR}/Plugin.hpp'),
                    ('${TPL_DIR}/plugin.cpp', '${SRC_DIR}/Plugin.cpp'),
                    ('${TPL_DIR}/plugin.xml', '${RC_DIR}/plugin.xml'),
                    ('${TPL_DIR}/namespace.hpp','${INCLUDE_DIR}/namespace.hpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]
        },
        'shared':
        {
            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/bundle/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),

                ],
            'template_prj':
                [
                    ('${TPL_DIR}/config.hpp', '${INCLUDE_DIR}/config.hpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]

        },
    }
    ,
    'dico_create_srv':
    {
        'options':
        {

            'commandline_prj_opts': True,
            'commandline_opts': True,
            'descriptions_opts':"Create new service",
        },

        'srv':
        {
            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/srv/'),
                    ('SRC_DIR', 'src/${PRJ_NAME}/${SRV_PATH}/'),
                    ('INCLUDE_DIR', 'include/${PRJ_NAME}/${SRV_PATH}/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/srv.hpp', '${INCLUDE_DIR}${SRV_NAME}.hpp'),
                    ('${TPL_DIR}/namespace.hpp', '${INCLUDE_DIR}/namespace.hpp'),
                    ('${TPL_DIR}/srv.cpp', '${SRC_DIR}${SRV_NAME}.cpp'),
                ]

        }
    }
    ,
    'dico_create_wix':
    {
        'options':
        {

            'default_value' : 'no',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : ['yes' , 'no'],
            'descriptions_opts':"Create new wix installer",
        },

        'yes':
        {
            'dirs':
                [
                    ('WIX_DIR'   ,'${WIX_INSTALL_DIR}/${CALLING_PROJECT}/'),
                    ('WIX_BITMAP_DIR'   ,'${WIX_INSTALL_DIR}/${CALLING_PROJECT}/Bitmaps'),
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/wix/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/call.wxs',
                        '${WIX_DIR}/${CALLING_PROJECT_FULL_NAME}.wxs'),
                    ('${TPL_DIR}/proj.wxs', '${WIX_DIR}/${PRJ_NAME}.wxs'),
                    ('${TPL_DIR}/generate_msi.py',
                         '${WIX_DIR}/gen_msi_${CALLING_PROJECT_FULL_NAME}.py'),
                    ('${TPL_DIR}/generate_msi.bat',
                         '${WIX_DIR}/gen_msi_${CALLING_PROJECT_FULL_NAME}.bat'),

                ]

        }

    }
    ,
    'dico_wix_profile':
    {
        'options':
        {

            'default_value' : 'rc/profile.xml',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : [],
            'descriptions_opts':"Path to profile relative to project dir",
        },
    }
    ,
    'dico_wix_icon':
    {
        'options':
        {

            'default_value' : '',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : [],
            'descriptions_opts':"Path to icon relative to project dir",
        },
    }

}

def get_dico_prj(dico, type):
    return dico[type]

def get_dico_prj_options(dico):
    res = {}
    for prj, attr in dico.items():

        if attr.has_key('options'):
            prj = prj.replace('dico_', '')
            prj = prj.upper()
            res[prj] = attr['options']

    return res

<commit_msg>[templating] Corrected help of PRJ_USER_FORMAT<commit_after>import racy
import racy.renv
import os
import os.path
from os.path import join as opjoin

# this dictionary contains all varibles for templates
dico_g = {
    'RACY_INSTALL_DIR': racy.renv.dirs.install,
    'RACY_SRC_DIR'    : racy.renv.dirs.code,
    'IDE_INSTALL_DIR' : opjoin(racy.renv.dirs.install, 'ide'),
    'WIX_INSTALL_DIR' : opjoin(racy.renv.dirs.install, 'wix'),
    'RACY_CMD'        : racy.get_racy_cmd(),
    'RACY_BIN_PATH'   : racy.renv.dirs.install_bin,
    'RACY_BUNDLE_PATH': racy.renv.dirs.install_bundle,
    'OS_NAME'         : racy.renv.system(), #windows, darwin, linux
    'SEP'             : os.sep,
    'PATHSEP'         : os.pathsep,
    'IDE_PLUGIN_PATH' : os.path.dirname(__file__),
    'WIX_PLUGIN_PATH' : os.path.dirname(__file__),
    'CALLING_PROJECT_TARGET' : '',
}

if os.name == 'nt':
    qt_default_dir = opjoin(os.environ['APPDATA'],'Nokia','qtcreator')
else:
    qt_default_dir = opjoin(os.path.expanduser("~"),'.config',
                                    'Nokia', 'qtcreator')

dico_prj_template = {
    'dico_ide':
    {
        'options':
        {
            'default_value': 'none',
            'allowed_value': ['none', 'eclipse', 'qtcreator', 'graphviz','vim','msvs'],
            'commandline_prj_opts': True,
            'descriptions_opts':"Create new developer project",
         },

        'qtcreator' :
        {
            'dirs':
                [
                    ('QT_DIR'   ,'${IDE_INSTALL_DIR}/qtcreator/${PRJ_NAME}/'),
                    ('TPL_DIR' ,'${IDE_PLUGIN_PATH}/rc/qtcreator/'     ),
                    ('OS_DIR'   , qt_default_dir                   ),
                ]
            ,
            'template_prj':
                [

                    ('${TPL_DIR}/template.pro'     ,
                            '${QT_DIR}/${PRJ_NAME}.pro'     ),
                    ('${TPL_DIR}/template.pro.user',
                            '${QT_DIR}/${PRJ_NAME}.pro.user'),
                    ('${TPL_DIR}/template.qws'     ,
                            '${OS_DIR}/${PRJ_NAME}.qws'     ),
                ]

        },

        'eclipse' :
        {
            'dirs':
                [
                   ( 'EC_DIR'     , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/${PRJ_USER_FORMAT}/')
                   ),
                   ( 'LAUNCH_DIR' , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/.metadata/.plugins/'
                                      'org.eclipse.debug.core/.launches/')
                   ),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/eclipse/'       ),
                ]

            ,
            'template_prj':
                [
                    ('${TPL_DIR}/template.project'       ,
                        '${EC_DIR}/.project'               ),
                    ('${TPL_DIR}/template.cproject'      ,
                       '${EC_DIR}/.cproject'               ),
                    ('${TPL_DIR}/template_exec.launch' ,
                       '${LAUNCH_DIR}/exec.launch'         ),
                ]
         },

        'eclipse-inplace' :
        {
            'dirs':
                [
                   ( 'EC_DIR'     , ('${PRJ_ROOT_DIR}/')
                   ),
                   ( 'LAUNCH_DIR' , ('${IDE_INSTALL_DIR}/eclipse/'
                                     '${CALLING_PROJECT}/.metadata/.plugins/'
                                      'org.eclipse.debug.core/.launches/')
                   ),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/eclipse/'       ),
                ]

            ,
            'template_prj':
                [
                    ('${TPL_DIR}/template.project'       ,
                        '${EC_DIR}/.project'               ),
                    ('${TPL_DIR}/template.cproject'      ,
                       '${EC_DIR}/.cproject'               ),
                    ('${TPL_DIR}/template_exec.launch' ,
                       '${LAUNCH_DIR}/exec.launch'         ),
                ]
         },

         'graphviz' :
         {
            'dirs':
                [
                   ( 'GRAPHVIZ_DIR' , ('${IDE_INSTALL_DIR}/graphviz/'
                                     '${CALLING_PROJECT}/'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/graphviz/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/template.dot'            ,
                     '${GRAPHVIZ_DIR}/${CALLING_PROJECT}.dot'),
                ]
          },
         'vim' :
         {
            'dirs':
                [
                   ( 'VIM_DIR' , ('${IDE_INSTALL_DIR}/vim/'
                                     '${CALLING_PROJECT}/'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/vim/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/vim.tagslist'            ,
                     '${VIM_DIR}/.${PRJ_NAME}_tagslist'),
                    ('${TPL_DIR}/vim.project'            ,
                     '${VIM_DIR}/.${PRJ_NAME}_vimprj'),
                    ('${TPL_DIR}/tmp.tagslist'            ,
                     '${VIM_DIR}/tagslist'),
                    ('${TPL_DIR}/tmp.vimprj'            ,
                     '${VIM_DIR}/vimprj'),

                ]
          },
          'msvs' :
          {
              'dirs':
                [
                   ( 'MSVS_DIR' , ('${IDE_INSTALL_DIR}/msvs/'
                                     '${CALLING_PROJECT}/${PRJ_NAME}'
                   )),
                   ( 'TPL_DIR'   , '${IDE_PLUGIN_PATH}/rc/msvs/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/temp.vcproj'            ,
                     '${MSVS_DIR}/${PRJ_NAME}.vcproj'),
                    ('${TPL_DIR}/user.template'            ,
                     '${MSVS_DIR}/${PRJ_NAME}.vcproj.user'),

                    ('${TPL_DIR}/temp.sln'            ,
                     '${IDE_INSTALL_DIR}/msvs/'
                           '${CALLING_PROJECT}/${CALLING_PROJECT}.sln'),
                ]
          }
    }
    ,
    'dico_prj_user_format':
    {
        'options':
        {
            'default_value' : '$(PRJ_TYPE)_$(PRJ_NAME)',
            'commandline_prj_opts': True,
            'commandline_opts': True,
            'descriptions_opts':
    """Preferencies formated project name.
    You can use this variable like this:
    $( VARIABLE )
    PRJ_NAME           : project base name.
    RACY_CMD           : racy command.
    PRJ_TYPE           : project type.
    OS_NAME            : os name.
    SEP                : os depend separator (/ or \\).
    PATHSEP            : path separator ( : ).
    CALLING_PROJECT    : the main project.
    PROJECT_SPLIT_PATH : list of element in prj_path,
                         the first element is the last directory
                         in RACY_SRC_DIR path.
    """,

        },

    }
    ,
    'dico_create_prj':
    {
        'options':
        {
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'descriptions_opts':"Create new developer project",
        },
        'exec':
        {

            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/exec/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/main.cpp', '${SRC_DIR}/main.cpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]
        },
        'bundle':
        {

            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/bundle/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('RC_DIR', '${PRJ_PATH}/rc/'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),

                ],
            'template_prj':
                [
                    ('${TPL_DIR}/config.hpp', '${INCLUDE_DIR}/config.hpp'),
                    ('${TPL_DIR}/plugin.hpp', '${INCLUDE_DIR}/Plugin.hpp'),
                    ('${TPL_DIR}/plugin.cpp', '${SRC_DIR}/Plugin.cpp'),
                    ('${TPL_DIR}/plugin.xml', '${RC_DIR}/plugin.xml'),
                    ('${TPL_DIR}/namespace.hpp','${INCLUDE_DIR}/namespace.hpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]
        },
        'shared':
        {
            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/bundle/'),
                    ('LICENSE_TMP_DIR', '${ROOT_TMP_DIR}/licenses/'),
                    ('SRC_DIR', '${PRJ_PATH}/src/${PRJ_NAME}'),
                    ('INCLUDE_DIR', '${PRJ_PATH}/include/${PRJ_NAME}'),
                    ('BIN_DIR', '${PRJ_PATH}/bin'),

                ],
            'template_prj':
                [
                    ('${TPL_DIR}/config.hpp', '${INCLUDE_DIR}/config.hpp'),
                    ('${ROOT_TMP_DIR}/bin/build.options', '${BIN_DIR}/build.options'),
                    ('${LICENSE_TMP_DIR}/COPYING', '${PRJ_PATH}/COPYING'),
                    ('${LICENSE_TMP_DIR}/COPYING.LESSER', '${PRJ_PATH}/COPYING.LESSER'),
                ]

        },
    }
    ,
    'dico_create_srv':
    {
        'options':
        {

            'commandline_prj_opts': True,
            'commandline_opts': True,
            'descriptions_opts':"Create new service",
        },

        'srv':
        {
            'dirs':
                [
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/dev/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/srv/'),
                    ('SRC_DIR', 'src/${PRJ_NAME}/${SRV_PATH}/'),
                    ('INCLUDE_DIR', 'include/${PRJ_NAME}/${SRV_PATH}/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/srv.hpp', '${INCLUDE_DIR}${SRV_NAME}.hpp'),
                    ('${TPL_DIR}/namespace.hpp', '${INCLUDE_DIR}/namespace.hpp'),
                    ('${TPL_DIR}/srv.cpp', '${SRC_DIR}${SRV_NAME}.cpp'),
                ]

        }
    }
    ,
    'dico_create_wix':
    {
        'options':
        {

            'default_value' : 'no',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : ['yes' , 'no'],
            'descriptions_opts':"Create new wix installer",
        },

        'yes':
        {
            'dirs':
                [
                    ('WIX_DIR'   ,'${WIX_INSTALL_DIR}/${CALLING_PROJECT}/'),
                    ('WIX_BITMAP_DIR'   ,'${WIX_INSTALL_DIR}/${CALLING_PROJECT}/Bitmaps'),
                    ('ROOT_TMP_DIR', '${IDE_PLUGIN_PATH}/rc/'),
                    ('TPL_DIR' , '${ROOT_TMP_DIR}/wix/'),
                ],
            'template_prj':
                [
                    ('${TPL_DIR}/call.wxs',
                        '${WIX_DIR}/${CALLING_PROJECT_FULL_NAME}.wxs'),
                    ('${TPL_DIR}/proj.wxs', '${WIX_DIR}/${PRJ_NAME}.wxs'),
                    ('${TPL_DIR}/generate_msi.py',
                         '${WIX_DIR}/gen_msi_${CALLING_PROJECT_FULL_NAME}.py'),
                    ('${TPL_DIR}/generate_msi.bat',
                         '${WIX_DIR}/gen_msi_${CALLING_PROJECT_FULL_NAME}.bat'),

                ]

        }

    }
    ,
    'dico_wix_profile':
    {
        'options':
        {

            'default_value' : 'rc/profile.xml',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : [],
            'descriptions_opts':"Path to profile relative to project dir",
        },
    }
    ,
    'dico_wix_icon':
    {
        'options':
        {

            'default_value' : '',
            'commandline_prj_opts': True,
            'commandline_opts': False,
            'allowed_values' : [],
            'descriptions_opts':"Path to icon relative to project dir",
        },
    }

}

def get_dico_prj(dico, type):
    return dico[type]

def get_dico_prj_options(dico):
    res = {}
    for prj, attr in dico.items():

        if attr.has_key('options'):
            prj = prj.replace('dico_', '')
            prj = prj.upper()
            res[prj] = attr['options']

    return res

<|endoftext|>


<commit_before># ***************************************************************************
# *   Copyright (c) 2016 Bernd Hahnebach <bernd@bimstatik.org>              *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   This program is distributed in the hope that it will be useful,       *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with this program; if not, write to the Free Software   *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************

__title__ = "FreeCAD FEM mesh gmsh ViewProvider for the document object"
__author__ = "Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"

## @package view_mesh_gmsh
#  \ingroup FEM
#  \brief view provider for mesh gmsh object

import FreeCAD
import FreeCADGui

import FemGui
from femtaskpanels import task_mesh_gmsh
from femtools.femutils import is_of_type
# from . import view_base_femobject

# TODO use VPBaseFemObject from view_base_femobject
# class VPMeshGmsh(view_base_femobject.VPBaseFemObject):
class VPMeshGmsh:
    """
    A View Provider for the MeshGmsh object
    """

    def __init__(self, vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/FEM_MeshGmshFromShape.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def updateData(self, obj, prop):
        return

    def onChanged(self, vobj, prop):
        return

    def setEdit(self, vobj, mode):
        # hide all FEM meshes and VTK FemPost* objects
        for o in vobj.Object.Document.Objects:
            if (
                o.isDerivedFrom("Fem::FemMeshObject")
                or o.isDerivedFrom("Fem::FemPostPipeline")
                or o.isDerivedFrom("Fem::FemPostClipFilter")
                or o.isDerivedFrom("Fem::FemPostScalarClipFilter")
                or o.isDerivedFrom("Fem::FemPostWarpVectorFilter")
                or o.isDerivedFrom("Fem::FemPostDataAlongLineFilter")
                or o.isDerivedFrom("Fem::FemPostDataAtPointFilter")
                or o.isDerivedFrom("Fem::FemPostCutFilter")
                or o.isDerivedFrom("Fem::FemPostDataAlongLineFilter")
                or o.isDerivedFrom("Fem::FemPostPlaneFunction")
                or o.isDerivedFrom("Fem::FemPostSphereFunction")
            ):
                o.ViewObject.hide()
        # show the mesh we like to edit
        self.ViewObject.show()
        # show task panel
        taskd = task_mesh_gmsh._TaskPanel(self.Object)
        # taskd.obj = vobj.Object
        FreeCADGui.Control.showDialog(taskd)
        return True

    """
    def setEdit(self, vobj, mode=0):
        view_base_femconstraint.VPBaseFemConstraint.setEdit(
            self,
            vobj,
            mode,
            _TaskPanel
        )
    """

    # overwrite unsetEdit, hide mesh object on task panel exit
    def unsetEdit(self, vobj, mode):
        FreeCADGui.Control.closeDialog()
        self.ViewObject.hide()
        return True

    def doubleClicked(self, vobj):
        # Group meshing is only active on active analysis
        # we should make sure the analysis the mesh belongs too is active
        gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
        if not gui_doc.getInEdit():
            # may be go the other way around and just activate the
            # analysis the user has doubleClicked on ?!
            # not a fast one, we need to iterate over all member of all
            # analysis to know to which analysis the object belongs too!!!
            # first check if there is an analysis in the active document
            found_an_analysis = False
            for o in gui_doc.Document.Objects:
                if o.isDerivedFrom("Fem::FemAnalysisPython"):
                        found_an_analysis = True
                        break
            if found_an_analysis:
                if FemGui.getActiveAnalysis() is not None:
                    if FemGui.getActiveAnalysis().Document is FreeCAD.ActiveDocument:
                        if self.Object in FemGui.getActiveAnalysis().Group:
                            if not gui_doc.getInEdit():
                                gui_doc.setEdit(vobj.Object.Name)
                            else:
                                FreeCAD.Console.PrintError(
                                    "Activate the analysis this Gmsh FEM "
                                    "mesh object belongs too!\n"
                                )
                        else:
                            FreeCAD.Console.PrintMessage(
                                "Gmsh FEM mesh object does not belong to the active analysis.\n"
                            )
                            found_mesh_analysis = False
                            for o in gui_doc.Document.Objects:
                                if o.isDerivedFrom("Fem::FemAnalysisPython"):
                                    for m in o.Group:
                                        if m == self.Object:
                                            found_mesh_analysis = True
                                            FemGui.setActiveAnalysis(o)
                                            FreeCAD.Console.PrintMessage(
                                                "The analysis the Gmsh FEM mesh object "
                                                "belongs to was found and activated: {}\n"
                                                .format(o.Name)
                                            )
                                            gui_doc.setEdit(vobj.Object.Name)
                                            break
                            if not found_mesh_analysis:
                                FreeCAD.Console.PrintMessage(
                                    "Gmsh FEM mesh object does not belong to an analysis. "
                                    "Analysis group meshing will be deactivated.\n"
                                )
                                gui_doc.setEdit(vobj.Object.Name)
                    else:
                        FreeCAD.Console.PrintError("Active analysis is not in active document.\n")
                else:
                    FreeCAD.Console.PrintMessage(
                        "No active analysis in active document, "
                        "we are going to have a look if the Gmsh FEM mesh object "
                        "belongs to a non active analysis.\n"
                    )
                    found_mesh_analysis = False
                    for o in gui_doc.Document.Objects:
                        if o.isDerivedFrom("Fem::FemAnalysisPython"):
                            for m in o.Group:
                                if m == self.Object:
                                    found_mesh_analysis = True
                                    FemGui.setActiveAnalysis(o)
                                    FreeCAD.Console.PrintMessage(
                                        "The analysis the Gmsh FEM mesh object "
                                        "belongs to was found and activated: {}\n"
                                        .format(o.Name)
                                    )
                                    gui_doc.setEdit(vobj.Object.Name)
                                    break
                    if not found_mesh_analysis:
                        FreeCAD.Console.PrintMessage(
                            "Gmsh FEM mesh object does not belong to an analysis. "
                            "Analysis group meshing will be deactivated.\n"
                        )
                        gui_doc.setEdit(vobj.Object.Name)
            else:
                FreeCAD.Console.PrintMessage("No analysis in the active document.\n")
                gui_doc.setEdit(vobj.Object.Name)
        else:
            from PySide.QtGui import QMessageBox
            message = "Active Task Dialog found! Please close this one before opening  a new one!"
            QMessageBox.critical(None, "Error in tree view", message)
            FreeCAD.Console.PrintError(message + "\n")
        return True

    def __getstate__(self):
        return None

    def __setstate__(self, state):
        return None

    def claimChildren(self):
        reg_childs = self.Object.MeshRegionList
        gro_childs = self.Object.MeshGroupList
        bou_childs = self.Object.MeshBoundaryLayerList
        return (reg_childs + gro_childs + bou_childs)

    def onDelete(self, feature, subelements):
        children = self.claimChildren()
        if len(children) > 0:
            try:
                for obj in children:
                    obj.ViewObject.show()
            except Exception as err:
                FreeCAD.Console.PrintError("Error in onDelete: {0} \n".format(err))
        return True

    def canDragObjects(self):
        return True

    def canDropObjects(self):
        return True

    def canDragObject(self, dragged_object):
        if (
            is_of_type(dragged_object, "Fem::MeshBoundaryLayer")
            or is_of_type(dragged_object, "Fem::MeshGroup")
            or is_of_type(dragged_object, "Fem::MeshRegion")
        ):
            return True
        else:
            return False

    def canDropObject(self, incoming_object):
        return True

    def dragObject(self, selfvp, dragged_object):
        if is_of_type(dragged_object, "Fem::MeshBoundaryLayer"):
            objs = self.Object.MeshBoundaryLayerList
            objs.remove(dragged_object)
            self.Object.MeshBoundaryLayerList = objs
        elif is_of_type(dragged_object, "Fem::MeshGroup"):
            objs = self.Object.MeshGroupList
            objs.remove(dragged_object)
            self.Object.MeshGroupList = objs
        elif is_of_type(dragged_object, "Fem::MeshRegion"):
            objs = self.Object.MeshRegionList
            objs.remove(dragged_object)
            self.Object.MeshRegionList = objs

    def dropObject(self, selfvp, incoming_object):
        if is_of_type(incoming_object, "Fem::MeshBoundaryLayer"):
            objs = self.Object.MeshBoundaryLayerList
            objs.append(incoming_object)
            self.Object.MeshBoundaryLayerList = objs
        elif is_of_type(incoming_object, "Fem::MeshGroup"):
            objs = self.Object.MeshGroupList
            objs.append(incoming_object)
            self.Object.MeshGroupList = objs
        elif is_of_type(incoming_object, "Fem::MeshRegion"):
            objs = self.Object.MeshRegionList
            objs.append(incoming_object)
            self.Object.MeshRegionList = objs
        incoming_object.Document.recompute()
<commit_msg>FEM: gmsh view provider, small improvements<commit_after># ***************************************************************************
# *   Copyright (c) 2016 Bernd Hahnebach <bernd@bimstatik.org>              *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   This program is distributed in the hope that it will be useful,       *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with this program; if not, write to the Free Software   *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************

__title__ = "FreeCAD FEM mesh gmsh ViewProvider for the document object"
__author__ = "Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"

## @package view_mesh_gmsh
#  \ingroup FEM
#  \brief view provider for mesh gmsh object

import FreeCAD
import FreeCADGui

import FemGui
from femtaskpanels import task_mesh_gmsh
from femtools.femutils import is_of_type
# from . import view_base_femobject

# TODO use VPBaseFemObject from view_base_femobject
# class VPMeshGmsh(view_base_femobject.VPBaseFemObject):
class VPMeshGmsh:
    """
    A View Provider for the MeshGmsh object
    """

    def __init__(self, vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/FEM_MeshGmshFromShape.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def updateData(self, obj, prop):
        return

    def onChanged(self, vobj, prop):
        return

    def setEdit(self, vobj, mode):
        # hide all FEM meshes and VTK FemPost* objects
        for o in vobj.Object.Document.Objects:
            if (
                o.isDerivedFrom("Fem::FemMeshObject")
                or o.isDerivedFrom("Fem::FemPostPipeline")
                or o.isDerivedFrom("Fem::FemPostClipFilter")
                or o.isDerivedFrom("Fem::FemPostScalarClipFilter")
                or o.isDerivedFrom("Fem::FemPostWarpVectorFilter")
                or o.isDerivedFrom("Fem::FemPostDataAlongLineFilter")
                or o.isDerivedFrom("Fem::FemPostDataAtPointFilter")
                or o.isDerivedFrom("Fem::FemPostCutFilter")
                or o.isDerivedFrom("Fem::FemPostDataAlongLineFilter")
                or o.isDerivedFrom("Fem::FemPostPlaneFunction")
                or o.isDerivedFrom("Fem::FemPostSphereFunction")
            ):
                o.ViewObject.hide()
        # show the mesh we like to edit
        self.ViewObject.show()
        # show task panel
        taskd = task_mesh_gmsh._TaskPanel(self.Object)
        # taskd.obj = vobj.Object
        FreeCADGui.Control.showDialog(taskd)
        return True

    """
    def setEdit(self, vobj, mode=0):
        view_base_femconstraint.VPBaseFemConstraint.setEdit(
            self,
            vobj,
            mode,
            _TaskPanel
        )
    """

    # overwrite unsetEdit, hide mesh object on task panel exit
    def unsetEdit(self, vobj, mode):
        FreeCADGui.Control.closeDialog()
        self.ViewObject.hide()
        return True

    def doubleClicked(self, vobj):
        # Group meshing is only active on active analysis
        # we should make sure the analysis the mesh belongs too is active
        gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
        if not gui_doc.getInEdit():
            # may be go the other way around and just activate the
            # analysis the user has doubleClicked on ?!
            # not a fast one, we need to iterate over all member of all
            # analysis to know to which analysis the object belongs too!!!
            # first check if there is an analysis in the active document
            found_an_analysis = False
            for o in gui_doc.Document.Objects:
                if o.isDerivedFrom("Fem::FemAnalysisPython"):
                        found_an_analysis = True
                        break
            if found_an_analysis:
                if FemGui.getActiveAnalysis() is not None:
                    if FemGui.getActiveAnalysis().Document is FreeCAD.ActiveDocument:
                        if self.Object in FemGui.getActiveAnalysis().Group:
                            if not gui_doc.getInEdit():
                                gui_doc.setEdit(vobj.Object.Name)
                            else:
                                FreeCAD.Console.PrintError(
                                    "Activate the analysis this Gmsh FEM "
                                    "mesh object belongs too!\n"
                                )
                        else:
                            FreeCAD.Console.PrintMessage(
                                "Gmsh FEM mesh object does not belong to the active analysis.\n"
                            )
                            found_mesh_analysis = False
                            for o in gui_doc.Document.Objects:
                                if o.isDerivedFrom("Fem::FemAnalysisPython"):
                                    for m in o.Group:
                                        if m == self.Object:
                                            found_mesh_analysis = True
                                            FemGui.setActiveAnalysis(o)
                                            FreeCAD.Console.PrintMessage(
                                                "The analysis the Gmsh FEM mesh object "
                                                "belongs to was found and activated: {}\n"
                                                .format(o.Name)
                                            )
                                            gui_doc.setEdit(vobj.Object.Name)
                                            break
                            if not found_mesh_analysis:
                                FreeCAD.Console.PrintLog(
                                    "Gmsh FEM mesh object does not belong to an analysis. "
                                    "Analysis group meshing can not be used.\n"
                                )
                                gui_doc.setEdit(vobj.Object.Name)
                    else:
                        FreeCAD.Console.PrintError("Active analysis is not in active document.\n")
                else:
                    FreeCAD.Console.PrintLog(
                        "No active analysis in active document, "
                        "we are going to have a look if the Gmsh FEM mesh object "
                        "belongs to a non active analysis.\n"
                    )
                    found_mesh_analysis = False
                    for o in gui_doc.Document.Objects:
                        if o.isDerivedFrom("Fem::FemAnalysisPython"):
                            for m in o.Group:
                                if m == self.Object:
                                    found_mesh_analysis = True
                                    FemGui.setActiveAnalysis(o)
                                    FreeCAD.Console.PrintMessage(
                                        "The analysis the Gmsh FEM mesh object "
                                        "belongs to was found and activated: {}\n"
                                        .format(o.Name)
                                    )
                                    gui_doc.setEdit(vobj.Object.Name)
                                    break
                    if not found_mesh_analysis:
                        FreeCAD.Console.PrintLog(
                            "Gmsh FEM mesh object does not belong to an analysis. "
                            "Analysis group meshing can not be used.\n"
                        )
                        gui_doc.setEdit(vobj.Object.Name)
            else:
                FreeCAD.Console.PrintLog("No analysis in the active document.\n")
                gui_doc.setEdit(vobj.Object.Name)
        else:
            from PySide.QtGui import QMessageBox
            message = "Active Task Dialog found! Please close this one before opening  a new one!"
            QMessageBox.critical(None, "Error in tree view", message)
            FreeCAD.Console.PrintError(message + "\n")
        return True

    def __getstate__(self):
        return None

    def __setstate__(self, state):
        return None

    def claimChildren(self):
        reg_childs = self.Object.MeshRegionList
        gro_childs = self.Object.MeshGroupList
        bou_childs = self.Object.MeshBoundaryLayerList
        return (reg_childs + gro_childs + bou_childs)

    def onDelete(self, feature, subelements):
        children = self.claimChildren()
        if len(children) > 0:
            try:
                for obj in children:
                    obj.ViewObject.show()
            except Exception as err:
                FreeCAD.Console.PrintError("Error in onDelete: {0} \n".format(err))
        return True

    def canDragObjects(self):
        return True

    def canDropObjects(self):
        return True

    def canDragObject(self, dragged_object):
        if (
            is_of_type(dragged_object, "Fem::MeshBoundaryLayer")
            or is_of_type(dragged_object, "Fem::MeshGroup")
            or is_of_type(dragged_object, "Fem::MeshRegion")
        ):
            return True
        else:
            return False

    def canDropObject(self, incoming_object):
        return True

    def dragObject(self, selfvp, dragged_object):
        if is_of_type(dragged_object, "Fem::MeshBoundaryLayer"):
            objs = self.Object.MeshBoundaryLayerList
            objs.remove(dragged_object)
            self.Object.MeshBoundaryLayerList = objs
        elif is_of_type(dragged_object, "Fem::MeshGroup"):
            objs = self.Object.MeshGroupList
            objs.remove(dragged_object)
            self.Object.MeshGroupList = objs
        elif is_of_type(dragged_object, "Fem::MeshRegion"):
            objs = self.Object.MeshRegionList
            objs.remove(dragged_object)
            self.Object.MeshRegionList = objs

    def dropObject(self, selfvp, incoming_object):
        if is_of_type(incoming_object, "Fem::MeshBoundaryLayer"):
            objs = self.Object.MeshBoundaryLayerList
            objs.append(incoming_object)
            self.Object.MeshBoundaryLayerList = objs
        elif is_of_type(incoming_object, "Fem::MeshGroup"):
            objs = self.Object.MeshGroupList
            objs.append(incoming_object)
            self.Object.MeshGroupList = objs
        elif is_of_type(incoming_object, "Fem::MeshRegion"):
            objs = self.Object.MeshRegionList
            objs.append(incoming_object)
            self.Object.MeshRegionList = objs
        incoming_object.Document.recompute()
<|endoftext|>


<commit_before>#!/usr/bin/env python

#* ***** BEGIN LICENSE BLOCK *****
#* Version: MPL 1.1/GPL 2.0/LGPL 2.1
#*
#* The contents of this file are subject to the Mozilla Public License Version
#* 1.1 (the "License"); you may not use this file except in compliance with
#* the License. You may obtain a copy of the License at
#* http://www.mozilla.org/MPL/
#*
#* Software distributed under the License is distributed on an "AS IS" basis,
#* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
#* for the specific language governing rights and limitations under the
#* License.
#*
#* The Original Code is [Open Source Virtual Machine.].
#*
#* The Initial Developer of the Original Code is
#* Adobe System Incorporated.
#* Portions created by the Initial Developer are Copyright (C) 2009
#* the Initial Developer. All Rights Reserved.
#*
#* Contributor(s):
#*   Adobe AS3 Team
#*
#* Alternatively, the contents of this file may be used under the terms of
#* either the GNU General Public License Version 2 or later (the "GPL"), or
#* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
#* in which case the provisions of the GPL or the LGPL are applicable instead
#* of those above. If you wish to allow use of your version of this file only
#* under the terms of either the GPL or the LGPL, and not to allow others to
#* use your version of this file under the terms of the MPL, indicate your
#* decision by deleting the provisions above and replace them with the notice
#* and other provisions required by the GPL or the LGPL. If you do not delete
#* the provisions above, a recipient may use your version of this file under
#* the terms of any one of the MPL, the GPL or the LGPL.
#*
#* ***** END LICENSE BLOCK ***** */
#
import os,re,subprocess,os.path,sys

class RunTestLib:
    "base class to run cmdline tests"

    __shared_state = {}

    def __init__(self):
        self.__dict__=self.__shared_state
        if self.__shared_state=={}:
            self.firstinit()

    def firstinit(self):
        self.verbose=False
        self.avm=self.checkenv('AVM','path to vm shell')
        self.avmrd=self.checkenv('AVMRD','path to debugger vm shell',False)
        self.asc=self.checkenv('ASC','path to actionscript compiler asc.jar')
        self.gabc=self.checkenv('GLOBALABC','path to core/builtin.abc')
        self.sabc=self.checkenv('SHELLABC','path to shell/shell_toplevel.abc')
        self.loadConfig()

    def loadConfig(self):
        file=open('testconfig.txt')
        self.testconfig={}
        for line in file:
            if len(line.strip())==0 or line.strip().startswith('#'):
                continue
            fields=line.split(',')
            if len(fields)<3:
                print "incorrect number of fields in line '%s'" % line
                continue
            self.testconfig[fields[0].strip()]=(fields[1].strip(),fields[2].strip())

    def checkenv(self,env,desc='',required=True):
        val=None
        if os.environ.has_key(env):
            val=os.environ[env]
        if val==None:
            if required:
                print "required environment variable '%s' is not set... it is '%s'" % (env,desc)
                sys.exit(1)
            print "optional environment variable '%s' is not set ... it is '%s'" % (env,desc)
        else:
            val=val.strip()
        return val

    def run_command(self,cwd,command,input=None):
        self.verbose_print(command)
        if cwd==None:
            cwd=os.getcwd()
        proc = subprocess.Popen(command.split(), stdout=subprocess.PIPE,stdin=subprocess.PIPE, shell=False,cwd=cwd)
        if input!=None:
            proc.stdin.write(input)
        (stdo,stde)=proc.communicate()
        return (proc.returncode,stdo,stde)

    def compile(self,file,imports=None,args=None):
        print "compiling %s" % file
        if imports==None:
            imports="-import %s -import %s" % (self.gabc,self.sabc)
        if args==None:
            args=''
        cmd="java -jar %s %s %s %s" % (self.asc,imports,args,file)
        cwd=os.getcwd()
        (exitcode,stdo,stde)=self.run_command(cwd,cmd)
        if exitcode!=0:
            print "ERROR: compile error\nstdout=%s\nstderr-%s\n" % (stdo,stde)
            sys.exit(1)
        return (exitcode,stdo,stde)

    def set_verbose(self,v):
        self.verbose=v

    def verbose_print(self,msg):
        if self.verbose:
            print(msg)

    def replace_crlf(self,s):
        return s.replace('\r','<cr>').replace('\n','<lf>')

    def run_test(self,name,command,cwd=None,input=None,expectedout=None,expectederr=None,expectedcode=None):
        (actualcode,actualout,actualerr)=self.run_command(cwd,command,input)
        result=True
        msg=''
        if cwd:
            msg+="cwd: %s\n" % cwd
        msg+="command: %s\n" % command
        if input:
            msg+="input: %s\n" % input
        if expectedcode!=None:
            if expectedcode==actualcode:
                msg+=' exit code matched %d\n' % actualcode
            else:
                result=False
                msg+=" exit code expected '%d' got '%d'\n" % (expectedcode,actualcode)
        elif self.verbose:
            msg+=" exit code=%d\n" % actualcode
        if expectedout!=None:
            for eout in expectedout:
                if re.search(eout,actualout):
                    msg+=" output matched expected '%s'\n" % eout
                else:
                    result=False
                    msg+=" output failed to match '%s'\n" % (eout)
        if (self.verbose or result==False) and actualout!=None:
            if len(actualout)>80:
                msg+="[OUTPUT START]\n%s\n[OUTPUT END]\n" % actualout
            else:
                msg+="output='%s'\n" % actualout

        if expectederr!=None:
            for eerr in expectederr:
                if p1.search(eerr,actualerr):
                    msg+=" error matched expected '%s'\n" % eerr
                else:
                    result=False
                    msg+=" error failed to match '%s'\n" % (eerr)
            if (self.verbose or result==False) and actualerr!=None:
                if len(actualerr)>80:
                    msg+="[START STDERR]\n%s\n[END STDERR]\n" % actualerr
                else:
                    msg+="stderr='%s'\n" % actualerr

        msg=name + " " + msg

        if os.path.exists("%s.output"%name):
            os.remove("%s.output"%name)

        type='normal'
        if self.testconfig.has_key(name):
            (type,notes)=self.testconfig[name]
        if type=='skip':
            msg=msg + " SKIPPED, result %s" % result
            print "%-30s SKIPPED, result %s" % (name,result)
        elif result and type=='normal':
            msg=msg + " PASSED"
            print "%-30s PASSED" % name
        elif result and type=='expectfail':
            msg=msg + " UNEXPECTED PASS : %s" % notes
            print "%-30s UNEXPECTED PASSED : %s" % name
        elif result==False  and type=='expectfail':
            msg=msg + " EXPECTED FAIL " + notes
            print "%-30s EXPECTED FAIL, see %s.output" % (name,name)
        else:
            msg=msg + " FAILED"
            print "%-30s FAILED, see %s.output" % (name,name)
        if result==False:
            out_file=open("%s.output"%name,"w")
            out_file.write(msg)
            out_file.close()

if __name__ == "__main__":
    rt=RunTestLib()
#    rt.run_test("test1",avm,expectedcode=1,expectedout=['avmplus shell','\[-Dforcemir]'])
    rt.run_command(None,'%s -d debug.abc' % rt.avm,'quit\n')
<commit_msg>minor fixes to commandline tests<commit_after>#!/usr/bin/env python

#* ***** BEGIN LICENSE BLOCK *****
#* Version: MPL 1.1/GPL 2.0/LGPL 2.1
#*
#* The contents of this file are subject to the Mozilla Public License Version
#* 1.1 (the "License"); you may not use this file except in compliance with
#* the License. You may obtain a copy of the License at
#* http://www.mozilla.org/MPL/
#*
#* Software distributed under the License is distributed on an "AS IS" basis,
#* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
#* for the specific language governing rights and limitations under the
#* License.
#*
#* The Original Code is [Open Source Virtual Machine.].
#*
#* The Initial Developer of the Original Code is
#* Adobe System Incorporated.
#* Portions created by the Initial Developer are Copyright (C) 2009
#* the Initial Developer. All Rights Reserved.
#*
#* Contributor(s):
#*   Adobe AS3 Team
#*
#* Alternatively, the contents of this file may be used under the terms of
#* either the GNU General Public License Version 2 or later (the "GPL"), or
#* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
#* in which case the provisions of the GPL or the LGPL are applicable instead
#* of those above. If you wish to allow use of your version of this file only
#* under the terms of either the GPL or the LGPL, and not to allow others to
#* use your version of this file under the terms of the MPL, indicate your
#* decision by deleting the provisions above and replace them with the notice
#* and other provisions required by the GPL or the LGPL. If you do not delete
#* the provisions above, a recipient may use your version of this file under
#* the terms of any one of the MPL, the GPL or the LGPL.
#*
#* ***** END LICENSE BLOCK ***** */
#
import os,re,subprocess,os.path,sys

class RunTestLib:
    "base class to run cmdline tests"

    __shared_state = {}

    def __init__(self):
        self.__dict__=self.__shared_state
        if self.__shared_state=={}:
            self.firstinit()

    def firstinit(self):
        self.verbose=True
        self.avm=self.checkenv('AVM','path to vm shell')
        self.avmrd=self.checkenv('AVMRD','path to debugger vm shell',False)
        self.asc=self.checkenv('ASC','path to actionscript compiler asc.jar')
        self.gabc=self.checkenv('GLOBALABC','path to core/builtin.abc')
        self.sabc=self.checkenv('SHELLABC','path to shell/shell_toplevel.abc')
        self.loadConfig()

    def loadConfig(self):
        file=open('testconfig.txt')
        self.testconfig={}
        for line in file:
            if len(line.strip())==0 or line.strip().startswith('#'):
                continue
            fields=line.split(',')
            if len(fields)<3:
                print "incorrect number of fields in line '%s'" % line
                continue
            self.testconfig[fields[0].strip()]=(fields[1].strip(),fields[2].strip())

    def checkenv(self,env,desc='',required=True):
        val=None
        if os.environ.has_key(env):
            val=os.environ[env]
        if val==None:
            if required:
                print "required environment variable '%s' is not set... it is '%s'" % (env,desc)
                sys.exit(1)
            print "optional environment variable '%s' is not set ... it is '%s'" % (env,desc)
        else:
            val=val.strip()
        return val

    def run_command(self,cwd,command,input=None):
        self.verbose_print(command)
        if cwd==None:
            cwd=os.getcwd()
        proc = subprocess.Popen(command.split(), stdout=subprocess.PIPE,stdin=subprocess.PIPE, shell=False,cwd=cwd)
        if input!=None:
            proc.stdin.write(input)
        (stdo,stde)=proc.communicate()
        return (proc.returncode,stdo,stde)

    def compile(self,file,imports=None,args=None):
        print "compiling %s" % file
        if imports==None:
            imports="-import %s -import %s" % (self.gabc,self.sabc)
        if args==None:
            args=''
        cmd="java -jar %s %s %s %s" % (self.asc,imports,args,file)
        cwd=os.getcwd()
        (exitcode,stdo,stde)=self.run_command(cwd,cmd)
        if exitcode!=0:
            print "ERROR: compile error\nstdout=%s\nstderr-%s\n" % (stdo,stde)
            sys.exit(1)
        return (exitcode,stdo,stde)

    def set_verbose(self,v):
        self.verbose=v

    def verbose_print(self,msg):
        if self.verbose:
            print(msg)

    def replace_crlf(self,s):
        return s.replace('\r','<cr>').replace('\n','<lf>')

    def run_test(self,name,command,cwd=None,input=None,expectedout=None,expectederr=None,expectedcode=None):
        (actualcode,actualout,actualerr)=self.run_command(cwd,command,input)
        result=True
        msg=''
        if cwd:
            msg+="cwd: %s\n" % cwd
        msg+="command: %s\n" % command
        if input:
            msg+="input: %s\n" % input
        if expectedcode!=None:
            if expectedcode==actualcode:
                msg+=' exit code matched %d\n' % actualcode
            else:
                result=False
                msg+=" exit code expected '%d' got '%d'\n" % (expectedcode,actualcode)
        elif self.verbose:
            msg+=" exit code=%d\n" % actualcode
        if expectedout!=None:
            for eout in expectedout:
                if re.search(eout,actualout):
                    msg+=" output matched expected '%s'\n" % eout
                else:
                    result=False
                    msg+=" output failed to match '%s'\n" % (eout)
        if (self.verbose or result==False) and actualout!=None:
            if len(actualout)>80:
                msg+="[OUTPUT START]\n%s\n[OUTPUT END]\n" % actualout
            else:
                msg+="output='%s'\n" % actualout

        if expectederr!=None:
            for eerr in expectederr:
                if p1.search(eerr,actualerr):
                    msg+=" error matched expected '%s'\n" % eerr
                else:
                    result=False
                    msg+=" error failed to match '%s'\n" % (eerr)
            if (self.verbose or result==False) and actualerr!=None:
                if len(actualerr)>80:
                    msg+="[START STDERR]\n%s\n[END STDERR]\n" % actualerr
                else:
                    msg+="stderr='%s'\n" % actualerr

        msg=name + " " + msg

        if os.path.exists("%s.output"%name):
            os.remove("%s.output"%name)

        type='normal'
        if self.testconfig.has_key(name):
            (type,notes)=self.testconfig[name]
        if type=='skip':
            msg=msg + " SKIPPED, result %s" % result
            print "%-30s SKIPPED, result %s" % (name,result)
        elif result and type=='normal':
            msg=msg + " PASSED"
            print "%-30s PASSED" % name
        elif result and type=='expectfail':
            msg=msg + " UNEXPECTED PASS : %s" % notes
            print "%-30s UNEXPECTED PASS : %s" % name
        elif result==False  and type=='expectfail':
            msg=msg + " EXPECTED FAIL " + notes
            print "%-30s EXPECTED FAIL, see %s.output" % (name,name)
        else:
            msg=msg + " FAILED"
            print "%-30s FAILED, see %s.output" % (name,name)
        if result==False:
            out_file=open("%s.output"%name,"w")
            out_file.write(msg)
            out_file.close()

if __name__ == "__main__":
    rt=RunTestLib()
#    rt.run_test("test1",avm,expectedcode=1,expectedout=['avmplus shell','\[-Dforcemir]'])
    rt.run_command(None,'%s -d debug.abc' % rt.avm,'quit\n')
<|endoftext|>


<commit_before>#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains the ProposalDuplicates Model.
"""

__authors__ = [
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  '"Lennard de Rijk" <ljvderijk@gmail.com>',
]

from google.appengine.ext import db

import soc.models.base

import soc.modules.gsoc.models.program
import soc.modules.gsoc.models.student

class ProposalDuplicate(soc.models.base.ModelWithFieldAttributes):
  """Model used to store the duplicate proposals for a student
     in a Project-Based Program.
  """

  #: Program in which this duplicates exist
  program = db.ReferenceProperty(
      reference_class=soc.modules.gsoc.models.program.GSoCProgram,
      required=True, collection_name='duplicate_proposals')

  #: Student who has these duplicates
  student = db.ReferenceProperty(
      reference_class=soc.modules.gsoc.models.student.GSoCStudent,
      required=True, collection_name='students_duplicates')

  #: List of organizations to which the proposals belong to
  orgs = db.ListProperty(item_type=db.Key, default=[])

  #: List of all proposals that would be accepted for this student
  duplicates = db.ListProperty(item_type=db.Key, default=[])
<commit_msg>Added property to quickly check wether or not a PD entity really has duplicates.<commit_after>#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains the ProposalDuplicates Model.
"""

__authors__ = [
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  '"Lennard de Rijk" <ljvderijk@gmail.com>',
]

from google.appengine.ext import db

import soc.models.base

import soc.modules.gsoc.models.program
import soc.modules.gsoc.models.student

class ProposalDuplicate(soc.models.base.ModelWithFieldAttributes):
  """Model used to store the duplicate proposals for a student
     in a Project-Based Program.
  """

  #: Program in which this duplicates exist
  program = db.ReferenceProperty(
      reference_class=soc.modules.gsoc.models.program.GSoCProgram,
      required=True, collection_name='duplicate_proposals')

  #: Student who has these duplicates
  student = db.ReferenceProperty(
      reference_class=soc.modules.gsoc.models.student.GSoCStudent,
      required=True, collection_name='students_duplicates')

  #: List of organizations to which the proposals belong to
  orgs = db.ListProperty(item_type=db.Key, default=[])

  #: List of all proposals that would be accepted for this student
  duplicates = db.ListProperty(item_type=db.Key, default=[])

  #: Property which specifies if number of proposals in duplicates
  #: is more than allowed amount of the program.
  is_duplicate = db.BooleanProperty(required=True, default=False)
<|endoftext|>


<commit_before>"""
Constructing Adaptive Configuration Dialogs using Crowd Data
"""

import os
import logging
import subprocess
from collections import defaultdict
from functools import reduce
from operator import mul

from sortedcontainers import SortedSet, SortedListWithKey

from .freq_table import FrequencyTable
from .assoc_rules import AssociationRuleMiner

def get_version():
    """Get the version string.

    Returns:
        The version string.
    """
    pkg_dir = os.path.dirname(__file__)
    src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
    git_dir = os.path.join(src_dir, ".git")
    try:
        # Try to get the  version string dynamically from Git.
        git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir,
                    "describe", "--tags", "--dirty")
        with open(os.devnull, "w") as devnull:
            version = subprocess.check_output(git_args, stderr=devnull).strip()
    except subprocess.CalledProcessError:
        # Overwritten by a custom 'python setup.py sdist/build' command.
        version = None
    return version

__version__ = get_version()

class ConfigDialog(object):
    """Adaptive configuration dialog.

    This is the base class of all the configuration dialogs defined in
    the package (not intented to be instantiated directly). It defines
    a common interface followed by the dialogs generated using the
    different ConfigDiagBuilder subclasses.
    """

    def __init__(self):
        """Initialize a new instance.
        """
        super().__init__()

class ConfigDialogBuilder(object):
    """Adaptive configuration dialog builder.
    """

    def __init__(self, config_sample=None,
                 config_values=None,
                 assoc_rule_algorithm="apriori",
                 assoc_rule_min_support=0.5,
                 assoc_rule_min_confidence=0.95):
        """Initialize a new instance.

        Arguments:
            config_sample: A 2-dimensional numpy array containing a
                sample of the configuration variables.
            config_values: A list with one entry for each variable
                containing a list with all the possible values of the
                variable. If it is not given, it is automatically
                computed from the columns of config_sample.
            assoc_rule_algorithm: Algorithm for mining the frequent
                item sets. Possible values are: 'apriori' (default)
                and 'fp-growth'.
            assoc_rule_min_supporte: Minimum item set support in [0,1]
                (default: 0.5).
            assoc_rule_min_confidence: Minimum confidence of the rules
                in [0,1] (default: 0.95).
        """
        super().__init__()
        self._config_sample = config_sample
        self._freq_tab = FrequencyTable(self._config_sample, cache_size=0)
        if config_values is None:
            config_values = [list(SortedSet(self._config_sample[:, i]))
                             for i in range(self._config_sample.shape[1])]
        self._config_values = config_values
        self._assoc_rule_algorithm = assoc_rule_algorithm
        self._assoc_rule_min_support = assoc_rule_min_support
        self._assoc_rule_min_confidence = assoc_rule_min_confidence
        self._logger = logging.getLogger(self.__class__.__name__)

    def build_dialog():
        """Construct an adaptive configuration dialog.

        Returns:
            An instance of a ConfigDialog subclass.
        """
        raise NotImplementedError()

    def _cond_prob(self, x, y, add_one_smoothing=True):
        # Conditional probability distributionn of x given y in the
        # sample of the configuration variables. By default the
        # frequencies are computed using add-one (Laplace) smoothing.
        z = dict(x.items() | y.items())
        num = self._freq_tab.count_freq(z)
        den = self._freq_tab.count_freq(y)
        if add_one_smoothing:
            num += 1
            x_card = [len(self._config_values[i]) for i in x.keys()]
            den += reduce(mul, x_card)
        prob = num / den
        return prob

    def _mine_rules(self):
        # Mine the association rules.
        self._logger.debug("mining association rules")
        miner = AssociationRuleMiner(self._config_sample)
        rules = miner.mine_assoc_rules(self._assoc_rule_min_support,
                                       self._assoc_rule_min_confidence,
                                       algorithm=self._assoc_rule_algorithm)
        if self._logger.isEnabledFor(logging.DEBUG):
            self._logger.debug("found %d rules", len(rules))
            supp = [rule.support for rule in rules]
            self._logger.debug("support values in [%.2f,%.2f]",
                               min(supp), max(supp))
            conf = [rule.confidence for rule in rules]
            self._logger.debug("confidence values in [%.2f,%.2f]",
                               min(conf), max(conf))
        # Merge rules with the same lhs. If two rules have
        # contradictory rhs, the rule with the greatest confidence
        # takes precedence.
        rule_sort_key = lambda rule: rule.confidence  # by inc. confidence
        rules_dict = defaultdict(lambda: SortedListWithKey(key=rule_sort_key))
        for rule in rules:
            lhs_key = hash(frozenset(rule.lhs.items()))
            rules_dict[lhs_key].add(rule)
        merged_rules = [reduce(self._merge_rules, grouped_rules)
                        for grouped_rules in rules_dict.values()]
        self._logger.debug("turned into %d rules after merging",
                           len(merged_rules))
        self._logger.debug("finished mining association rules")
        # Return the merged rules.
        return merged_rules

    def _merge_rules(self, rule1, rule2):
        # Merge two association rules with the same lhs.
        # rule1 is overwritten and returned.
        rule1.support = None
        rule1.confidence = None
        rule1.rhs.update(rule2.rhs)
        return rule1

    def _is_rule_lhs_compatible(self, rule, state):
        # Check if the rule's lhs is compatible with the given
        # configuration state. All the variables in the lhs have to
        # match the values in the state.
        return set(rule.lhs.items()) <= set(state.items())

    def _is_rule_rhs_compatible(self, rule, state):
        # Check if the rule's rhs is compatible with the given
        # configuration state. Each variable in the rhs has the same
        # value in the state or it's value is still unknown. At least
        # one variable must be unknown in order to apply the rule.
        one_unknown_var = False
        for var_index, var_value in rule.rhs.items():
            if var_index in state:
                if state[var_index] != var_value:
                    return False
            else:
                one_unknown_var = True
        return one_unknown_var

    def _is_rule_applicable(self, rule, state):
        # Check if a rule can be applied at a given configuration state.
        return (self._is_rule_lhs_compatible(rule, state) and
                self._is_rule_rhs_compatible(rule, state))
<commit_msg>Do not set default values in ConfigDialogBuilder<commit_after>"""
Constructing Adaptive Configuration Dialogs using Crowd Data
"""

import os
import logging
import subprocess
from collections import defaultdict
from functools import reduce
from operator import mul

from sortedcontainers import SortedSet, SortedListWithKey

from .freq_table import FrequencyTable
from .assoc_rules import AssociationRuleMiner

def get_version():
    """Get the version string.

    Returns:
        The version string.
    """
    pkg_dir = os.path.dirname(__file__)
    src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
    git_dir = os.path.join(src_dir, ".git")
    try:
        # Try to get the  version string dynamically from Git.
        git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir,
                    "describe", "--tags", "--dirty")
        with open(os.devnull, "w") as devnull:
            version = subprocess.check_output(git_args, stderr=devnull).strip()
    except subprocess.CalledProcessError:
        # Overwritten by a custom 'python setup.py sdist/build' command.
        version = None
    return version

__version__ = get_version()

class ConfigDialog(object):
    """Adaptive configuration dialog.

    This is the base class of all the configuration dialogs defined in
    the package (not intented to be instantiated directly). It defines
    a common interface followed by the dialogs generated using the
    different ConfigDiagBuilder subclasses.
    """

    def __init__(self):
        """Initialize a new instance.
        """
        super().__init__()

class ConfigDialogBuilder(object):
    """Adaptive configuration dialog builder.
    """

    def __init__(self, config_sample=None,
                 config_values=None,
                 assoc_rule_algorithm="apriori",
                 assoc_rule_min_support=None,
                 assoc_rule_min_confidence=None):
        """Initialize a new instance.

        Arguments:
            config_sample: A 2-dimensional numpy array containing a
                sample of the configuration variables.
            config_values: A list with one entry for each variable
                containing a list with all the possible values of the
                variable. If it is not given, it is automatically
                computed from the columns of config_sample.
            assoc_rule_algorithm: Algorithm for mining the frequent
                item sets. Possible values are: 'apriori' (default)
                and 'fp-growth'.
            assoc_rule_min_support: Minimum item set support in [0,1].
            assoc_rule_min_confidence: Minimum confidence in [0,1].
        """
        super().__init__()
        self._config_sample = config_sample
        self._freq_tab = FrequencyTable(self._config_sample, cache_size=0)
        if config_values is None:
            config_values = [list(SortedSet(self._config_sample[:, i]))
                             for i in range(self._config_sample.shape[1])]
        self._config_values = config_values
        self._assoc_rule_algorithm = assoc_rule_algorithm
        self._assoc_rule_min_support = assoc_rule_min_support
        self._assoc_rule_min_confidence = assoc_rule_min_confidence
        self._logger = logging.getLogger(self.__class__.__name__)

    def build_dialog():
        """Construct an adaptive configuration dialog.

        Returns:
            An instance of a ConfigDialog subclass.
        """
        raise NotImplementedError()

    def _cond_prob(self, x, y, add_one_smoothing=True):
        # Conditional probability distributionn of x given y in the
        # sample of the configuration variables. By default the
        # frequencies are computed using add-one (Laplace) smoothing.
        z = dict(x.items() | y.items())
        num = self._freq_tab.count_freq(z)
        den = self._freq_tab.count_freq(y)
        if add_one_smoothing:
            num += 1
            x_card = [len(self._config_values[i]) for i in x.keys()]
            den += reduce(mul, x_card)
        prob = num / den
        return prob

    def _mine_rules(self):
        # Mine the association rules.
        self._logger.debug("mining association rules")
        miner = AssociationRuleMiner(self._config_sample)
        rules = miner.mine_assoc_rules(self._assoc_rule_min_support,
                                       self._assoc_rule_min_confidence,
                                       algorithm=self._assoc_rule_algorithm)
        if self._logger.isEnabledFor(logging.DEBUG):
            self._logger.debug("found %d rules", len(rules))
            supp = [rule.support for rule in rules]
            self._logger.debug("support values in [%.2f,%.2f]",
                               min(supp), max(supp))
            conf = [rule.confidence for rule in rules]
            self._logger.debug("confidence values in [%.2f,%.2f]",
                               min(conf), max(conf))
        # Merge rules with the same lhs. If two rules have
        # contradictory rhs, the rule with the greatest confidence
        # takes precedence.
        rule_sort_key = lambda rule: rule.confidence  # by inc. confidence
        rules_dict = defaultdict(lambda: SortedListWithKey(key=rule_sort_key))
        for rule in rules:
            lhs_key = hash(frozenset(rule.lhs.items()))
            rules_dict[lhs_key].add(rule)
        merged_rules = [reduce(self._merge_rules, grouped_rules)
                        for grouped_rules in rules_dict.values()]
        self._logger.debug("turned into %d rules after merging",
                           len(merged_rules))
        self._logger.debug("finished mining association rules")
        # Return the merged rules.
        return merged_rules

    def _merge_rules(self, rule1, rule2):
        # Merge two association rules with the same lhs.
        # rule1 is overwritten and returned.
        rule1.support = None
        rule1.confidence = None
        rule1.rhs.update(rule2.rhs)
        return rule1

    def _is_rule_lhs_compatible(self, rule, state):
        # Check if the rule's lhs is compatible with the given
        # configuration state. All the variables in the lhs have to
        # match the values in the state.
        return set(rule.lhs.items()) <= set(state.items())

    def _is_rule_rhs_compatible(self, rule, state):
        # Check if the rule's rhs is compatible with the given
        # configuration state. Each variable in the rhs has the same
        # value in the state or it's value is still unknown. At least
        # one variable must be unknown in order to apply the rule.
        one_unknown_var = False
        for var_index, var_value in rule.rhs.items():
            if var_index in state:
                if state[var_index] != var_value:
                    return False
            else:
                one_unknown_var = True
        return one_unknown_var

    def _is_rule_applicable(self, rule, state):
        # Check if a rule can be applied at a given configuration state.
        return (self._is_rule_lhs_compatible(rule, state) and
                self._is_rule_rhs_compatible(rule, state))
<|endoftext|>


<commit_before>import collections
import warnings

import numpy

import cupy
from cupyx.jit import _compile
from cupyx.jit import _typerules
from cupyx.jit import _types

class _CudaFunction:
    """JIT cupy function object
    """

    def __init__(self, func, mode, device=False, inline=False):
        self.attributes = []

        if device:
            self.attributes.append('__device__')
        else:
            self.attributes.append('__global__')

        if inline:
            self.attributes.append('inline')

        self.name = getattr(func, 'name', func.__name__)
        self.func = func
        self.mode = mode

    def __call__(self, *args, **kwargs):
        raise NotImplementedError

    def _emit_code_from_types(self, in_types, ret_type=None):
        return _compile.transpile(
            self.func, self.attributes, self.mode, in_types, ret_type)

class _JitRawKernel:

    def __init__(self, func, mode):
        self._func = func
        self._mode = mode
        self._cache = {}
        self._cached_codes = {}

    def __call__(
            self, grid, block, args, shared_mem=0,
            stream=None, enable_cooperative_groups=False):
        in_types = []
        for x in args:
            if isinstance(x, cupy.ndarray):
                t = _types.CArray.from_ndarray(x)
            elif numpy.isscalar(x):
                t = _typerules.get_ctype_from_scalar(self._mode, x)
            else:
                raise TypeError(f'{type(x)} is not supported for RawKernel')
            in_types.append(t)
        in_types = tuple(in_types)

        kern = self._cache.get(in_types)
        if kern is None:
            result = _compile.transpile(
                self._func,
                ['extern "C"', '__global__'],
                self._mode,
                in_types,
                _types.Void(),
            )
            fname = result.func_name
            module = cupy._core.core.compile_with_cache(
                source=result.code,
                options=('-D CUPY_JIT_MODE',))
            kern = module.get_function(fname)
            self._cache[in_types] = kern
            self._cached_codes[in_types] = result.code

        kern(grid, block, args, shared_mem, stream, enable_cooperative_groups)

    def __getitem__(self, grid_and_block):
        grid, block = grid_and_block
        if not isinstance(grid, tuple):
            grid = (grid, 1, 1)
        if not isinstance(block, tuple):
            block = (block, 1, 1)
        return lambda *args, **kwargs: self(grid, block, args, **kwargs)

    @property
    def cached_codes(self):
        """Returns a dict that has input types as keys and codes values.

        This proprety method is for debugging purpose.
        The return value is not guaranteed to keep backward compatibility.
        """
        if len(self._cached_codes) == 0:
            warnings.warn(
                'No codes are cached because compilation is deferred until '
                'the first function call.')
        return self._cached_codes

    @property
    def cached_code(self):
        """Returns `next(iter(self.cached_codes.values()))`.

        This proprety method is for debugging purpose.
        The return value is not guaranteed to keep backward compatibility.
        """
        codes = self.cached_codes
        if len(codes) > 1:
            warnings.warn(
                'The input types of the kernel could not be inferred. '
                'Please use `.cached_codes` instead.')
        return next(iter(codes.values()))

def rawkernel(mode='cuda'):
    """A decorator compiles a Python function into CUDA kernel.
    """
    cupy._util.experimental('cupyx.jit.rawkernel')

    def wrapper(func):
        return _JitRawKernel(func, mode)
    return wrapper

Dim3 = collections.namedtuple('dim3', ['x', 'y', 'z'])

def _create_dim3(name):
    return Dim3(
        _compile.CudaObject(f'{name}.x', _types.uint32),
        _compile.CudaObject(f'{name}.y', _types.uint32),
        _compile.CudaObject(f'{name}.z', _types.uint32),
    )

threadIdx = _create_dim3('threadIdx')
blockDim = _create_dim3('blockDim')
blockIdx = _create_dim3('blockIdx')
gridDim = _create_dim3('gridDim')

syncthreads = _compile.SyncThreads()
shared_memory = _compile.SharedMemory()
<commit_msg>Use functools.update_wrapper<commit_after>import collections
import functools
import warnings

import numpy

import cupy
from cupyx.jit import _compile
from cupyx.jit import _typerules
from cupyx.jit import _types

class _CudaFunction:
    """JIT cupy function object
    """

    def __init__(self, func, mode, device=False, inline=False):
        self.attributes = []

        if device:
            self.attributes.append('__device__')
        else:
            self.attributes.append('__global__')

        if inline:
            self.attributes.append('inline')

        self.name = getattr(func, 'name', func.__name__)
        self.func = func
        self.mode = mode

    def __call__(self, *args, **kwargs):
        raise NotImplementedError

    def _emit_code_from_types(self, in_types, ret_type=None):
        return _compile.transpile(
            self.func, self.attributes, self.mode, in_types, ret_type)

class _JitRawKernel:

    def __init__(self, func, mode):
        self._func = func
        self._mode = mode
        self._cache = {}
        self._cached_codes = {}

    def __call__(
            self, grid, block, args, shared_mem=0,
            stream=None, enable_cooperative_groups=False):
        in_types = []
        for x in args:
            if isinstance(x, cupy.ndarray):
                t = _types.CArray.from_ndarray(x)
            elif numpy.isscalar(x):
                t = _typerules.get_ctype_from_scalar(self._mode, x)
            else:
                raise TypeError(f'{type(x)} is not supported for RawKernel')
            in_types.append(t)
        in_types = tuple(in_types)

        kern = self._cache.get(in_types)
        if kern is None:
            result = _compile.transpile(
                self._func,
                ['extern "C"', '__global__'],
                self._mode,
                in_types,
                _types.Void(),
            )
            fname = result.func_name
            module = cupy._core.core.compile_with_cache(
                source=result.code,
                options=('-D CUPY_JIT_MODE',))
            kern = module.get_function(fname)
            self._cache[in_types] = kern
            self._cached_codes[in_types] = result.code

        kern(grid, block, args, shared_mem, stream, enable_cooperative_groups)

    def __getitem__(self, grid_and_block):
        grid, block = grid_and_block
        if not isinstance(grid, tuple):
            grid = (grid, 1, 1)
        if not isinstance(block, tuple):
            block = (block, 1, 1)
        return lambda *args, **kwargs: self(grid, block, args, **kwargs)

    @property
    def cached_codes(self):
        """Returns a dict that has input types as keys and codes values.

        This proprety method is for debugging purpose.
        The return value is not guaranteed to keep backward compatibility.
        """
        if len(self._cached_codes) == 0:
            warnings.warn(
                'No codes are cached because compilation is deferred until '
                'the first function call.')
        return self._cached_codes

    @property
    def cached_code(self):
        """Returns `next(iter(self.cached_codes.values()))`.

        This proprety method is for debugging purpose.
        The return value is not guaranteed to keep backward compatibility.
        """
        codes = self.cached_codes
        if len(codes) > 1:
            warnings.warn(
                'The input types of the kernel could not be inferred. '
                'Please use `.cached_codes` instead.')
        return next(iter(codes.values()))

def rawkernel(mode='cuda'):
    """A decorator compiles a Python function into CUDA kernel.
    """
    cupy._util.experimental('cupyx.jit.rawkernel')

    def wrapper(func):
        return functools.update_wrapper(_JitRawKernel(func, mode), func)
    return wrapper

Dim3 = collections.namedtuple('dim3', ['x', 'y', 'z'])

def _create_dim3(name):
    return Dim3(
        _compile.CudaObject(f'{name}.x', _types.uint32),
        _compile.CudaObject(f'{name}.y', _types.uint32),
        _compile.CudaObject(f'{name}.z', _types.uint32),
    )

threadIdx = _create_dim3('threadIdx')
blockDim = _create_dim3('blockDim')
blockIdx = _create_dim3('blockIdx')
gridDim = _create_dim3('gridDim')

syncthreads = _compile.SyncThreads()
shared_memory = _compile.SharedMemory()
<|endoftext|>


<commit_before>from . import input
from .fmtstr import fmtstr
from . import events
from window import FullscreenWindow, CursorAwareWindow
import sys
import signal
import logging
from termhelpers import Cbreak
logging.basicConfig(filename='display.log',level=logging.DEBUG)

def simple_fullscreen():
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    rows, columns = w.t.height, w.t.width
    with w:
        a = [fmtstr((('.row%r.' % (row,)) * rows)[:columns]) for row in range(rows)]
        w.render_to_terminal(a)

def array_size_test(window):
    """Tests arrays one row to small or too large"""
    with window as w:
        with input.Input(sys.stdin) as input_generator:
            rows, columns = w.t.height, w.t.width
            while True:
                c = input_generator.next()
                if c == "":
                    sys.exit() # same as raise SystemExit()
                elif c == "h":
                    a = w.array_from_text("a for small array")
                elif c == "a":
                    a = [fmtstr(c*columns) for _ in range(rows)]
                elif c == "s":
                    a = [fmtstr(c*columns) for _ in range(rows-1)]
                elif c == "d":
                    a = [fmtstr(c*columns) for _ in range(rows+1)]
                elif c == "f":
                    a = [fmtstr(c*columns) for _ in range(rows-2)]
                elif c == "q":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "w":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "e":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "c":
                    w.write(w.t.move(w.t.height-1, 0))
                    w.scroll_down()
                elif isinstance(c, events.WindowChangeEvent):
                    a = w.array_from_text("window just changed to %d rows and %d columns" % (c.rows, c.columns))
                elif c == '\x0c': # ctrl-L
                    [w.write('\n') for _ in range(rows)]
                    continue
                else:
                    a = w.array_from_text("unknown command")
                w.render_to_terminal(a)

def fullscreen_winch():
    logging.basicConfig(filename='display.log',level=logging.DEBUG)
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    def sigwinch_handler(signum, frame):
        print 'sigwinch! Changed from %r to %r' % ((rows, columns), (w.t.height, w.t.width))
    with w:
        while True:
            rows, columns = w.t.height, w.t.width
            a = [fmtstr((('.%sx%s.' % (rows, columns)) * rows)[:columns]) for row in range(rows)]
            w.render_to_terminal(a)
            raw_input()

def fullscreen_winch_with_input():
    logging.basicConfig(filename='display.log',level=logging.DEBUG)
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    def sigwinch_handler(signum, frame):
        print 'sigwinch! Changed from %r to %r' % ((rows, columns), (w.t.height, w.t.width))
    with w:
        for e in input.Input():
            rows, columns = w.t.height, w.t.width
            a = [fmtstr((('.%sx%s.' % (rows, columns)) * rows)[:columns]) for row in range(rows)]
            w.render_to_terminal(a)
            raw_input()

if __name__ == '__main__':
    #simple_fullscreen()
    #array_size_test(FullscreenWindow(sys.stdout))
    array_size_test(CursorAwareWindow(sys.stdout, sys.stdin, keep_last_line=True, hide_cursor=True))
    #fullscreen_winch()

<commit_msg>array_size_test works with window changes<commit_after>from . import input
from .fmtstr import fmtstr
from . import events
from window import FullscreenWindow, CursorAwareWindow
import sys
import signal
import logging
from termhelpers import Cbreak
logging.basicConfig(filename='display.log',level=logging.DEBUG)

def simple_fullscreen():
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    rows, columns = w.t.height, w.t.width
    with w:
        a = [fmtstr((('.row%r.' % (row,)) * rows)[:columns]) for row in range(rows)]
        w.render_to_terminal(a)

def array_size_test(window):
    """Tests arrays one row to small or too large"""
    with window as w:
        with input.Input(sys.stdin) as input_generator:
            while True:
                c = input_generator.next()
                rows, columns = w.t.height, w.t.width
                if c == "":
                    sys.exit() # same as raise SystemExit()
                elif c == "h":
                    a = w.array_from_text("a for small array")
                elif c == "a":
                    a = [fmtstr(c*columns) for _ in range(rows)]
                elif c == "s":
                    a = [fmtstr(c*columns) for _ in range(rows-1)]
                elif c == "d":
                    a = [fmtstr(c*columns) for _ in range(rows+1)]
                elif c == "f":
                    a = [fmtstr(c*columns) for _ in range(rows-2)]
                elif c == "q":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "w":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "e":
                    a = [fmtstr(c*columns) for _ in range(1)]
                elif c == "c":
                    w.write(w.t.move(w.t.height-1, 0))
                    w.scroll_down()
                elif isinstance(c, events.WindowChangeEvent):
                    a = w.array_from_text("window just changed to %d rows and %d columns" % (c.rows, c.columns))
                elif c == '\x0c': # ctrl-L
                    [w.write('\n') for _ in range(rows)]
                    continue
                else:
                    a = w.array_from_text("unknown command")
                w.render_to_terminal(a)

def fullscreen_winch():
    logging.basicConfig(filename='display.log',level=logging.DEBUG)
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    def sigwinch_handler(signum, frame):
        print 'sigwinch! Changed from %r to %r' % ((rows, columns), (w.t.height, w.t.width))
    with w:
        while True:
            rows, columns = w.t.height, w.t.width
            a = [fmtstr((('.%sx%s.' % (rows, columns)) * rows)[:columns]) for row in range(rows)]
            w.render_to_terminal(a)
            raw_input()

def fullscreen_winch_with_input():
    logging.basicConfig(filename='display.log',level=logging.DEBUG)
    print 'this should be just off-screen'
    w = FullscreenWindow(sys.stdout)
    def sigwinch_handler(signum, frame):
        print 'sigwinch! Changed from %r to %r' % ((rows, columns), (w.t.height, w.t.width))
    with w:
        for e in input.Input():
            rows, columns = w.t.height, w.t.width
            a = [fmtstr((('.%sx%s.' % (rows, columns)) * rows)[:columns]) for row in range(rows)]
            w.render_to_terminal(a)
            raw_input()

if __name__ == '__main__':
    #simple_fullscreen()
    #array_size_test(FullscreenWindow(sys.stdout))
    array_size_test(CursorAwareWindow(sys.stdout, sys.stdin, keep_last_line=True, hide_cursor=True))
    #fullscreen_winch()

<|endoftext|>