def add(silent=False):
    params = menuUtils.getCurrentParams()
    meta = menuUtils.getCurrentMeta()

    import utils
    utils.outputDict(params, 'menu_addtofaves - params')
    utils.outputDict(meta, 'menu_addtofaves - meta')

    if params == None:
        if not silent:
            import utils
            utils.DialogOK(utils.GETTEXT(30260))
        return

    menuUtils.addToFaves(params, meta)
def add(silent=False):
    params = menuUtils.getCurrentParams()
    meta   = menuUtils.getCurrentMeta()

    import utils
    utils.outputDict(params, 'menu_addtofaves - params')
    utils.outputDict(meta,   'menu_addtofaves - meta')

    if params == None:
        if not silent:
            import utils
            utils.DialogOK(utils.GETTEXT(30260))
        return

    menuUtils.addToFaves(params, meta)
Exemple #3
0
def addToFaves(params, meta=None):
    try:
        label = params['label']
        thumb = params['thumb']
        fanart = params['fanart']
        path = params['path']
        desc = params['description']
        window = params['window']
        filename = params['filename']
        isFolder = params['isfolder']

        cmd = getCmd(path, fanart, desc, window, filename, isFolder, meta)
        copyFave(label, thumb, cmd)
    except Exception, e:
        utils.log('\n\nError in menuUtils.addToFaves : %s' % str(e))
        utils.outputDict(params)
Exemple #4
0
def addToFaves(params, meta=None):
    try:
        label    = params['label']
        thumb    = params['thumb']
        fanart   = params['fanart']
        path     = params['path']
        desc     = params['description']
        window   = params['window']
        filename = params['filename']
        isFolder = params['isfolder']

        cmd = getCmd(path, fanart, desc, window, filename, isFolder, meta)
        copyFave(label, thumb, cmd)
    except Exception, e:
        utils.log('\n\nError in menuUtils.addToFaves : %s' % str(e))
        utils.outputDict(params)
