text:
'''
------------------------------------------
Red9 Studio Pack: Maya Pipeline Solutions
Author: Mark Jackson
email: rednineinfo@gmail.com

Red9 blog : http://red9-consultancy.blogspot.co.uk/
MarkJ blog: http://markj3d.blogspot.co.uk
------------------------------------------

This is the heart of the Red9 StudioPack's boot sequence, managing folder structures,
dependencies and menuItems.

#########  THIS SHOULD NOT REQUIRE ANY OF THE RED9.core modules  ##########
'''

__author__ = 'Mark Jackson'
__buildVersionID__ = 2.5
installedVersion= False

import sys
import os
import imp
import maya.cmds as cmds
import maya.mel as mel
from functools import partial

import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

'''
 Maya Version Mapping History:
 ====================================

 Release         -version    -api     python    -qt       prefs      release    extra info
 -----------------------------------------------------------------------------------------

  2008          .  2008  .  ??????  .  2.5.1     na    .  2008    . 2007-09-01
  2009          .  2009  .  ??????  .  2.5.1     na    .  2009    . 2008-10-01
  2010          .  2010  .  201000  .  2.6.1     na    .  2010    . 2009-08-01
  2011 Hotfix2  .  2011  .  201102  .  2.6.4    4.5.3  .  2011    .
  2011 SAP      .  2011  .  201104  .  2.6.4    4.5.3  .  2011.5  . 2010-09-29

  2012          .  2012  .  201200  .  2.6.4    4.7.1  .  2012    . 2011-04-01
  2012 SP1      .  2012  .  ??????  .  2.6.4    4.7.1  .  2012    .
  2012 SAP1     .  2012  .  ??????  .  2.6.4    4.7.1  .  2012    . 2012-01-26
  2012 SP2      .  2012  .  201217  .  2.6.4    4.7.1  .  2012    .

  2013 SP1      .  2013  .  201301  .  2.6.4    4.7.1  .  2013    . 2012-07-00
  2013 SP2      .  2013  .  201303  .  2.6.4    4.7.1  .  2013    . 2013-01-00
  2013 EXT      .  2013  .  201350? .  2.6.4    4.7.1  .  2013.5  . 2012-09-25  . 2013 binary incompatible
  2013 EXT2     .  2013  .  201355  .  2.6.4    4.7.1  .  2013.5  . 2013-01-22  . 2013 binary incompatible

  2014          .  2014  .  201400  .  2.6.4    4.8.2  .  2014    . 2013-04-10
  2015          .  2015  .  201500  .  2.7      4.8.5  .  2015    . 2014-04-15
  2015 SP6      .  2015  .  201516  .  2.7      4.8.5  .  2015
  2016          .  2016  .  201600  .  2.7      4.8.6  .  2016    . 2015-04-15
  2016 EXT1 SP6 .  2016  .  201614  .  2.7      4.8.6  .  2016
  2016 EXT2     .  2016  .  201650  .  2.7      4.8.6  .  2016.5  . 2016-04-15 . 2016 binary incompatible
  2017          .  2017  .  201700  .  2.7      5.6.1  .  2017    . 2016-05-15

------------------------------------------------------------------------------------------
'''

#=========================================================================================
# LANGUAGE MAPPING -----------------------------------------------------------------------
#=========================================================================================

#global LANGUAGE_MAP

import language_packs.language_english
LANGUAGE_MAP = language_packs.language_english

def get_language_maps():
    languages=[]
    language_path = os.path.join(os.path.dirname(__file__),'language_packs')
    packs = os.listdir(language_path)
    for p in packs:
        if p.startswith('language_') and p.endswith('.py'):
            languages.append(p.split('.py')[0])
    return languages

def set_language(language='language_english', *args):
    global LANGUAGE_MAP
    language_path = os.path.join(os.path.dirname(__file__),'language_packs')
    packs = get_language_maps()
    if language in packs:
        print 'Red9 : Importing Language Map : %s' % language
        LANGUAGE_MAP = imp.load_source('language', os.path.join(language_path, language+'.py'))

set_language()

# -----------------------------------------------------------------------------------------
# MAYA DATA  ---
# -----------------------------------------------------------------------------------------

MAYA_INTERNAL_DATA = {}  # cached Maya internal vars for speed

def mayaFullSpecs():
    print 'Maya version : ', mayaVersion()
    print 'Maya API version: ', mayaVersionRelease()
    print 'Maya Release: ', cmds.about(v=True)
    print 'QT build: ', mayaVersionQT()
    print 'Prefs folder: ',mayaPrefs()
    print 'OS build: ', osBuild()

    print MAYA_INTERNAL_DATA

def mayaVersion():
    '''
    get the application version back, this doesn't track service packs or extensions
    TODO: need to manage this better and use the API version, eg: 2013.5 returns 2013
    '''
    if 'version' in MAYA_INTERNAL_DATA and MAYA_INTERNAL_DATA['version']:
        return MAYA_INTERNAL_DATA['version']
    else:
        MAYA_INTERNAL_DATA['version'] = mel.eval('getApplicationVersionAsFloat')
        return MAYA_INTERNAL_DATA['version']

def mayaInstallDir(version='2016'):
    '''
    This is more for future reference, we read the key from the win registry and return the MAYA_INSTALL_LOCATION
    '''
    try:
        import _winreg
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Autodesk\Maya\{0}\Setup\InstallPath".format(version), 0, _winreg.KEY_READ)
        return _winreg.QueryValueEx(key, "MAYA_INSTALL_LOCATION")[0]
    except:
        raise StandardError('Given Maya key not found in Registry')

def mayaVersionRelease():
    '''
    get the api version back so we can track service packs etc
    '''
    if 'api' in MAYA_INTERNAL_DATA and MAYA_INTERNAL_DATA['api']:
        return MAYA_INTERNAL_DATA['api']
    else:
        MAYA_INTERNAL_DATA['api'] = cmds.about(api=True)
        return MAYA_INTERNAL_DATA['api']

def mayaRelease():
    '''
    wrap over the version and api to return EXT builds that modify the
    codebase significantly, prefs being set to 20XX.5 is a general clue
    but we use the api build id to be specific
    '''
    base=mayaVersion()
    api=mayaVersionRelease()
    if base==2016:
        if api>=201615:
            return 2016.5
        return base
    return base

def mayaVersionQT():
    try:
        if 'qt' in MAYA_INTERNAL_DATA and MAYA_INTERNAL_DATA['qt']:
            return MAYA_INTERNAL_DATA['qt']
        else:
            MAYA_INTERNAL_DATA['qt'] = cmds.about(qt=True)
            return MAYA_INTERNAL_DATA['qt']
    except:
        pass

def mayaPrefs():
    '''
    Root of Maya prefs folder
    '''
    if 'prefs' in MAYA_INTERNAL_DATA and MAYA_INTERNAL_DATA['prefs']:
        return MAYA_INTERNAL_DATA['prefs']
    else:
        MAYA_INTERNAL_DATA['prefs'] = os.path.dirname(cmds.about(env=True))
        return MAYA_INTERNAL_DATA['prefs']

def mayaUpAxis(setAxis=None):
    import maya.OpenMaya as OpenMaya
    if setAxis:
        if setAxis.lower()=='y':
            OpenMaya.MGlobal.setYAxisUp()
        if setAxis.lower()=='z':
            OpenMaya.MGlobal.setZAxisUp()
    else:
        vect=OpenMaya.MGlobal.upAxis()
        if vect.z:
            return 'z'
        if vect.y:
            return 'y'

def mayaIsBatch():
    return cmds.about(batch=True)

def osBuild():
    build = cmds.about(os=True)
    if build == 'win64':
        return 64
    elif build == 'win32':
        return 32

def getCurrentFPS():
    '''
    returns the current frames per second as a number, rather than a useless string
    '''
    fpsDict = {"game": 15.0, "film": 24.0, "pal": 25.0, "ntsc": 30.0, "show": 48.0, "palf": 50.0, "ntscf": 60.0}
    return  fpsDict[cmds.currentUnit(q=True, fullName=True, time=True)]

# -----------------------------------------------------------------------------------------
# MENU SETUPS ---
# -----------------------------------------------------------------------------------------