def doMenu(mode):
    import menuUtils

    utils.log('**** Context Menu Information ****')

    window = xbmcgui.getCurrentWindowId()

    DEBUG = ADDON.getSetting('DEBUG') == 'true'
    if DEBUG:
        utils.DialogOK('Current Window ID %d' % window)

    utils.log('Capture window\t: %d' % window)

    if window > 12999:
        doStandard(useScript=False)
        return

    # to prevent master profile setting being used in other profiles
    if mode == 0 and ADDON.getSetting('CONTEXT') != 'true':
        doStandard(useScript=False)
        return

    folder = xbmc.getInfoLabel('Container.FolderPath')
    path = xbmc.getInfoLabel('ListItem.FolderPath')

    #ignore if in Super Favourites
    if (ADDONID in folder) or (ADDONID in path):
        doStandard(useScript=False)
        return

    if mode == 0 and whitelisted():
        doStandard(useScript=False)
        return

    try:
        params = menuUtils.getCurrentParams()
    except:
        params = None

    if params == None:
        doStandard(useScript=False)
        return

    try:
        meta = menuUtils.getCurrentMeta()
    except:
        meta = {}

    utils.outputDict(params, 'Capture Parameters')
    utils.outputDict(meta, 'Capture Metadata')

    folder = params['folder']
    path = params['path']
    label = params['label']
    filename = params['filename']
    thumb = params['thumb']
    icon = params['icon']
    playable = params['isplayable']
    fanart = params['fanart']
    isFolder = params['isfolder']
    hasVideo = params['hasVideo']
    desc = params['description']
    window = params['window']
    file = params['file']
    isStream = params['isstream']

    choice = 0
    menu = []
    localAddon = None

    if MENU_QUICKLAUNCH:
        menu.append((GETTEXT(30219), _QUICKLAUNCH))

    plugins = []
    try:
        plugins = getPlugins()
        addPlugins(menu, plugins, params, _EXTRABASE)
    except Exception as e:
        utils.log('Error adding plugins : %s' % str(e))

    if len(path) > 0:

        if MENU_ADDTOFAVES:
            menu.append((GETTEXT(30047), _ADDTOFAVES))

        if MENU_ADDON_SETTINGS:
            localAddon = utils.findAddon(path)
            if localAddon:
                name = utils.getSettingsLabel(localAddon)
                menu.append((name, _SETTINGS))

        if MENU_DEF_ISEARCH:
            default = getDefaultSearch()
            if len(default) > 0:
                menu.append((GETTEXT(30098) % default, _SEARCHDEF))

        if MENU_ISEARCH: menu.append((GETTEXT(30054), _SEARCH))

        if MENU_IRECOMMEND: menu.append((GETTEXT(30088), _RECOMMEND))

        if MENU_COPY_PROPS: menu.append((GETTEXT(30209), _COPYITEM))

        if MENU_VIEW_IMAGES:
            if len(thumb) > 0 or len(fanart) > 0:
                menu.append((GETTEXT(30216), _SHOWIMAGE))

    if MENU_SF_SETTINGS:
        menu.append((GETTEXT(30049), _SF_SETTINGS))

    stdMenu = False
    if MENU_STD_MENU:
        if (len(path) > 0) or (window == 10034):  #10034 is profile dialog
            stdMenu = True
            menu.append((GETTEXT(30048), _STD_MENU))

    if hasVideo:
        if MENU_DOWNLOADS and isStream:
            menu.append((GETTEXT(30259), _DOWNLOAD))

        if len(menu) == 0:
            doStandard(useScript=False)
            return

        nowPlaying = GETTEXT(30220)
        menu.append((nowPlaying, _PLAYLIST))

    if len(menu) == 0 or (len(menu) == 1 and stdMenu):
        doStandard(useScript=False)
        return

    xbmcgui.Window(10000).setProperty('SF_MENU_VISIBLE', 'true')

    dialog = ADDON.getSetting('CONTEXT_STYLE') == '1'

    import menus

    if dialog:
        choice = menus.selectMenu(utils.TITLE, menu)
    else:
        choice = menus.showMenu(
            ADDONID, menu,
            useBuiltin=False)  #False to allow right-click to std context menu

    utils.log('selection\t\t: %s' % choice)

    if choice >= _EXTRABASE:
        module = (choice - _EXTRABASE) / 1000
        option = (choice - _EXTRABASE) % 1000

        utils.log('plugin\t\t: %s' % module)
        utils.log('option\t\t: %s' % option)

        try:
            plugins[module].process(option, params)
        except Exception as e:
            utils.log('Error processing plugin: %s' % str(e))

    if choice == _QUICKLAUNCH:
        try:
            quickLaunch()
        except:
            pass

    if choice == _STD_MENU:
        doStandard(useScript=True)

    if choice == _PLAYLIST:
        activateWindow('videoplaylist')

    if choice == _DOWNLOAD:
        try:
            menuUtils.doDownload(file)
        except:
            pass

    if choice == _SF_SETTINGS:
        utils.ADDON.openSettings()

    if choice == _SETTINGS:
        xbmcaddon.Addon(localAddon).openSettings()

    if choice == _ADDTOFAVES:
        menuUtils.addToFaves(params, meta)

    if choice == _LAUNCH_SF:
        utils.LaunchSF()

    if choice in [_SEARCH, _SEARCHDEF, _RECOMMEND]:
        if utils.ADDON.getSetting('STRIPNUMBERS') == 'true':
            label = utils.Clean(label)

        thumb = thumb if len(thumb) > 0 else 'null'
        fanart = fanart if len(fanart) > 0 else 'null'

        #declared in default.py
        _SUPERSEARCH = 0
        _SUPERSEARCHDEF = 10
        _RECOMMEND_KEY = 2700

        valid = [10001, 10002, 10025, 10502]

        if window not in valid:
            window = 10025  #video window

        import urllib

        if choice == _RECOMMEND:
            mode = _RECOMMEND_KEY
        else:
            mode = _SUPERSEARCH if (choice == _SEARCH) else _SUPERSEARCHDEF

        if mode == _SUPERSEARCHDEF:
            return launchDefaultSearch(label)

        try:
            meta = urllib.quote_plus(utils.convertDictToURL(meta))
        except:
            meta = ''

        cmd = 'ActivateWindow(%d,"plugin://%s/?mode=%d&keyword=%s&image=%s&fanart=%s&meta=%s")' % (
            window, ADDONID, mode, urllib.quote_plus(label),
            urllib.quote_plus(thumb), urllib.quote_plus(fanart), meta)

        activateCommand(cmd)

    if choice == _COPYITEM:
        #if not fanart:
        #    fanart = thumb

        cmd = menuUtils.getCmd(path, fanart, desc, window, filename, isFolder,
                               meta)

        import clipboard
        clipboard.setPasteProperties(thumb, fanart, desc, label, cmd, meta)

    if choice == _SHOWIMAGE:
        #if not fanart:
        #    fanart = thumb

        import viewer
        viewer.show(fanart, thumb, ADDONID)