def menuSetup(parent='MayaWindow'):

    #if exists remove all items, means we can update on the fly by restarting the Red9 pack
    if cmds.menu('redNineMenuItemRoot', exists=True):
        cmds.deleteUI('redNineMenuItemRoot')
        log.info("Rebuilding Existing RedNine Menu")

    # parent is an existing window with an existing menuBar?
    if cmds.window(parent, exists=True):
        if not cmds.window(parent, q=True, menuBar=True):
            raise StandardError('given parent for Red9 Menu has no menuBarlayout %s' % parent)
        else:
            cmds.menu('redNineMenuItemRoot', l="RedNine", p=parent, tearOff=True, allowOptionBoxes=True)
            log.info('new Red9 Menu added to current window : %s' % parent)
    # parent is a menuBar?
    elif cmds.menuBarLayout(parent, exists=True):
        cmds.menu('redNineMenuItemRoot', l='RedNine', p=parent, tearOff=True, allowOptionBoxes=True)
        log.info('New Red9 Sound Menu added to current windows menuBar : %s' % parent)
    # parent is an existing menu?
    elif cmds.menu(parent, exists=True):
        cmds.menuItem('redNineMenuItemRoot', l='RedNine', sm=True, p=parent)
        log.info('new Red9 subMenu added to current Menu : %s' % parent)
    else:
        raise StandardError('given parent for Red9 Menu is invalid %s' % parent)
    try:
        cmds.menuItem('redNineProRootItem',
                      l='PRO : PACK', sm=True, p='redNineMenuItemRoot', tearOff=True,i='red9.jpg')

        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.red9_details+' : ProPack', i='info_30.png',
                      c='Red9.setup.get_pro_pack()',p='redNineProRootItem')

        # Holder Menus for Client code
        if get_client_modules():
            cmds.menuItem(divider=True,p='redNineMenuItemRoot')
            for client in get_client_modules():
                cmds.menuItem('redNineClient%sItem' % client,
                               l='CLIENT : %s' % client, sm=True, p='redNineMenuItemRoot', tearOff=True, i='red9.jpg')

        cmds.menuItem(divider=True,p='redNineMenuItemRoot')

        #Add the main Menu items
        cmds.menuItem('redNineAnimItem',
                      l=LANGUAGE_MAP._MainMenus_.animation_toolkit,
                      ann=LANGUAGE_MAP._MainMenus_.animation_toolkit_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='pose_30.png',
                      c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.AnimationUI.show()")
        cmds.menuItem('redNineSnapItem',
                      l=LANGUAGE_MAP._MainMenus_.simple_snap,
                      ann=LANGUAGE_MAP._MainMenus_.simple_snap_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='locationon_30.png',
                      c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.AnimFunctions.snap()")
        cmds.menuItem('redNineSearchItem',
                      l=LANGUAGE_MAP._MainMenus_.searchui,
                      ann=LANGUAGE_MAP._MainMenus_.searchui_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='search_30.png',
                      c="import Red9.core.Red9_CoreUtils as r9Core;r9Core.FilterNode_UI.show()")
        cmds.menuItem('redNineLockChnsItem',
                      l=LANGUAGE_MAP._MainMenus_.lockchannels,
                      ann=LANGUAGE_MAP._MainMenus_.lockchannels_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='lock_30.png',
                      c="import Red9.core.Red9_CoreUtils as r9Core;r9Core.LockChannels.UI.show()")
        cmds.menuItem('redNineMetaUIItem',
                      l=LANGUAGE_MAP._MainMenus_.metanodeui,
                      ann=LANGUAGE_MAP._MainMenus_.metanodeui_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='meta_node_30.png',
                      c="import Red9.core.Red9_Meta as r9Meta;r9Meta.MClassNodeUI.show()")
        cmds.menuItem('redNineReporterUIItem',
                      l=LANGUAGE_MAP._MainMenus_.scene_reviewer,
                      ann=LANGUAGE_MAP._MainMenus_.scene_reviewer_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='hand_with_pen_30.png',
                      c="import Red9.core.Red9_Tools as r9Tools;r9Tools.SceneReviewerUI.show()")
        cmds.menuItem('redNineMoCapItem',
                      l=LANGUAGE_MAP._MainMenus_.mouse_mocap,
                      ann=LANGUAGE_MAP._MainMenus_.mouse_mocap_ann,
                      p='redNineMenuItemRoot', echoCommand=True,
                      c="import Red9.core.Red9_Tools as r9Tools;r9Tools.RecordAttrs.show()")
        cmds.menuItem('redNineRandomizerItem',
                      l=LANGUAGE_MAP._MainMenus_.randomize_keyframes,
                      ann=LANGUAGE_MAP._MainMenus_.randomize_keyframes_ann,
                      p='redNineMenuItemRoot', echoCommand=True,
                      c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.RandomizeKeys.showOptions()")
        cmds.menuItem('redNineFilterCurvesItem',
                      l=LANGUAGE_MAP._MainMenus_.interactive_curve_filter,
                      ann=LANGUAGE_MAP._MainMenus_.interactive_curve_filter_ann,
                      p='redNineMenuItemRoot', echoCommand=True,
                      c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.FilterCurves.show()")
        cmds.menuItem('redNineMirrorUIItem',
                      l=LANGUAGE_MAP._MainMenus_.mirror_setup,
                      ann=LANGUAGE_MAP._MainMenus_.mirror_setup_ann,
                      p='redNineMenuItemRoot', echoCommand=True,
                      c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.MirrorSetup().show()")
        cmds.menuItem('redNineCameraTrackItem', i='camera_30.png',
                      l='CameraTracker',sm=True,p='redNineMenuItemRoot')
        cmds.menuItem('redNineCamerTrackFixedItem',
                      l=LANGUAGE_MAP._MainMenus_.camera_tracker_pan,
                      ann=LANGUAGE_MAP._MainMenus_.camera_tracker_pan_ann,
                      p='redNineCameraTrackItem', echoCommand=True,
                      c="from Red9.core.Red9_AnimationUtils import CameraTracker as camTrack;camTrack.cameraTrackView(fixed=True)")
        if not mayaVersion()<=2009:
            cmds.menuItem(optionBox=True,
                      ann=LANGUAGE_MAP._MainMenus_.tracker_tighness_ann,
                      p='redNineCameraTrackItem', echoCommand=True,
                      c="from Red9.core.Red9_AnimationUtils import CameraTracker as camTrack;camTrack(fixed=True)._showUI()")
        cmds.menuItem('redNineCamerTrackFreeItem',
                      l=LANGUAGE_MAP._MainMenus_.camera_tracker_track,
                      ann=LANGUAGE_MAP._MainMenus_.camera_tracker_track_ann,
                      p='redNineCameraTrackItem', echoCommand=True,
                      c="from Red9.core.Red9_AnimationUtils import CameraTracker as camTrack;camTrack.cameraTrackView(fixed=False)")
        if not mayaVersion()<=2009:
            cmds.menuItem(optionBox=True,
                      ann=LANGUAGE_MAP._MainMenus_.tracker_tighness_ann,
                      p='redNineCameraTrackItem', echoCommand=True,
                      c="from Red9.core.Red9_AnimationUtils import CameraTracker as camTrack;camTrack(fixed=False)._showUI()")

        cmds.menuItem(divider=True,p='redNineMenuItemRoot')
        cmds.menuItem('redNineAnimBndItem',
                      l=LANGUAGE_MAP._MainMenus_.animation_binder,
                      ann=LANGUAGE_MAP._MainMenus_.animation_binder_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='workflow_30.png',
                      c="import Red9.core.AnimationBinder as animBnd;animBnd.AnimBinderUI()._UI()")
        cmds.menuItem(divider=True,p='redNineMenuItemRoot')

        cmds.menuItem('redNineHomepageItem',
                      l=LANGUAGE_MAP._MainMenus_.red9_homepage,
                      ann=LANGUAGE_MAP._MainMenus_.red9_homepage_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='domain_30.png',
                      c="Red9.setup.red9_website_home()")
        cmds.menuItem('redNineBlogItem',
                      l=LANGUAGE_MAP._MainMenus_.red9_blog,
                      ann=LANGUAGE_MAP._MainMenus_.red9_blog_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='blogspot_30.png',
                      c="Red9.setup.red9_blog()")
        cmds.menuItem('redNineVimeoItem',
                      l=LANGUAGE_MAP._MainMenus_.red9_vimeo,
                      ann=LANGUAGE_MAP._MainMenus_.red9_vimeo_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='vimeo_30.png',
                      c="Red9.setup.red9_vimeo()")
        cmds.menuItem('redNineFacebookItem',
                      l=LANGUAGE_MAP._MainMenus_.red9_facebook,
                      ann=LANGUAGE_MAP._MainMenus_.red9_facebook_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='facebook_30.png',
                      c="Red9.setup.red9_facebook()")
        cmds.menuItem('redNineAPIDocItem',
                      l=LANGUAGE_MAP._MainMenus_.red9_api_docs,
                      ann=LANGUAGE_MAP._MainMenus_.red9_api_docs_ann,
                      p='redNineMenuItemRoot', echoCommand=True, i='api_30.png',
                      c="Red9.setup.red9_apidocs()")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.red9_details, i='info_30.png',
                      c='Red9.setup.red9ContactInfo()',p='redNineMenuItemRoot')
        cmds.menuItem(divider=True,p='redNineMenuItemRoot')

        cmds.menuItem('redNineDebuggerItem', l=LANGUAGE_MAP._MainMenus_.red9_debugger,sm=True, i='bug_30.png', p='redNineMenuItemRoot')
        cmds.menuItem('redNineLostAnimItem', p='redNineDebuggerItem',
                      l=LANGUAGE_MAP._MainMenus_.reconnect_anim,
                      ann=LANGUAGE_MAP._MainMenus_.reconnect_anim_ann,
                      echoCommand=True, c="import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.ReconnectAnimData().show()")
        cmds.menuItem('redNineOpenCrashItem', p='redNineDebuggerItem',
                      l=LANGUAGE_MAP._MainMenus_.open_last_crash,
                      ann=LANGUAGE_MAP._MainMenus_.open_last_crash_ann,
                      echoCommand=True, c="import Red9.core.Red9_General as r9General;r9General.os_openCrashFile()")
        cmds.menuItem(divider=True,p='redNineDebuggerItem')
        cmds.menuItem('redNineDebugItem',
                      l=LANGUAGE_MAP._MainMenus_.systems_debug,
                      ann=LANGUAGE_MAP._MainMenus_.systems_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug()")
        cmds.menuItem('redNineInfoItem',
                      l=LANGUAGE_MAP._MainMenus_.systems_info,
                      ann=LANGUAGE_MAP._MainMenus_.systems_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info()")
        cmds.menuItem(divider=True,p='redNineDebuggerItem')

        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.individual_debug, sm=True, p='redNineDebuggerItem')
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Core",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Core')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Meta",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Meta')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Anim",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Anim')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Tools",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Tools')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Pose",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Pose')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9General",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9General')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.debug+" : r9Audio",
                      ann=LANGUAGE_MAP._MainMenus_.individual_debug_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_debug('r9Audio')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.individual_info,sm=True,p='redNineDebuggerItem')
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Core",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Core')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Meta",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Meta')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Anim",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Anim')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Tools",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Tools')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Pose",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Pose')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9General",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9General')")
        cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.info+" : r9Audio",
                      ann=LANGUAGE_MAP._MainMenus_.individual_info_ann,
                      echoCommand=True, c="Red9.core._setlogginglevel_info('r9Audio')")
        cmds.menuItem(divider=True,p='redNineDebuggerItem')
        cmds.menuItem('redNineReloadItem',l=LANGUAGE_MAP._MainMenus_.systems_reload, p='redNineDebuggerItem',
                      ann=LANGUAGE_MAP._MainMenus_.systems_reload_ann,
                      echoCommand=True, c=reload_Red9)
        cmds.menuItem(divider=True,p='redNineDebuggerItem')
        for language in get_language_maps():
            cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.language+" : %s" % language, c=partial(set_language,language),p='redNineDebuggerItem')
    except:
        raise StandardError('Unable to parent Red9 Menu to given parent %s' % parent)

def addToMayaMenus():
    '''
    Red9 Additions to the Maya Menu's themselves, additions to the timeSlider, fileMenu ETC..
    '''
    try:
        # fileMenu additions
        if not cmds.menuItem('redNineOpenFolderItem',q=True,ex=True):
            mainFileMenu=mel.eval("string $f=$gMainFileMenu")
            if not cmds.menu(mainFileMenu, q=True, ni=True):
                mel.eval('buildFileMenu()')
            cmds.menuItem(divider=True,p=mainFileMenu)
            cmds.menuItem('redNineCopyPathItem',
                          l=LANGUAGE_MAP._MainMenus_.copy_to_clipboard,
                          ann=LANGUAGE_MAP._MainMenus_.copy_to_clipboard_ann,
                          p=mainFileMenu,
                          echoCommand=True,
                          c="import maya.cmds as cmds;import Red9.core.Red9_General as r9General;r9General.Clipboard.setText(cmds.file(q=True,sn=True))")
            cmds.menuItem('redNineOpenFolderItem',
                          l=LANGUAGE_MAP._MainMenus_.open_in_explorer,
                          ann=LANGUAGE_MAP._MainMenus_.open_in_explorer_ann,
                          p=mainFileMenu,
                          echoCommand=True,
                          c="import maya.cmds as cmds;import Red9.core.Red9_General as r9General;r9General.os_OpenFileDirectory(cmds.file(q=True,sn=True))")

        # timeSlider additions
        if not cmds.menuItem('redNineTimeSliderCollapseItem',q=True,ex=True):
            if mayaVersion >= 2011:
                mel.eval('updateTimeSliderMenu TimeSliderMenu')

            TimeSliderMenu='TimeSliderMenu'
            cmds.menuItem(divider=True, p=TimeSliderMenu)
            cmds.menuItem(subMenu=True, label=LANGUAGE_MAP._MainMenus_.range_submenu, p=TimeSliderMenu)

            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.selectkeys_timerange,
                          ann=LANGUAGE_MAP._MainMenus_.selectkeys_timerange_ann,
                          c='import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.selectKeysByRange()')
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.setrangetoo,
                          ann=LANGUAGE_MAP._MainMenus_.setrangetoo_ann,
                          c='import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.setTimeRangeToo()')

            cmds.menuItem(divider=True, p=TimeSliderMenu)
            cmds.menuItem('redNineTimeSliderCollapseItem', label=LANGUAGE_MAP._MainMenus_.collapse_time,
                          ann=LANGUAGE_MAP._MainMenus_.collapse_time_ann,
                          c='import Red9.core.Red9_CoreUtils as r9Core;r9Core.timeOffset_collapseUI()',
                          p=TimeSliderMenu)

            cmds.menuItem(subMenu=True, label=LANGUAGE_MAP._MainMenus_.insert_padding, p=TimeSliderMenu)
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.pad_selected,
                          ann=LANGUAGE_MAP._MainMenus_.pad_selected_ann,
                          c='import Red9.core.Red9_CoreUtils as r9Core;r9Core.timeOffset_addPadding(scene=False)')
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.pad_full_scene,
                          ann=LANGUAGE_MAP._MainMenus_.pad_full_scene_ann,
                          c='import Red9.core.Red9_CoreUtils as r9Core;r9Core.timeOffset_addPadding(scene=True)')
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.pad_mrigs,
                          ann=LANGUAGE_MAP._MainMenus_.pad_mrigs_ann,
                          c='import Red9.core.Red9_CoreUtils as r9Core;r9Core.timeOffset_addPadding(scene=False,mRigs=True)')

            cmds.menuItem(subMenu=True, label=LANGUAGE_MAP._MainMenus_.inverse_anim, p=TimeSliderMenu)
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.inverse_selected,
                          ann=LANGUAGE_MAP._MainMenus_.inverse_selected_ann,
                          c='import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.AnimFunctions.inverseAnimCurves(mode="object", mRigs=False)')
            cmds.menuItem(label=LANGUAGE_MAP._MainMenus_.inverse_mrigs,
                          ann=LANGUAGE_MAP._MainMenus_.inverse_mrigs_ann,
                          c='import Red9.core.Red9_AnimationUtils as r9Anim;r9Anim.AnimFunctions.inverseAnimCurves(mode="object", mRigs=True)')
            if has_pro_pack():
                cmds.menuItem(divider=True, p=TimeSliderMenu)
                cmds.menuItem(subMenu=True, label='Red9 PRO: Timecode', p=TimeSliderMenu, i='red9.jpg')
                cmds.menuItem(label='PRO: Toggle Timecode', i='red9.jpg',
                          ann='Toggle the timeline to view time in timecode or frame',
                          c="from Red9.pro_pack import r9pro;r9pro.r9import('r9paudio');import r9paudio;r9paudio.timecode_maya_toggle_timeline()")
                cmds.menuItem(divider=True)
                cmds.menuItem(label='PRO: Set Maya Production Timecode', i='red9.jpg',
                          ann='set the Internal Maya Production timecode mapping',
                          c="from Red9.pro_pack import r9pro;r9pro.r9import('r9paudio');import r9paudio;r9paudio.timecode_maya_set_production()")
                cmds.menuItem(label='PRO: Reset Maya Production Timecode', i='red9.jpg',
                          ann='reset the Internal Maya Production timecode mapping',
                          c="from Red9.pro_pack import r9pro;r9pro.r9import('r9paudio');import r9paudio;r9paudio.timecode_maya_set_production(reset=True)")

        else:
            log.debug('Red9 Timeslider menus already built')
    except:
        log.debug('gMainFileMenu not found >> catch for unitTesting')

def addAudioMenu(parent=None, rootMenu='redNineTraxRoot'):
    '''
    Red9 Sound Menu setup
    '''
    print 'AudioMenu: given parent : ',parent
    if not parent:
        cmds.menu(rootMenu, l=LANGUAGE_MAP._MainMenus_.sound_red9_sound, tearOff=True, allowOptionBoxes=True)
        print 'New r9Sound Menu added - no specific parent given so adding to whatever menu is currently being built!'
    else:
        # parent is a window containing a menuBar?
        if cmds.window(parent, exists=True):
            if not cmds.window(parent, q=True, menuBar=True):
                raise StandardError('given parent for Red9 Sound Menu has no menuBarlayout %s' % parent)
            else:
                cmds.menu(rootMenu, l=LANGUAGE_MAP._MainMenus_.sound_red9_sound, p=parent, tearOff=True, allowOptionBoxes=True)
                log.info('New Red9 Sound Menu added to current windows menuBar : %s' % parent)
        # parent is a menuBar?
        elif cmds.menuBarLayout(parent, exists=True):
            cmds.menu(rootMenu, l=LANGUAGE_MAP._MainMenus_.sound_red9_sound, p=parent, tearOff=True, allowOptionBoxes=True)
            log.info('New Red9 Sound Menu added to current windows menuBar : %s' % parent)
        # parent is a menu already?
        elif cmds.menu(parent, exists=True):
            cmds.menuItem(rootMenu, l=LANGUAGE_MAP._MainMenus_.sound_red9_sound, sm=True, p=parent, allowOptionBoxes=True)
            log.info('New Red9 Sound subMenu added to current Menu : %s' % parent)
        else:
            raise StandardError('given parent for Red9 Sound Menu is invalid %s' % parent)

    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_offset_manager, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_offset_manager_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioToolsWrap().show()")
    if has_pro_pack():
        cmds.menuItem(l='PRO: Timecode Manager', p=rootMenu,
                  ann='Pro Time and Audio offset management tools',
                  c="from Red9.pro_pack import Pro_MenuStubs;Pro_MenuStubs('r9timecode_manager')")
    cmds.menuItem(d=True)
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_activate_selected_audio, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_activate_selected_audio_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().setActive()")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_set_timeline_to_selected, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_set_timeline_to_selected_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().setTimelineToAudio()")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_focus_on_selected, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_focus_on_selected_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().setTimelineToAudio();r9Audio.AudioHandler().setActive()")
    cmds.menuItem(d=True)
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_mute_selected, p=rootMenu,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().muteSelected(True)")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_unmute_selected, p=rootMenu,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().muteSelected(False)")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_lock_selected, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_lock_selected_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().lockTimeInputs(True)")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_unlock_selected, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_unlock_selected_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().lockTimeInputs(False)")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_delete_selected, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_delete_selected_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().deleteSelected()")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_format_soundnode_name, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_format_soundnode_name_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioHandler().formatNodes_to_Path()")
    cmds.menuItem(d=True)
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_combine_audio, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_combine_audio_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.combineAudio()")
    cmds.menuItem(d=True)
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_open_audio_path, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_open_audio_path_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.AudioNode().openAudioPath()")
    cmds.menuItem(l=LANGUAGE_MAP._MainMenus_.sound_inspect_wav, p=rootMenu,
                  ann=LANGUAGE_MAP._MainMenus_.sound_inspect_wav_ann,
                  c="import Red9.core.Red9_Audio as r9Audio;r9Audio.inspect_wav()")

# -----------------------------------------------------------------------------------------
# GENERAL RED9 DATA ---
# -----------------------------------------------------------------------------------------

def red9ButtonBGC(colour, qt=False):
    '''
    Generic setting for the main button colours in the UI's
    '''

    if colour==1 or colour=='green':
        rgb=[0.6, 1, 0.6]
    elif colour==2 or colour=='grey':
        rgb=[0.5, 0.5, 0.5]
    elif colour==3 or colour=='red':
        rgb=[1,0.3,0.3]
    elif colour==4 or colour=='white':
        rgb=[0.75,0.75,0.8]
    elif colour==5 or colour=='dark':
        rgb=[0.15,0.25,0.25]
    if qt:
        return [rgb[0]*255,rgb[1]*255,rgb[2]*255]
    else:
        return rgb

# def red9ContactInfo(*args):
#     '''
#     add icon link for : https://icons8.com
#     '''
#     import Red9.core.Red9_General as r9General  # lazy load
#     result=cmds.confirmDialog(title='Red9_StudioPack : build %f' % red9_getVersion(),
#                        message=("Author: Mark Jackson\r\r"+
#                                 "Technical Animation Director\r\r"+
#                                 "Contact me at info@red9Consultancy.com for more information\r\r"+
#                                 "thanks for trying the toolset. If you have any\r"+
#                                 "suggestions or bugs please let me know!"),
#                        button=['Red9Consultancy.com','ChangeLog','Close'],messageAlign='center')
#     if result == 'ChangeLog':
#         r9General.os_OpenFile(os.path.join(red9ModulePath(),'changeLog.txt'))
#     if result =='Red9Consultancy.com':
#         r9General.os_OpenFile('http://red9consultancy.com/')