Exemple #6
0
def doMenu(mode):
    import menuUtils

    utils.log('**** Context Menu Information ****')

    window = xbmcgui.getCurrentWindowId()

    DEBUG = ADDON.getSetting('DEBUG') == 'true'
    if DEBUG:
        utils.DialogOK('Current Window ID %d' % window)

    utils.log('Capture window\t: %d' % window)

    if window > 12999:
        doStandard(useScript=False)
        return

    # to prevent master profile setting being used in other profiles
    if mode == 0 and ADDON.getSetting('CONTEXT') != 'true':
        doStandard(useScript=False)
        return

    folder = xbmc.getInfoLabel('Container.FolderPath')
    path = xbmc.getInfoLabel('ListItem.FolderPath')

    #ignore if in Super Favourites
    if (ADDONID in folder) or (ADDONID in path):
        doStandard(useScript=False)
        return

    if mode == 0 and whitelisted():
        doStandard(useScript=False)
        return

    try:
        params = menuUtils.getCurrentParams()
    except:
        params = None

    if params == None:
        doStandard(useScript=False)
        return

    try:
        meta = menuUtils.getCurrentMeta()
    except:
        meta = {}

    utils.outputDict(params, 'Capture Parameters')
    utils.outputDict(meta, 'Capture Metadata')

    folder = params['folder']
    path = params['path']
    label = params['label']
    filename = params['filename']
    thumb = params['thumb']
    icon = params['icon']
    playable = params['isplayable']
    fanart = params['fanart']
    isFolder = params['isfolder']
    hasVideo = params['hasVideo']
    desc = params['description']
    window = params['window']
    file = params['file']
    isStream = params['isstream']

    choice = 0
    menu = []
    localAddon = None

    if MENU_QUICKLAUNCH:
        menu.append((GETTEXT(30219), _QUICKLAUNCH))

    plugins = []
    try:
        plugins = getPlugins()
        addPlugins(menu, plugins, params, _EXTRABASE)
    except Exception, e:
        utils.log('Error adding plugins : %s' % str(e))