def red9ContactInfo(*args):
    '''
    launch the stand-in UI for ProPack
    '''
    redSPWin='Red9StudioPack'
    if cmds.window(redSPWin,exists=True):
        cmds.deleteUI(redSPWin, window=True)
    redProWin = cmds.window(redSPWin, title='Red9_StudioPack : build %s' % red9_getVersion(),s=False)
    cmds.columnLayout()
    cmds.rowColumnLayout(nc=2,cw=(1,50))
    cmds.separator(style='none')
    cmds.image( image='Red9_StudioPack_logo.png' )
    cmds.setParent('..')
    cmds.rowColumnLayout(nc=1,cw=(1,350))
    cmds.text( fn='boldLabelFont',l="Red9 StudioPack\nAuthor: Mark Jackson\n\n"+\
                                 "Red9 Consultancy\n"+\
                                 "Contact: info@red9Consultancy.com\n\n"+\
                                 "thanks for trying the toolset. If you have any\n"+\
                                 "suggestions or bugs please let us know!\n\n")
    cmds.button(label='Visit us for more Information',h=40,c="import Red9.core.Red9_General as r9General;r9General.os_OpenFile('http://red9consultancy.com/')")
    cmds.separator(style='none',h=5)
    cmds.button(label='GitHub project',h=40,c="import Red9.core.Red9_General as r9General;r9General.os_OpenFile('https://github.com/markj3d/Red9_StudioPack')")
    cmds.separator(style='none',h=15)
    cmds.text(l="with thanks to:")
    cmds.text(l="icon libs: https://icons8.com")
    cmds.text(l="pydub libs: https://github.com/jiaaro/pydub")
    cmds.showWindow(redSPWin)
    cmds.window(redSPWin, e=True,widthHeight=(350, 535))

def red9Presets():
    '''
    get the default presets dir for all filterSettings.cfg files
    '''
    return os.path.join(red9ModulePath(), 'presets')

def red9Presets_get():
    '''
    generic extraction of all cfg presets from the default location above
    '''
    try:
        configs=[p for p in os.listdir(red9Presets()) if p.endswith('.cfg')]
        configs.sort()
        return configs
    except:
        log.debug('failed to retrieve the presets')
    return []

def red9ModulePath():
    '''
    Returns the Main path to the Red9 root module folder
    '''
    return os.path.join(os.path.dirname(os.path.dirname(__file__)),'')

def red9MayaNativePath():
    '''
    Returns the MayaVersioned Hacked script path if valid and found
    '''
    _version=mayaRelease()  # switched to manage ext builds that divert to a .5 release (2016.5)
    basepath=os.path.join(red9ModulePath(),'startup','maya_native','maya_%s' % str(int(_version)))
    path=os.path.join(red9ModulePath(),'startup','maya_native','maya_%s' % str(_version))

    if os.path.exists(path):
        # version including .5 handler
        return path
    elif os.path.exists(basepath):
        # simple int version
        return basepath
    else:
        log.info('Red9MayaHacked Folder not found for this build of Maya : %s' % path)

def red9_help(*args):
    '''
    open up the Red9 help docs
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    helpFile=os.path.join(red9ModulePath(),'docs',r'Red9-StudioTools Help.pdf')
    r9General.os_OpenFile(helpFile)

def red9_blog(*args):
    '''
    open up the Red9 Blog
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    r9General.os_OpenFile('http://red9-consultancy.blogspot.com/')

def red9_website_home(*args):
    '''
    open up the Red9 Consultancy homepage
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    r9General.os_OpenFile('http://red9consultancy.com/')

def red9_facebook(*args):
    '''
    open up the Red9 Facebook Page
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    r9General.os_OpenFile('http://www.facebook.com/Red9StudioPack/')