Exemple #7
0
def completeAnalysis(geneNetwork,
                     genome2sequence,
                     n,
                     c,
                     a=None,
                     clustType=None,
                     UniqID=None,
                     sep=None,
                     keyList=None,
                     handle=sys.stderr,
                     config=None):
    """Perform complete bipartite and twin analysis at a given identity threshold n"""
    directory = "graphs" + str(n)
    try:
        os.mkdir(directory)
    except OSError:
        pass
    # Names and file definitions
    if clustType == 'cc':
        seqCompFile = "CC.nodes"  # compFile for sequences
        eFile = "CC.edges"
        iFile = "CC.info"
    elif clustType == 'families':
        seqCompFile = "family.nodes"  # compFile for sequences
        eFile = "family.edges"
        iFile = "family.info"
    else:
        sys.exit("Bad clustering type -- see -C option")
    edgeFile = "graph.edges"  # edgeFile
    trailFile = "graph.trail"  # trailFile
    geneNetworkDico = geneNetwork + ".dico"
    geneNetworkGenes = geneNetwork + ".genes"
    ## ==============================
    # c) assemble sequence families by computing the connected components
    cmd2 = """%s -i %s -d %s -n %s -m %s -p %d""" % (
        familydetector, geneNetwork, directory, geneNetworkGenes, clustType, n)
    printLog(
        "--------------------------------------------------\nRunning %s" %
        cmd2, handle)
    proc2 = Popen(args=[cmd2], shell=True, stdout=PIPE, executable="/bin/bash")
    out = proc2.communicate()[0]
    printLog(out.decode('utf-8'), handle)
    mySeqCompFile = os.path.join(directory, seqCompFile)
    myiFile = os.path.join(directory, iFile)
    myeFile = os.path.join(directory, eFile)
    # renumber back families through geneNetworkDico
    dic1 = ut.loadMapping(geneNetworkDico)
    dic2 = ut.node2communityFasta(mySeqCompFile, sep=sep)
    compDict = ut.composeDict(dic1, dic2)
    ut.outputDict(compDict, mySeqCompFile, sep=sep)
    cleanCmd = """rm %s %s""" % (myiFile, myeFile)
    procClean = Popen(args=[cleanCmd], shell=True, executable="/bin/bash")
    procClean.communicate()
    ## B) from the sequence families to the bipartite graph
    # a) Cluster sequence families and quotient the graph
    cmd3 = """%s -c %s -k %s -d %s %s %s %s""" % (
        FactorGraph, mySeqCompFile, UniqID, directory, genome2sequence,
        edgeFile, trailFile)
    printLog(
        "--------------------------------------------------\nRunning %s" %
        cmd3, handle)
    FG.Main(edgeFile=genome2sequence,
            outEdgeFile=edgeFile,
            outTrailFile=trailFile,
            direct=directory,
            community=mySeqCompFile,
            comm_id=UniqID,
            sep=sep,
            log=handle,
            header=cmd3)
    os.chdir(directory)
    printLog(
        "--------------------------------------------------\ncd %s" %
        directory, handle)
    ##
    rad = "graph0"
    # b) Remove the degree one nodes from the sequence side
    edges = rad + ".edges"
    cmd4 = """%s -d 1 -u 2 %s %s""" % (shaveGraph, edgeFile, edges)
    printLog(
        "--------------------------------------------------\nRunning %s" %
        cmd4, handle)
    SG.Main(edgeFile=edgeFile,
            outEdgeFile=edges,
            degree=1,
            nodeType=2,
            sep=sep,
            log=handle)
    # d) Compute twins and twin supports of the bipartite graph
    twins = rad + ".twins"
    twinComp = rad + ".twin_comp"
    cmd6 = """%s -o %s -u 2 -c %s %s """ % (DetectTwins, twins, twinComp,
                                            edges)
    printLog(
        "--------------------------------------------------\nRunning %s" %
        cmd6, handle)
    try:
        DT.Main(edgeFile=edges,
                outFile=twins,
                sep=sep,
                unilat='2',
                comp=twinComp,
                log=handle)
    except IOError as e:
        printLog("Error in %s: %s\nExiting." % (cmd6, e), handle)
        return ()
    ## C) from the bipartite graph to the twins and articulation points
    # a) twin quotienting
    twinDir = "TwinQuotient"
    try:
        os.mkdir(twinDir)
    except OSError:
        pass
    rad = "graph1"
    newEdges = rad + ".edges"
    newTrail = rad + ".trail"
    cmd7 = """%s -c %s -k %s -d %s -t %s %s %s %s""" % (
        FactorGraph, twins, UniqID, twinDir, trailFile, edges, newEdges,
        newTrail)
    printLog(
        "--------------------------------------------------\nRunning %s" %
        cmd7, handle)
    try:
        FG.Main(edgeFile=edges,
                outEdgeFile=newEdges,
                outTrailFile=newTrail,
                direct=twinDir,
                community=twins,
                comm_id=UniqID,
                in_trail=trailFile,
                sep=sep,
                log=handle,
                header=cmd7)
    except IOError as e:
        printLog("Error in %s: %s\nExiting." % (cmd7, e), handle)
        return ()
    os.chdir(twinDir)
    printLog(
        "--------------------------------------------------\ncd %s" % twinDir,
        handle)
    # b) Computing articulation points and biconnected components
    ART, BIC = getArticulationPoints(newEdges)
    artPoints = rad + ".art"
    aP = open(artPoints, "w")
    printLog(
        "--------------------------------------------------\nPrinting %d articulation points in %s"
        % (len(ART), artPoints), handle)
    for node in ART:
        outString = """%s\t%s\n""" % (node, ",".join(
            [str(ID) for ID in BIC[node]]))
        aP.write(outString)
    aP.close()
    bcNb = 0
    bicFile = rad + ".bic_comp"
    bC = open(bicFile, "w")
    for node in BIC:
        for ID in BIC[node]:
            bcNb = max(bcNb, ID)
            bC.write("""%s\t%d\n""" % (node, ID))
    bC.close()
    printLog(
        "--------------------------------------------------\nPrinting %d biconnected components in %s"
        % (bcNb + 1, bicFile), handle)
    ## D) annotations and twin component analysis
    if a:
        edges = rad + ".edges"
        twins = rad + ".twins"
        twinComp = rad + ".twin_comp"
        cmd9 = """%s -o %s -u 2 -c %s %s """ % (DetectTwins, twins, twinComp,
                                                edges)
        printLog(
            "--------------------------------------------------\nRunning %s" %
            cmd9, handle)
        try:
            DT.Main(edgeFile=edges,
                    outFile=twins,
                    sep=sep,
                    unilat='2',
                    comp=twinComp,
                    log=handle)
        except IOError as e:
            printLog("Error in %s: %s\nExiting." % (cmd9, e), handle)
            return ()
        runDescription(a,
                       radical=rad,
                       ID=UniqID,
                       keyList=keyList,
                       handle=handle,
                       config=config)
Exemple #8
0
def Main(edgeFile=None,outFile=None,sep=None,unilat=None,twin_supp=None,Twin_Supp=None,min_supp=None,min_size=None,nodeType=None,comp=None,debug=None,log=None):
    """ Main program """
    i0 = time.clock()
    inext = i0
    ## File reading options ========================================
    if not outFile:
        outFile = edgeFile+".twins"
    thr = min_supp
    try:
        k_part = int(nodeType)
    except (TypeError,ValueError):
        k_part = nodeType
    ## File reading ========================================
    if not os.stat(edgeFile).st_size:
        if myModule() == "__main__.py":
            sys.exit("Error: Empty file %s" % edgeFile)
        else:
            raise IOError("Empty file %s" % edgeFile)
    g = ut.myReadGraph(edgeFile)
    print(g.summary())
    id2name = {}
    name2id = {}
    for n in g.vs():
        name = n['name']
        ind = n.index
        id2name[ind] = name
        name2id[name] = ind
    inext = myTimer(i0,"Loading graph",handle=log)
    ## Program body ===========================================
    # Adjacency list computation ------------------------------
    getName = lambda x:id2name[x]
    nodes = None
    if unilat:
        typeSet = set(map(lambda x:int(x),unilat.strip().split(",")))
        typeDict = defaultdict(int)
        if k_part == 2 or not k_part:
            typeDict.update(ut.rawNodeType(edgeFile))
        elif k_part != 1:
            typeDict.update(ut.loadNodeType(k_part))
        nodes = (n.index for n in g.vs() if typeDict[n['name']] in typeSet)
    ADJ = ut.getAdjlist(g,nodes=nodes)
    inext = myTimer(inext,"Computation of adjacency list",handle=log)
    # Twin computation ----------------------------------------
    support,twins = ut.detectRepeated(ADJ,k_init=0,debug=debug)   # support: groupID -> common_list_of_neighbours; twins: node -> groupID_of_its_twin_class
    inext = myTimer(inext,"Computation of twins",handle=log)
    new_support = dict([(gid,tuple(map(getName,support[gid]))) for gid in support])
    new_twins = dict([(id2name[node],twins[node]) for node in twins])
    support = new_support
    twins = new_twins
    inext = myTimer(inext,"Renumbering of twins",handle=log)
    sniwt = ut.InvertMap(twins)   # groupID -> list_of_twin_nodes
    inext = myTimer(inext,"Computation of twin support",handle=log)
    # Computation of components (twins + support)
    if comp:
        with open(comp,'w') as h:
            for key,val in iter(twins.items()):
                outString = str(key)+sep+str(val)+"\n"
                h.write(outString)
            inext = myTimer(inext,"Writing twins file",handle=log)
            for val,nodes in iter(support.items()):
                for node in nodes:
                    outString = str(node)+sep+str(val)+"\n"
                    h.write(outString)
            inext = myTimer(inext,"Writing twins component file",handle=log)
    # Computation of twinSupport (twinID twinNb twinSupport)
    if twin_supp:
        with open(twin_supp,'w') as g:
            for i,nodeList in iter(sniwt.items()):
                supp = support[i]
                if len(supp) >= thr and len(nodeList) >= min_size:   # Threshold for trivial twins (new option 15/12/15)
                    vals = [str(i),str(len(nodeList)),str(len(supp))]
                    vals.extend(list(map(lambda x:str(x),supp)))
                    g.write("\t".join(vals)+"\n")
        inext = myTimer(inext,"Writing twins support file",handle=log)
    # Computation of TwinSupport (twinID twinNodes twinSupport)
    if Twin_Supp:
        with open(Twin_Supp,'w') as g:
            for i,nodeList in iter(sniwt.items()):
                supp = support[i]
                if len(supp) >= thr and len(nodeList) >= min_size:   # Threshold for trivial twins (new option 15/12/15)
                    myTwins = ",".join(map(lambda x:str(x),nodeList))
                    mySupport = ",".join(map(lambda x:str(x),supp))
                    vals = [str(i)]
                    vals.extend(list(map(lambda x:str(x),supp)))
                    g.write("\t".join(vals)+"\n")
        inext = myTimer(inext,"Writing Twins Support file",handle=log)
    ut.outputDict(twins,outFile,sep=sep)
    allTwins = len(sniwt.keys())
    t = len([i for (i,v) in iter(sniwt.items()) if len(v) == 1])
    try:
        tp = 100*float(t)/float(allTwins)
    except:
        tp = 0
    nt = allTwins - t
    try:
        ntp = 100*float(nt)/float(allTwins)
    except:
        ntp = 0
    printLog("""Found %s twins, %s trivial twins (%.2f%%) and %s non-trivial twins (%.2f%%)""" % (allTwins,t,tp,nt,ntp),log)
    ## Ending ======================================================
    prog = myModule()
    if prog == "__main__.py":
        prog = sys.argv[0].split("/")[-1]
    inext = myTimer(i0,"Total computing time for %s" % prog,handle=log)
    return