def red9_vimeo(*args):
    '''
    open up the Red9 Vimeo Channel
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    r9General.os_OpenFile('https://vimeo.com/user9491246')

def red9_apidocs(*args):
    '''
    open up the Red9 Vimeo Channel
    '''
    import Red9.core.Red9_General as r9General  # lazy load
    apidocs=os.path.join(red9ModulePath(),'docs', 'html', 'index.html')
    r9General.os_OpenFile(apidocs)

def red9_getVersion():
    return __buildVersionID__

def red9_getAuthor():
    return __author__

# def get_pro_pack(*args):
#     try:
#         #new pro_pack build calls
#         import Red9.pro_pack.r9pro as r9pro
#         r9pro.r9import('r9wtools')
#         import r9wtools
#         r9wtools.MailRegistration().show()
#     except:
#         #legacy
#         import Red9.core.Red9_General as r9General  # lazy load
#         result=cmds.confirmDialog(title='Red9_StudioPack : build %f' % red9_getVersion(),
#                             message=("Red9_ProPack Not Installed!\r\r"+
#                                      "Contact info@red9consultancy.com for more information"),
#                             button=['Red9Consultancy.com','Get_Pro','Close'],messageAlign='center')
#         if result == 'Get_Pro':
#             log.warning('Red9 ProPack systems not yet available - watch this space!')
#         if result =='Red9Consultancy.com':
#             r9General.os_OpenFile('http://red9consultancy.com/')

def get_pro_pack(*args):
    '''
    launch the stand-in UI for ProPack
    '''
    redProWin='Red9ProPack'
    if cmds.window(redProWin,exists=True):
        cmds.deleteUI(redProWin, window=True)
    redProWin = cmds.window(redProWin, title="Red9 ProPack",s=False)
    cmds.columnLayout()
    cmds.paneLayout()
    cmds.image( image='Red9_ProPack_logo.png' )
    cmds.setParent('..')
    cmds.rowColumnLayout(nc=1,cw=(1,250))
    cmds.text(l="Red9 ProPack : Not yet Installed!\n", fn='boldLabelFont')
    cmds.button(label='Get Me ProPack!',h=40,c="import Red9.core.Red9_General as r9General;r9General.os_OpenFile('http://red9consultancy.com/')")
    cmds.showWindow( redProWin )
    cmds.window(redProWin,e=True,widthHeight=(250, 350))

# -----------------------------------------------------------------------------------------
# BOOT FUNCTIONS ---
# -----------------------------------------------------------------------------------------

def addScriptsPath(path):
    '''
    Add additional folders to the ScriptPath
    '''
    scriptsPath=os.environ.get('MAYA_SCRIPT_PATH')

    if os.path.exists(path):
        if not path in scriptsPath:
            log.info('Adding To Script Paths : %s' % path)
            os.environ['MAYA_SCRIPT_PATH']+='%s%s' % (os.pathsep,path)
        else:
            log.info('Red9 Script Path already setup : %s' % path)
    else:
        log.debug('Given Script Path is invalid : %s' % path)

def addPluginPath(path=None):
    '''
    Make sure the plugin path has been added. If run as a module
    this will have already been added
    '''
    if not path:
        path=os.path.join(red9ModulePath(),'plug-ins')
    plugPaths=os.environ.get('MAYA_PLUG_IN_PATH')
    if os.path.exists(path) and not path in plugPaths:
        log.info('Adding Red9 Plug-ins to Plugin Paths : %s' % path)
        os.environ['MAYA_PLUG_IN_PATH']+='%s%s' % (os.pathsep,path)
    else:
        log.info('Red9 Plug-in Path already setup')

def addIconsPath(path=None):
    '''
    Make sure the icons path has been added. If run as a module
    this will have already been added
    '''
    if not path:
        path=os.path.join(red9ModulePath(),'icons')
    iconsPath=os.environ.get('XBMLANGPATH')

    if os.path.exists(path) and not path in iconsPath:
        log.info('Adding Red9 Icons To XBM Paths : %s' % path)
        os.environ['XBMLANGPATH']+='%s%s' % (os.pathsep,path)
    else:
        log.info('Red9 Icons Path already setup')

def addPythonPackages():
    '''
    Add the packages folder which is where any external modules
    will be stored
    '''
    red9Packages=os.path.join(red9ModulePath(),'packages')

    if not red9Packages in sys.path:
        log.info('Adding Red9Packages To Python Paths : %s' % red9Packages)
        sys.path.append(red9Packages)
    else:
        log.info('Red9Packages Path already setup : %s' % red9Packages)

    # PySide Management for pre 2014 x64 builds
    if mayaVersion()<2014.0 and os.path.exists(os.path.join(red9Packages, 'PySide')):
        pysidePath=os.path.join(red9Packages, 'PySide')
        if mayaVersion()==2012.0:
            pysidePath=os.path.join(pysidePath, 'PySide_2012_x64')
        elif mayaVersion()==2013.0:
            pysidePath=os.path.join(pysidePath, 'PySide_2013_x64')
        if os.path.exists(pysidePath) and not pysidePath in sys.path:
            sys.path.append(pysidePath)
            log.info('Adding Red9Packages:PySide To Python Paths : %s' % pysidePath)

    # Python compiled folders, if they exists
    if mayaVersion()<=2014 and os.path.exists(os.path.join(red9Packages, 'python2.6')):
        sys.path.append(os.path.join(red9Packages, 'python2.6'))
    if mayaVersion()>=2015 and os.path.exists(os.path.join(red9Packages, 'python2.7')):
        sys.path.append(os.path.join(red9Packages, 'python2.7'))

def sourceMelFolderContents(path):
    '''
    source all mel files in a given folder
    '''
    for script in [f for f in os.listdir(path) if f.lower().endswith('.mel')]:
        log.info('Sourcing mel script : %s' % script)
        mel.eval('source %s' % script)

def delete_shelf(shelf_name):
    '''
    Delete maya shelf and update maya shelf optionVars
    :param shelf_name: string: name of the shelf to be deleted
    :return:
    '''
    if mayaIsBatch():
        return
    if not cmds.shelfLayout(shelf_name, q=True, ex=True):
        return

    shelfs = cmds.optionVar(q='numShelves')
    current_shelf = None

    # Shelf preferences.
    for i in range(shelfs + 1):
        if shelf_name == cmds.optionVar(q="shelfName%i" % i):
            current_shelf = i
            break

    # manage shelve ids
    for i in range(current_shelf, shelfs + 1):
        cmds.optionVar(iv=("shelfLoad%s" % str(i), cmds.optionVar(q="shelfLoad%s" % str(i + 1))))
        cmds.optionVar(sv=("shelfName%s" % str(i), cmds.optionVar(q="shelfName%s" % str(i + 1))))
        cmds.optionVar(sv=("shelfFile%s" % str(i), cmds.optionVar(q="shelfFile%s" % str(i + 1))))

    cmds.optionVar(remove="shelfLoad%s" % shelfs)
    cmds.optionVar(remove="shelfName%s" % shelfs)
    cmds.optionVar(remove="shelfFile%s" % shelfs)
    cmds.optionVar(iv=("numShelves", shelfs - 1))

    cmds.deleteUI(shelf_name, layout=True)
    pref_file = os.path.join(mayaPrefs(), 'prefs', 'shelves', 'shelf_%s.mel.deleted' % shelf_name)
    if os.path.exists(pref_file):
        os.remove(pref_file)
    mel.eval("shelfTabChange")
    log.info('Shelf deleted: % s' % shelf_name)

def load_shelf(shelf_path):
    '''
    load Maya shelf
    :param shelf_path: string: file path to maya shelf
    '''
    if mayaIsBatch():
        return

    # get current top shelf
    gShelfTopLevel = mel.eval("string $shelf_ly=$gShelfTopLevel")
    top=cmds.shelfTabLayout(gShelfTopLevel, q=True, st=True)

    if os.path.exists(shelf_path):
        #print shelf_path
        delete_shelf(shelf_path)
        mel.eval('source "%s"' % shelf_path)
        mel.eval('loadNewShelf("%s")' % shelf_path)
        log.info('Shelf loaded: % s' % shelf_path)
        return True
    else:
        log.error('Cant load shelf, file doesnt exist: %s' % shelf_path)

    # restore users top shelf
    cmds.shelfTabLayout(gShelfTopLevel, e=True, st=top)

# -----------------------------------------------------------------------------------------
# PRO PACK ---
# -----------------------------------------------------------------------------------------

PRO_PACK_STUBS=None

def pro_pack_path():
    return os.path.join(red9ModulePath(),'pro_pack')

def has_pro_pack():
    '''
    Red9 Pro_Pack is available and activated as user
    '''
    if os.path.exists(pro_pack_path()):
        try:
            #new pro_pack call
            import Red9.pro_pack.r9pro as r9pro
            status=r9pro.checkr9user()
            if status and not issubclass(type(status),str):
                return True
            else:
                return False
        except:
            #we have the pro-pack folder so assume we're running legacy build (Dambusters support)
            return True
    else:
        return False

class ProPack_UIError(Exception):
    '''
    custom exception so we can catch it, this launched the
    get ProPack UI
    '''
    def __init__(self, *args):
        get_pro_pack()

class ProPack_Error(Exception):
    '''
    custom exception so we can catch it. This is an in-function
    error
    '''
    def __init__(self, *args):
        super(ProPack_Error, self).__init__('ProPack missing from setup!')

class pro_pack_missing_stub(object):
    '''
    Exception to raised when the the Pro_Pack is missing
    and the stubs are called
    '''
    def __init__(self):
        raise ProPack_UIError()

# -----------------------------------------------------------------------------------------
# RED9 PRODUCTION MODULES ---
# -----------------------------------------------------------------------------------------

def has_internal_systems():
    '''
    Red9 Consultancy internal modules only
    '''
    if os.path.exists(internal_module_path()):
        return True

def internal_module_path():
    return os.path.join(os.path.dirname(os.path.dirname(red9ModulePath())),'Red9_Internals')

# -----------------------------------------------------------------------------------------
# CLIENT MODULES ---
# -----------------------------------------------------------------------------------------

CLIENTS_BOOTED=[]

def client_core_path():
    return os.path.join(os.path.dirname(os.path.dirname(red9ModulePath())),'Red9_ClientCore')

def has_client_modules():
    '''
    Red9 Client Modules is the distribution of bespoke code to clients
    that tightly integrates into our ProPack core
    '''
    if os.path.exists(client_core_path()):
        return True

def get_client_modules():
    '''
    get all client modules ready for the boot sequence

    #TODO: link this up with a management setup so we can determine
    which client to boot if we have multiple client repositories in the system.
    '''
    clients=[]
    if has_client_modules():
        for f in os.listdir(client_core_path()):
            if os.path.isdir(os.path.join(client_core_path(), f)):
                if not f.startswith('.') and not f.startswith('_'):
                    clients.append(f)
    return clients

def clients_booted():
    '''
    return the client modules booted by the system
    '''
    global CLIENTS_BOOTED
    return CLIENTS_BOOTED

def boot_client_projects():
    '''
    Boot Client modules found in the Red9_ClientCore dir. This now propts
    if multiple client projects were found.
    '''
    global CLIENTS_BOOTED
    CLIENTS_BOOTED=[]
    clients=get_client_modules()
    clientsToBoot=[]
    if clients and len(clients)>1 and not mayaIsBatch():
        options=['All']
        options.extend(clients)
        result=cmds.confirmDialog(title='ProjectPicker',
                            message=("Multiple Projects Found!\r\r"+
                                     "Which Project would you like to boot?"),
                            button=options, messageAlign='center')
        if result == 'All':
            clientsToBoot=clients
        else:
            clientsToBoot.append(result)
    else:
        clientsToBoot=clients

    # boot the project / projects
    for client in clientsToBoot:
        #log.info('Booting Client Module : %s' % client)
        cmds.evalDeferred("import Red9_ClientCore.%s" % client, lp=True)  # Unresolved Import
        CLIENTS_BOOTED.append(client)

    # remove unused menuItems - added previously so that the menu grouping is clean
    for client in clients:
        if not client in clientsToBoot:
            cmds.deleteUI('redNineClient%sItem' % client)
            log.debug('Unused Client Menu Removed: %s' % client)

def __reload_clients__():
    '''
    used in the main reload_Red9 call below to ensure that
    the reload sequence is correct for the MetaData registry
    '''
    for client in get_client_modules():
        try:
            path='Red9_ClientCore.%s' % client
            cmds.evalDeferred("import %s;%s._reload()" % (path,path), lp=True)  # Unresolved Import
            log.info('Reloaded Client : "%s"' % path)
        except:
            log.info('Client : "%s" : does not have a _reload func internally' % path)

# -----------------------------------------------------------------------------------------
# BOOT CALL ---
# -----------------------------------------------------------------------------------------

def start(Menu=True, MayaUIHooks=True, MayaOverloads=True, parentMenu='MayaWindow'):
    '''
    Main entry point for the StudioPack
    :param Menu: Add the Red9 Menu to the Maya Main Menus
    :param MayUIHooks: Add the Red9 hooks to Maya Native UI's
    :param MayaOverloads: run the Maya native script hacks for Red9 - integrates into native Maya ui's
    '''
    log.info('Red9 StudioPack v%s : author: %s' % (red9_getVersion(), red9_getAuthor()))
    log.info('Red9 StudioPack Setup Calls :: Booting from >> %s' % red9ModulePath())

    #check for current builds
#    currentBuild=False
#    try:
#        currentBuild = mel.eval('$temp=$buildInstalled')
#    except:
#        print 'Red9 : version not found'
#
#    if currentBuild:
#        print 'Red9 : StudioPack already found : v', currentBuild
#        if currentBuild<=red9_getVersion():
#            print 'Red9 StudioPack Start Aborted : v%f is already installed' % currentBuild
#            return
#    else:
#        print 'Red9 : no version currently loaded'

    #Ensure the Plug-in and Icon paths are up
    addPluginPath()
    addIconsPath()
    #Need to add a Mel Folder to the scripts path
    addScriptsPath(os.path.join(red9ModulePath(),'core'))

    #Add the Packages folder
    addPythonPackages()

    if not cmds.about(batch=True):
        if Menu:
            try:
                menuSetup(parent=parentMenu)
            except:
                log.debug('Red9 main menu Build Failed!')

        if MayaUIHooks:
            #Source Maya Hacked Mel files
            hacked=red9MayaNativePath()
            if hacked and MayaOverloads:
                addScriptsPath(os.path.join(red9ModulePath(),'startup','maya_native'))
                addScriptsPath(hacked)
                try:
                    mel.eval('source Red9_MelCore')
                    sourceMelFolderContents(hacked)
                except StandardError, error:
                    log.info(error)

            #Add custom items to standard built Maya menus
            addToMayaMenus()

    log.info('Red9 StudioPack Complete!')

    # Rearrangement of the Boot core systems to better structure the boot sequence

    # Boot main Red9.core
    cmds.evalDeferred("import Red9.core", lp=True)

    # Boot the Pro_Pack
    if has_pro_pack():
        cmds.evalDeferred("import Red9.pro_pack", lp=True)  # Unresolved Import
    # Boot the Red9_Internal systems
    if has_internal_systems():
        cmds.evalDeferred("import Red9_Internals", lp=True)  # Unresolved Import
    # Boot Client Codebases
    if has_client_modules():
        boot_client_projects()
        #cmds.evalDeferred('import Red9.startup.setup as r9Setup;r9Setup.boot_client_projects()', lp=True)

def reload_Red9(*args):
    '''
    careful reload of the systems to maintain the integrity of the
    MetaData registry setups for pro_pack, client_core and internals
    '''
    #global LANGUAGE_MAP
    #reload(LANGUAGE_MAP)
    import Red9.core
    Red9.core._reload()

    if has_pro_pack():
        print '\nReloading ProPack Systems (INTERNAL USE)'
        print '='*40
        import Red9.pro_pack.core
        Red9.pro_pack.core._reload()

    if has_internal_systems():
        print '\nReloading Internal Codebase'
        print '='*40
        import Red9_Internals
        Red9_Internals._reload()

    if has_client_modules():
        print '\nReloading Client Codebase'
        print '='*40
        __reload_clients__()

PRO_PACK_STUBS=pro_pack_missing_stub


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Hub-Press - Page 1 - coder's dilemma</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Hub-Press - Page 1 - coder's dilemma">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="Hub-Press - Page 1 - coder's dilemma">
    <meta property="og:description" content="">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link rel="stylesheet" type="text/css" href="//codersdilemma.com/themes/uno/assets/css/uno.css?v=1508618090910" />

    <link rel="canonical" href="http://codersdilemma.com/http://codersdilemma.com/tag/Hub-Press/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="coder's dilemma" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Hub-Press - Page 1 - coder's dilemma" />
    <meta property="og:url" content="http://codersdilemma.com/http://codersdilemma.com/tag/Hub-Press/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Hub-Press - Page 1 - coder's dilemma" />
    <meta name="twitter:url" content="http://codersdilemma.com/http://codersdilemma.com/tag/Hub-Press/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="coder's dilemma" href="http://codersdilemma.com/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

coder's dilemma

Blog

About

                      Github

Tag: Hub-Press

Adding "about page" to hubpress.io

goal - add "about page" is not supported I wanted to add a page describing this website and a page to showcase my current project.  Ghost a similiar blogger engine to hubpress.io - can have static pages that have there own static urls.  But as of this wrighting you…

            <time datetime="22 Sep 2017" class="post-list__meta--date date">22 Sep 2017</time> •
            HubPress, about, page

Adding custom domain to hubpress

   When you create a hubpress webpage it will be hosted with github pages and have a url of www.username.github.io.  Which is harder to remember then a standered .com address.  The fix for this is relitively simple and cost me around 15 dollars. Step 1    …

            <time datetime="22 Sep 2017" class="post-list__meta--date date">22 Sep 2017</time> •
            HubPress, Blog, custom domain, setup

Privacy Policy For Apps

fit sync Privacy Policy Merge Google Sheet Privacy Policy Math Equations Privacy Policy This privacy policy has been compiled to better serve those who are concerned with how their `Personally Identifiable Information' (PII) is being used online. PII, as described in US privacy law and information security, is information that…

            <time datetime="01 Jan 2014" class="post-list__meta--date date">01 Jan 2014</time> •
            HubPress, Policy

    Page 1 of 1

                © 2017. All rights reserved.
                Uno theme by Dale-Anthony
                Proudly published with Hubpress

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit, AfterViewInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { HttpService } from '../../../../services/http.service';

@Component({
    selector: 'app-user-appointment',
    templateUrl: './appointment.component.html',
    styleUrls: ['./appointment.component.css']
})
export class AppointmentComponent implements OnInit, AfterViewInit {
    appointment;
    newReview;

    constructor(public router: Router, public routerActivated: ActivatedRoute
        , public domSanitizer: DomSanitizer, private http: HttpService) {

    }

    ngOnInit() {
        this.routerActivated.params
            .subscribe((appointmentId) => {
                this.http.get('api/appointment/' + appointmentId.id).subscribe(appointment => {
                    this.appointment = appointment
                });
            });

    }

    ngAfterViewInit() { }

    review() {
        console.log(this.newReview);
        this.http.post('api/appointment/review', this.newReview)
            .subscribe(result => {
                console.log(result);
                if (result.success) {
                    //console.log(this.newReview);

                }
            });;
    }

}


text:
package cleanup

import (
	"regexp"
)

var (
	// markdown headline which start with the headline text righ after the hash
	markdownHeadlineStartWhitespace = regexp.MustCompile(`^(#+)([^\s#])`)

	// match headlines which have a hash at the end
	markdownHeadlineClosingHeadline = regexp.MustCompile(`^(#+)\s*(.+?)\s*(#+)$`)
)

func cleanupHeadlines(lines []string) []string {
	for index, line := range lines {

		fixedLine := line

		// headline start
		fixedLine = markdownHeadlineStartWhitespace.ReplaceAllString(fixedLine, "$1 $2")

		// remove closing headline hashes
		fixedLine = markdownHeadlineClosingHeadline.ReplaceAllString(fixedLine, "$1 $2")

		// same the fixed line
		if fixedLine != line {
			lines[index] = fixedLine
		}
	}

	return lines
}


text:
> Christoff Bürger.
> "Reference Attribute Grammar Controlled Graph Rewriting: Motivation and Overview".
> In: _Proceedings of the 2015 ACM SIGPLAN International Conference on Software Language Engineering_.
> ACM, October 2015, pages 89-100.
> [Paper at the ACM Digital Library](http://dl.acm.org/citation.cfm?id=2814257)

> Christoff Bürger.
> "fUML Activity Diagrams with RAG-controlled Rewriting: A RACR Solution of The TTC 2015 Model Execution Case".
> In: _TTC 2015: Proceedings of the 8th Transformation Tool Contest_.
> Volume 1524. CEUR Workshop Proceedings. CEUR-WS.org, July 2015, pp. 27–36.
> [Original version at CEUR-WS.org](http://ceur-ws.org/Vol-1524/paper10.pdf), [up-to-date version](examples/ttc-2015-fuml-activity-diagrams/documentation/solution-description.pdf)

> Christoff Bürger, Johannes Mey, René Schöne, Sven Karol and Daniel Langner.
> "Using Reference Attribute Grammar-Controlled Rewriting for Energy Auto-Tuning".
> In: _MRT 2015: Proceedings of the 10th International Workshop on Models@run.time_.
> Volume 1474. CEUR Workshop Proceedings. CEUR-WS.org, September 2015, pp. 31–40.
> [Paper at CEUR-WS.org](http://ceur-ws.org/Vol-1474/MRT15_paper_1.pdf)

> René Schöne, Sebastian Götz, Uwe Aßmann and Christoff Bürger.
> "Incremental Runtime-generation of Optimisation Problems using RAG-controlled Rewriting".
> In: _MRT 2016: Proceedings of the 11th International Workshop on Models@run.time_.
> Volume 1742. CEUR Workshop Proceedings. CEUR-WS.org, October 2016, pp. 26–34.
> [Paper at CEUR-WS.org](http://ceur-ws.org/Vol-1742/MRT16_paper_5.pdf)

> Johannes Mey, René Schöne, Daniel Langner and Christoff Bürger.
> "Using Reference Attribute Grammar-Controlled Rewriting for Runtime Resource Management".
> In: _RES4ANT 2016: Proceedings of the 1st International Workshop on RESource Awareness and Application Auto-tuning in Adaptive and heterogeNeous compuTing_.
> Volume 1643. CEUR Workshop Proceedings. CEUR-WS.org, March 2016, pp. 13-17.
> [Paper at CEUR-WS.org](http://ceur-ws.org/Vol-1643/paper-03.pdf)

## Non-reviewed Publications

> Christoff Bürger. _RACR: A Scheme Library for Reference Attribute Grammar Controlled Rewriting_.
> Technical report, TUD-FI12-09. Lehrstuhl Softwaretechnologie, Technische Universität Dresden, December 2012.
> [Original version at Qucosa](http://nbn-resolving.de/urn:nbn:de:bsz:14-qucosa-104623), [up-to-date version](racr/documentation/title.md).

> Daniel Langner, Christoff Bürger. _Die C# Schnittstelle der Referenzattributgrammatik-gesteuerten Graphersetzungsbibliothek RACR: Übersicht, Anwendung und Implementierung_.
> Technical report, TUD-FI15-06. Lehrstuhl Softwaretechnologie, Technische Universität Dresden, October 2015.
> [Original version at Qucosa](http://nbn-resolving.de/urn:nbn:de:bsz:14-qucosa-191908), [up-to-date version](racr-net//documentation/title.md).

# Presentations

> Christoff Bürger. _Reference Attribute Grammar Controlled Graph Rewriting: Motivation and Overview_.
> Presentation at the 2015 ACM SIGPLAN International Conference on Software Language Engineering.
> Pittsburgh, USA, 27th October 2015.
> [Presentation](examples/sle-2015/documentation/presentation.pdf).

> Christoff Bürger. _fUML Activity Diagrams with RAG-controlled Rewriting: A RACR Solution of The TTC 2015 Model Execution Case_.
> Presentation at the 8th Transformation Tool Contest.
> L'Aquila, Italy, 24th July 2015.
> [Presentation](examples/ttc-2015-fuml-activity-diagrams/documentation/solution-presentation.pdf), [poster](examples/ttc-2015-fuml-activity-diagrams/documentation/solution-poster-a0.pdf), [overall quality award](examples/ttc-2015-fuml-activity-diagrams/documentation/solution-award.pdf).

> Johannes Mey. _Using Reference Attribute Grammar-Controlled Rewriting for Energy Auto-Tuning_.
> Presentation at the 10th International Workshop on Models@run.time.
> Ottawa, Canada, 29th September 2015.
> [Presentation](https://github.com/christoff-buerger/reat/raw/master/documentation/presentation-mrt-2015.pdf).

> Марта Тасић. _Benchmarking Incremental Dynamic Attribute Evaluation - RACR/JastAdd Performance Case Study in the Domain of Invasive Software Composition_.
> Presentation at Lehrstuhl Softwaretechnologie, Technische Universität Dresden.
> Dresden, Germany, 1st July 2014.
> [Presentation](https://github.com/christoff-buerger/racr-boneyard/raw/master/invasive-composition/original-case-study-by-Марта-Тасић/Benchmarking-Incremental-Dynamic-Attribute-Evaluation-RACR-JastAdd-Performance-Case-Study-in-the-Domain-of-Invasive-Software-Composition.pdf), [original sources on GitHub](https://github.com/christoff-buerger/racr-boneyard/tree/master/invasive-composition/original-case-study-by-Марта-Тасић), [up-to-date sources on GitHub](https://github.com/christoff-buerger/racr-boneyard/tree/master/invasive-composition/refactored-case-study-by-Christoff-Bürger).


text:
package com.github.paddan.rtsp;

import java.util.*;
import java.nio.*;

// RR: Receiver Report RTCP Packet

//         0                   1                   2                   3
//         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// header |V=2|P|    RC   |   PT=RR=201   |             length            |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//        |                     SSRC of packet sender                     |
//        +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// report |                           fraction lost                       |
// block  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//   1    |              cumulative number of packets lost                |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//        |           extended highest sequence number received           |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//        |                      interarrival jitter                      |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//        |                         last SR (LSR)                         |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//        |                   delay since last SR (DLSR)                  |
//        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

class RTCPpacket {

    final static int HEADER_SIZE = 8;
    final static int BODY_SIZE = 24;

	public int Version;			// Version number 2
    public int Padding;			// Padding of packet
    public int RC; 				// Reception report count = 1 for one receiver
    public int PayloadType;		// 201 for Receiver Report
    public int length;			// 1 source is always 32 bytes: 8 header, 24 body
    public int Ssrc;			// Ssrc of sender
    public float fractionLost;	// The fraction of RTP data packets from sender lost since the previous RR packet was sent
    public int cumLost;			// The total number of RTP data packets from sender that have been lost since the beginning of reception.
    public int highSeqNb;		// Highest sequence number received
    public int jitter;			// Not used
    public int LSR;				// Not used
    public int DLSR;			// Not used

	public byte[] header;	//Bitstream of header
	public byte[] body;		//Bitstream of the body

    // Constructor from field values
    public RTCPpacket(float fractionLost, int cumLost, int highSeqNb) {
    	Version = 2;
    	Padding = 0;
    	RC = 1;
    	PayloadType = 201;
    	length = 32;
    	//Other fields not used

    	this.fractionLost = fractionLost;
    	this.cumLost = cumLost;
    	this.highSeqNb = highSeqNb;

    	//Construct the bitstreams
    	header = new byte[HEADER_SIZE];
    	body = new byte[BODY_SIZE];

   		header[0] = (byte)(Version << 6 | Padding << 5 | RC);
        header[1] = (byte)(PayloadType & 0xFF);
        header[2] = (byte)(length >> 8);
        header[3] = (byte)(length & 0xFF);
        header[4] = (byte)(Ssrc >> 24);
        header[5] = (byte)(Ssrc >> 16);
        header[6] = (byte)(Ssrc >> 8);
        header[7] = (byte)(Ssrc & 0xFF);

		ByteBuffer bb = ByteBuffer.wrap(body);
		bb.putFloat(fractionLost);
		bb.putInt(cumLost);
		bb.putInt(highSeqNb);
    }

    // Constructor from bit stream
    public RTCPpacket(byte[] packet, int packet_size) {

    	header = new byte[HEADER_SIZE];
    	body = new byte[BODY_SIZE];

        System.arraycopy(packet, 0, header, 0, HEADER_SIZE);
        System.arraycopy(packet, HEADER_SIZE, body, 0, BODY_SIZE);

    	// Parse header fields
        Version = (header[0] & 0xFF) >> 6;
        PayloadType = header[1] & 0xFF;
        length = (header[3] & 0xFF) + ((header[2] & 0xFF) << 8);
        Ssrc = (header[7] & 0xFF) + ((header[6] & 0xFF) << 8) + ((header[5] & 0xFF) << 16) + ((header[4] & 0xFF) << 24);

    	// Parse body fields
    	ByteBuffer bb = ByteBuffer.wrap(body); // big-endian by default
    	fractionLost = bb.getFloat();
    	cumLost = bb.getInt();
    	highSeqNb = bb.getInt();
    }

    //--------------------------
    //getpacket: returns the packet bitstream and its length
    //--------------------------
    public int getpacket(byte[] packet)
    {
        //construct the packet = header + body
        System.arraycopy(header, 0, packet, 0, HEADER_SIZE);
        System.arraycopy(body, 0, packet, HEADER_SIZE, BODY_SIZE);

        //return total size of the packet
        return (BODY_SIZE + HEADER_SIZE);
    }

    //--------------------------
    //getlength: return the total length of the RTCP packet
    //--------------------------
    public int getlength() {
        return (BODY_SIZE + HEADER_SIZE);
    }

    public String toString() {
    	return "[RTCP] Version: " + Version + ", Fraction Lost: " + fractionLost
    		   + ", Cumulative Lost: " + cumLost + ", Highest Seq Num: " + highSeqNb;
    }
}


text:
package com.intellij.ide.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.refactoring.copy.CopyHandler;

public class SaveAsAction extends DumbAwareAction {

  @Override
  public void update(AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final VirtualFile virtualFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
    e.getPresentation().setEnabled(project!=null && virtualFile!=null);
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final VirtualFile virtualFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
    @SuppressWarnings({"ConstantConditions"}) final PsiElement element = PsiManager.getInstance(project).findFile(virtualFile);
    if(element==null) return;
    CopyHandler.doCopy(new PsiElement[] {element.getContainingFile()}, element.getContainingFile().getContainingDirectory());
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.apache.flink</groupId>
		<artifactId>flink-table</artifactId>
		<version>1.11-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>

	<artifactId>flink-table-api-scala_${scala.binary.version}</artifactId>
	<name>flink-table-api-scala</name>
	<description>
		This module contains the Table/SQL API for writing table programs
		within the table ecosystem using the Scala programming language.
	</description>

	<packaging>jar</packaging>

	<dependencies>
		<!-- Flink dependencies -->
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-table-common</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-table-api-java</artifactId>
			<version>${project.version}</version>
		</dependency>

		<!-- External dependencies -->

		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-reflect</artifactId>
		</dependency>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-library</artifactId>
		</dependency>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-compiler</artifactId>
		</dependency>

		<!-- Test dependencies -->

		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-core</artifactId>
			<version>${project.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-table-common</artifactId>
			<version>${project.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-table-api-java</artifactId>
			<version>${project.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- Scala Compiler -->
			<plugin>
				<groupId>net.alchim31.maven</groupId>
				<artifactId>scala-maven-plugin</artifactId>
				<executions>
					<!-- Run Scala compiler in the process-resources phase, so that dependencies on
						Scala classes can be resolved later in the (Java) compile phase -->
					<execution>
						<id>scala-compile-first</id>
						<phase>process-resources</phase>
						<goals>
							<goal>compile</goal>
						</goals>
					</execution>

					<!-- Run Scala compiler in the process-test-resources phase, so that dependencies on
						 Scala classes can be resolved later in the (Java) test-compile phase -->
					<execution>
						<id>scala-test-compile</id>
						<phase>process-test-resources</phase>
						<goals>
							<goal>testCompile</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<!-- Scala Code Style -->
			<plugin>
				<groupId>org.scalastyle</groupId>
				<artifactId>scalastyle-maven-plugin</artifactId>
				<configuration>
					<configLocation>${project.basedir}/../../tools/maven/scalastyle-config.xml</configLocation>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
//----------------------------------------------------------------------------
// Harmony .NET
// A dynamic loader and linker library for integrating .NET and C
// Copyright (C) 2016 Sean Werkema
//
// 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.
//----------------------------------------------------------------------------

namespace Harmony.Win32.Enums
{
	using System;

	[Flags]
	internal enum MemoryProtection : uint
	{
		EXECUTE = 0x10,
		EXECUTE_READ = 0x20,
		EXECUTE_READWRITE = 0x40,
		EXECUTE_WRITECOPY = 0x80,
		NOACCESS = 0x01,
		READONLY = 0x02,
		READWRITE = 0x04,
		WRITECOPY = 0x08,
		GUARD_Modifierflag = 0x100,
		NOCACHE_Modifierflag = 0x200,
		WRITECOMBINE_Modifierflag = 0x400
	}
}


text:
package com.android.sdk.net.gson;

import com.android.sdk.net.NetContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;

/**
 * json 解析容错处理,参考
 *
 * @author Ztiany
 * Date : 2018-08-13
 */
public class ErrorJsonLenientConverterFactory extends Converter.Factory {

    private final GsonConverterFactory mGsonConverterFactory;

    public ErrorJsonLenientConverterFactory(GsonConverterFactory gsonConverterFactory) {
        mGsonConverterFactory = gsonConverterFactory;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations,
                                                          Retrofit retrofit) {
        return mGsonConverterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type,
                                                            Annotation[] annotations,
                                                            Retrofit retrofit) {

        final Converter<ResponseBody, ?> delegateConverter = mGsonConverterFactory.responseBodyConverter(type, annotations, retrofit);

        return (Converter<ResponseBody, Object>) value -> {
            try {
                return delegateConverter.convert(value);
            } catch (Exception e/*防止闪退:JsonSyntaxException、IOException or MalformedJsonException*/) {
                Timber.e(e, "Json covert error -->error ");
                return NetContext.get().netProvider().errorDataAdapter().createErrorDataStub(type, annotations, retrofit, value);//服务器数据格式错误
            }
        };

    }

}


text:
package de.uniaugsburg.isse.constraints;

import de.uniaugsburg.isse.powerplants.PowerPlantData;
import de.uniaugsburg.isse.util.PowerPlantUtil;

/**
 * Expects a fixed rate of change that must not be exceeded per timestep in
 * contrast to relative rate of change constraints
 *
 * @author Alexander Schiendorfer
 *
 */
public class FixedChangeConstraint extends PlantConstraint {
	private double maxProductionChange; // relative rate of change per timestep

	/**
	 * Concrete physical limit rate of change constraint
	 *
	 * @param p
	 *            - Power source
	 * @param maxProductionChange
	 *            - absolute amount of change
	 */
	public FixedChangeConstraint(PowerPlantData pd) {
		this.maxProductionChange = PowerPlantUtil.safeDouble(
				"maxProductionChange", pd.getMap());
	}

	@Override
	public double maximize() {
		return maxProductionChange + plant.getPower().max;
	}

	@Override
	public double minimize() {
		return plant.getPower().min - maxProductionChange;
	}

	public double getMaxProductionChange() {
		return maxProductionChange;
	}

	public void setMaxProductionChange(double maxProductionChange) {
		this.maxProductionChange = maxProductionChange;
	}
}


text:
package extracells.render;

import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import extracells.blocks.BlockCertusTank;
import extracells.blocks.BlockMonitorStorageFluid;
import extracells.blocks.BlockTerminalFluid;
import extracells.render.helpers.RenderHelperMonitorStorageFluid;
import extracells.render.helpers.RenderHelperTerminalFluid;
import extracells.render.model.ModelCertusTank;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;

public class RenderHandler implements ISimpleBlockRenderingHandler
{
	int renderID = 0;
	RenderHelperMonitorStorageFluid monitorRender = new RenderHelperMonitorStorageFluid();
	RenderHelperTerminalFluid terminalRender = new RenderHelperTerminalFluid();
	ModelCertusTank tank = new ModelCertusTank();
	public static int renderPass;

	public RenderHandler(int id)
	{
		RenderHandler.renderPass = 0;
		renderID = id;
	}

	@Override
	public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)
	{
		if (block instanceof BlockTerminalFluid)
		{
			terminalRender.renderInventoryBlock(block, metadata, modelID, renderer);
		}
		if (block instanceof BlockMonitorStorageFluid)
		{
			monitorRender.renderInventoryBlock(block, metadata, modelID, renderer);
		}
	}

	@Override
	public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
	{
		if (block instanceof BlockTerminalFluid)
		{
			return terminalRender.renderWorldBlock(world, x, y, z, block, modelId, renderer);
		}
		if (block instanceof BlockMonitorStorageFluid)
		{
			return monitorRender.renderWorldBlock(world, x, y, z, block, modelId, renderer);
		}
		if (block instanceof BlockCertusTank)
		{
			Tessellator tessellator = Tessellator.instance;
			tessellator.setColorOpaque_F(1, 1, 1);
			boolean oldAO = renderer.enableAO;
			renderer.enableAO = false;
			if (RenderHandler.renderPass == 0)
			{
				tank.renderOuterBlock(block, x, y, z, renderer, world);
			} else
			{
				tank.renderInnerBlock(block, x, y, z, renderer, world);
				TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
				tank.renderFluid(tileEntity, x, y, z, renderer);
			}
			renderer.enableAO = oldAO;
			return true;
		}
		return false;
	}

	@Override
	public boolean shouldRender3DInInventory()
	{
		return true;
	}

	@Override
	public int getRenderId()
	{
		return renderID;
	}
}


text:
@echo off
pushd %~dp0
cd ..\libraries\src

set AZTOOLS=..\..\..\azure-sdk-tools\WindowsAzurePowerShell\src

robocopy /E .\ %AZTOOLS%\ManagementLibraries\ /XD CloudServiceManagement /XD Keys /XD PackageSpecs /XD Playground /XD Scheduler /XD bin /XD obj /XD Common.NetFramework /XF AssemblyInfo.cs /XF libraries.targets /XF .gitignore /XF packages.config /XF app.config /XF *.csproj
robocopy /E .\Common.NetFramework\ %AZTOOLS%\ManagementLibraries.NetFramework\ /XF AssemblyInfo.cs /XF libraries.targets /XF .gitignore /XF packages.config /XF app.config /XF *.csproj /XD bin /XD obj

: done
popd


text:
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )

package ${package}.domain.persona;

import javax.activation.DataHandler;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Ryan Heaton
 */
@XmlRootElement
public class Persona {

  private String id;
  private String email;
  private String alias;
  private Name name;
  private javax.activation.DataHandler picture;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getAlias() {
    return alias;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  public Name getName() {
    return name;
  }

  public void setName(Name name) {
    this.name = name;
  }

  public DataHandler getPicture() {
    return picture;
  }

  public void setPicture(DataHandler picture) {
    this.picture = picture;
  }
}


text:
<?php

namespace Venus\src\plugins\FreeHtml\Controller;

use \Venus\src\plugins\common\Controller        as Controller;
use \Venus\src\BackOffice\Entity\plugin_freehtml as EntityPluginFreeHtml;
use \Venus\src\BackOffice\Model\plugin_freehtml as PluginFreeHtml;

/**
 * Controller to test
 *
 * @category    Venus\src
 * @package     Venus\src\plugins\FreeHtml\Controller
 * @author      Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright   Copyright (c) 2013-2015 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license     https://github.com/las93/uranium/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version     Release: 1.0.0
 * @filesource  https://github.com/las93/uranium
 * @link        https://github.com/las93
 * @since       1.0
 */
class FreeHtml extends Controller
{
    /**
     * Constructor
     *
     * @access public
     * @return object
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * the main page
     *
     * @access public
     * @param  object $oThis
     * @param  int $iId
     * @return void
     */
    public function update($oThis, $iId)
    {
        $oPluginFreeHtml = new PluginFreeHtml;
        $oOnePluginFreeHtml = $oPluginFreeHtml->findOneByid_page($iId);

        if (isset($_POST) && count($_POST) > 0 && isset($_POST['content'])) {

            if ($oOnePluginFreeHtml) {

                $oOnePluginFreeHtml->set_content($_POST['content'])
                                   ->set_type($_POST['type'])
                                   ->save();

                $this->redirect($this->url->getUrl('page').'?msg='.urlencode($this->translator->_('ModifiedSuccessfully')));
            }
            else {

                $oOnePluginFreeHtml = new EntityPluginFreeHtml;
                $oOnePluginFreeHtml->set_content($_POST['content'])
                                   ->set_type($_POST['type'])
                                   ->set_id_page($iId)
                                   ->save();

                $this->redirect($this->url->getUrl('page').'?msg='.urlencode($this->translator->_('ModifiedSuccessfully')));
            }
        }

        $oThis->layout
              ->assign('model', '/src/plugins/FreeHtml/View/Update.tpl')
              ->assign('sTitle', $this->translator->_('ModifyPage'))
              ->assign('sSecondUrl', $this->url->getUrl('page'))
              ->assign('sThirdTitle', $this->translator->_('ModifyPage'))
              ->assign('oPluginFreeHtml', $oOnePluginFreeHtml);
    }

    /**
     * the main page
     *
     * @access public
     * @return void
     */
    public function install()
    {
        $this->installDb;
    }
}


text: import { type } from "./mod.js";


text:
<?php

namespace PhpGitHooks\Module\Git\Infrastructure\Git;

use PhpGitHooks\Module\Git\Model\PrePushOriginalExecutorInterface;
use Symfony\Component\Process\Process;

class PrePushOriginalExecutor implements PrePushOriginalExecutorInterface
{
    /**
     * @param string $remote
     * @param string $url
     *
     * @return string|null
     */
    public function execute($remote, $url)
    {
        $process = new Process(sprintf('./%s %s %s', 'pre-push-original', $remote, $url));
        $process->run();

        return $process->getOutput();
    }
}


text:
from __future__ import generators
import sys
import copy

class OrderedDict(dict):
    """This is specialization of dictionary that preserves order of insertion
       when enumerating keys or items."""

    # These must be overriden in derived class:

    def __init__(self):
        dict.__init__(self)
        self.order = []

    def __setitem__(self, key, value):
        if not self.has_key(key):
            self.order.append(key)
        dict.__setitem__(self, key, value)
    def __delitem__(self, key):
        self.order.remove(key)
        dict.__delitem__(self, key)

    def __iter__(self):
        return iter(self.order)

    def __deepcopy__(self, memo):
        c = OrderedDict()
        for k in self.iterkeys():
            c[k] = copy.deepcopy(self[k])
        return c

    # The rest is implemented using above methods:

    def update(self, dict):
        assert 0 # not permitted!
    def __copy__(self):
        assert 0 # not permitted!

    def iterkeys(self):
        return self.__iter__()
    def iteritems(self):
        for k in self.iterkeys():
           yield (k, self[k])
    def itervalues(self):
        for k in self.iterkeys():
           yield self[k]

    def keys(self):
        return list(self.iterkeys())
    def items(self):
        return list(self.iteritems())
    def values(self):
        return list(self.itervalues())

class OrderedDictWithClasification(OrderedDict):
    """Like OrderedDict, but items are categorized into several groups and
       order is preserved only within the group. Groups are identified by their
       number (starting from 0) and are sorted by increasing group number.
       For example, this sequence of insertions:
          d[3] = ObjInGroup0
          d[2] = ObjInGroup1
          d[1] = ObjInGroup1
          d[8] = ObjInGroup0
       will result in this list returned by d.keys():
          [3,8,2,1]
    """

    def __init__(self, numGroups, getGroupPredicate):
        """numGroups is number of groups the values are classified into
           and getGroupPredicate is function that takes the value (not key!)
           as argument and returns group number."""
        OrderedDict.__init__(self)
        self.order = [ [] for i in range(0, numGroups) ]
        self.getGroup = getGroupPredicate

    def __setitem__(self, key, value):
        if not self.has_key(key):
            self.order[self.getGroup(value)].append(key)
        dict.__setitem__(self, key, value)
    def __delitem__(self, key):
        for group in self.order:
            if key in group:
                group.remove(key)
                return
        dict.__delitem__(self, key)

    def __iter__(self):
        for group in self.order:
            for k in group:
               yield k

    def __deepcopy__(self, memo):
        c = OrderedDictWithClasification(len(self.order), self.getGroup)
        for k in self.iterkeys():
            c[k] = copy.deepcopy(self[k])
        return c

if sys.version_info >= (2,4):

    class MergedDict:
        """This class implements "merged dictionary" - fake dictionary that
           serves as a proxy to ordered list of "slave" dictionaries. Lookups
           are performed by trying the slaves in order. Insertions and removals
           are done using temporary dict object that is initially empty."""
        def __init__(self):
            self.localdict = {}
            self.dicts = []

        def add(self, dict):
            """Adds a dictionary to the front of the list (i.e. variables in
               the latest added dictionary take precendence over variables
               from the lists added earlier)."""
            self.dicts.insert(0, dict)

        def dictForEval(self):
            """Returns dictionary that can be passed to eval()."""
            return self

        def __getitem__(self, key):
            if key in self.localdict:
                return self.localdict[key]
            for d in self.dicts:
                if key in d: return d[key]
            raise KeyError(key)

        def __contains__(self, key):
            for d in self.dicts:
                if key in d: return True
            return key in self.localdict

        def __setitem__(self, key, value):
            self.localdict.__setitem__(key, value)

        def __delitem__(self, key):
            self.localdict.__delitem__(key)

else:

    # MergedDict implementation for Python <= 2.3, which depends on an ugly
    # hack from bottlenecks.c:
    import bkl_c

    class MergedDict:
        def __init__(self):
            self.proxy = bkl_c.ProxyDictionary()
            self.dicts = []

        def add(self, dict):
            self.proxy.add(dict)
            self.dicts.insert(0, dict)

        def dictForEval(self):
            return self.proxy.dict

        def __contains__(self, key):
            for d in self.dicts:
                if key in d: return True
            return False