Exemple #9
0
def doMenu(mode):
    import menuUtils

    utils.log('**** Context Menu Information ****')

    window = xbmcgui.getCurrentWindowId()

    DEBUG = ADDON.getSetting('DEBUG') == 'true'
    if DEBUG:
        utils.DialogOK('Current Window ID %d' % window)

    utils.log('Capture window\t: %d' % window)

    #active = [0, 1, 2, 3, 25, 40, 500, 501, 502, 601, 2005]
    #if window-10000 not in active:
    #    doStandard(useScript=False)
    #    return

    if window > 12999:
        doStandard(useScript=False)
        return

    # to prevent master profile setting being used in other profiles
    if mode == 0 and ADDON.getSetting('CONTEXT') != 'true':
        doStandard(useScript=False)
        return

    folder = xbmc.getInfoLabel('Container.FolderPath')
    path   = xbmc.getInfoLabel('ListItem.FolderPath')

    #ignore if in Super Favourites
    if (ADDONID in folder) or (ADDONID in path):
        doStandard(useScript=False)
        return

    if mode == 0 and whitelisted():
        doStandard(useScript=False)
        return

    params = menuUtils.getCurrentParams()
    meta   = menuUtils.getCurrentMeta()

    if params == None:
        doStandard(useScript=False)
        return

    utils.outputDict(params, 'Capture Parameters')
    utils.outputDict(meta,   'Capture Metadata')

    folder   = params['folder']
    path     = params['path']
    label    = params['label']
    filename = params['filename']
    thumb    = params['thumb']
    icon     = params['icon']
    playable = params['isplayable']
    fanart   = params['fanart']
    isFolder = params['isfolder']
    hasVideo = params['hasVideo']
    desc     = params['description']       
    window   = params['window']
    file     = params['file']
    isStream = params['isstream']

    choice     = 0
    menu       = []
    localAddon = None

    if MENU_QUICKLAUNCH:
        menu.append((GETTEXT(30219), _QUICKLAUNCH))

    plugins    = []
    try:
        plugins = getPlugins()
        addPlugins(menu, plugins, params, _EXTRABASE)
    except Exception, e:
        utils.log('Error adding plugins : %s' % str(e))