# Poly Report, by Joshua Buck, (c)2019, all rights reserved

"""
import jbPolyReport
jbPolyReport.jbPolyReportGo()
"""

import maya.cmds as cmds

defColor = 0.3, 0.3, 0.3
passColor = (0.17, 1.0, 0.17)
warningColor = (1.0, 1.0, 0.17)
errorColor = (1.0, 0.17, 0.17)

def jbPolyReportGo():
    jbPolyReportWIN()
    jbPolyReportUI()

def jbPolyReportWIN():
    version = 1.01
    if cmds.window("jbPrWin", exists=True):
        cmds.deleteUI("jbPrWin", window=True)

    # if cmds.windowPref("jbPrWin", exists=True):
    #     cmds.windowPref('jbPrWin', remove=True)

    cmds.window("jbPrWin", title="Poly Report  v" + str(version), mnb=False, mxb=False, s=True)

    cmds.columnLayout("mainUI_C", p="jbPrWin")

    cmds.showWindow("jbPrWin")
    cmds.window("jbPrWin", e=True, h=1)

def jbPolyReportUI():
    mainCW = 300
    warningTitleCW = 100
    warningContentCW = 280

    # General Mesh Info
    cmds.rowColumnLayout(nc=1, cw=[(1, mainCW)], p="mainUI_C")
    cmds.separator(h=4, style='none')

    cmds.rowColumnLayout(nc=2, cw=[(1, 100), (2,180)], p="mainUI_C")
    cmds.text(l="Mesh Name:   ", align="right", font="boldLabelFont")
    cmds.text("meshName_TX", l='No Mesh', align="left", font="boldLabelFont")

    cmds.rowColumnLayout(nc=1, cw=[(1, 280)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8)

    cmds.rowColumnLayout(nc=4, cw=[(1, 80),(2,60),(3,75),(4,50)], p="mainUI_C")

    cmds.text(l='Triangles:  ', align="right")
    cmds.text("numTriangles_TX", l='', align="left")

    cmds.text(l='Edges:  ', align="right")
    cmds.text("numEdges_TX", l='', align="left")

    cmds.text(l='Faces:  ', align="right")
    cmds.text("numFaces_TX", l='', align="left")

    cmds.text(l='Vertices:  ', align="right")
    cmds.text("numVerts_TX", l='', align="left")

    cmds.text(l='Mesh Shells:  ', align="right")
    cmds.text("numMeshShells_TX", l='', align="left")

    cmds.text(l='Shapes:  ', align="right")
    cmds.text("numShapes_TX", l='', align="left")

    cmds.text(l='Parents:  ', align="right")
    cmds.text("parents_TX", l='', align="left")

    cmds.text(l='Children:  ', align="right")
    cmds.text("children_TX", l='', align="left")

    cmds.rowColumnLayout(nc=1, cw=[(1, mainCW)], p="mainUI_C")
    cmds.separator(h=4, style='none')

    cmds.rowColumnLayout(nc=4, cw=[(1, 80), (2, 60), (3, 75), (4, 50)], p="mainUI_C")

    cmds.text(l='Materials:  ', align="right")
    cmds.text("materials_TX", l='', align="left")

    cmds.text(l='UV Sets:  ', align="right")
    cmds.text("uvSets_TX", l='', align="left")

    cmds.text(l='UV Points:  ', align="right")
    cmds.text("uvPoints_TX", l='', align="left")

    cmds.text(l='UV Shells:  ', align="right")
    cmds.text("uvShells_TX", l='', align="left")

    cmds.rowColumnLayout(nc=1, cw=[(1, mainCW)], p="mainUI_C")
    cmds.separator(h=4, style='none')

    cmds.rowColumnLayout(nc=4, cw=[(1, 80), (2, 40), (3, 95), (4, 74)], p="mainUI_C")

    cmds.text(l='Has History:  ', align="right")
    cmds.text("hasHistory_TX", l='', align="left")

    cmds.text(l='Transformations:  ', align="right")
    cmds.text("transformations_TX", l='', align="left")

    cmds.rowColumnLayout(nc=1, cw=[(1, 280)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8)

    # Face Info
    cmds.rowColumnLayout(nc=3, cw=[(1, 130), (2, 14), (3, 75)], cs=[(1,0),(2,6),(3,6)], p="mainUI_C")

    cmds.text(l='Quadrilaterals:', align="right")
    cmds.button("quadFaces_BUT", l='', h=14, bgc=defColor)
    cmds.text("quadFaces_TX", l='', align="left")

    cmds.text(l='Defined Triangles:', align="right")
    cmds.button("triangleFaces_BUT", l='', h=14, bgc=defColor)
    cmds.text("triangleFaces_TX", l='', align="left")

    cmds.text(l='N-Gons:', align="right")
    cmds.button("faceFivePlusEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("faceFivePlusEdges_TX", l='', align="left")

    cmds.rowColumnLayout(nc=1, cw=[(1, mainCW)], p="mainUI_C")
    cmds.separator(h=8, style='none')

    # Vertex Info
    cmds.rowColumnLayout(nc=3, cw=[(1, 130), (2, 14), (3, 75)], cs=[(1,0),(2,6),(3,6)], p="mainUI_C")

    cmds.text(l='Vertices w/2 Edges:', align="right")
    cmds.button("vtxTwoEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("vtxTwoEdges_TX", l='', align="left")

    cmds.text(l='Vertices w/3 Edges:', align="right")
    cmds.button("vtxThreeEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("vtxThreeEdges_TX", l='', align="left")

    cmds.text(l='Vertices w/4 Edges:', align="right")
    cmds.button("vtxFourEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("vtxFourEdges_TX", l='', align="left")

    cmds.text(l='Vertices w/5+ Edges:', align="right")
    cmds.button("vtxFivePlusEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("vtxFivePlusEdges_TX", l='', align="left")

    # General Cleanup Info
    cmds.rowColumnLayout(nc=1, cw=[(1, 280)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8)
    # cmds.text(l='Examine / Cleanup', font="boldLabelFont")
    # cmds.separator(h=5, style='none')

    cmds.rowColumnLayout(nc=3, cw=[(1, 130), (2, 14), (3, 75)], cs=[(1, 0), (2, 6), (3, 6)], p="mainUI_C")

    cmds.text(l='Faces w/Zero Area:', align="right")
    cmds.button("faceZeroAreaSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("faceZeroArea_TX", l='', align="left")

    cmds.text(l='Faces w/2 Edges:', align="right")
    cmds.button("faceTwoEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("faceTwoEdges_TX", l='', align="left")

    cmds.text(l='Vertices Sharing Space:', align="right")
    cmds.button("vtxSharingSpaceSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("vtxSharingSpace_TX", l='', align="left")

    cmds.text(l='Nonmanifold Edges:', align="right")
    cmds.button("nonmanifoldEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("nonmanifoldEdges_TX", l='', align="left")

    cmds.text(l='Nonmanifold UV Edges:', align="right")
    cmds.button("nonmanifoldUvEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("nonmanifoldUvEdges_TX", l='', align="left")

    cmds.text(l='Nonmanifold UVs:', align="right")
    cmds.button("nonmanifoldUvsSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("nonmanifoldUvs_TX", l='', align="left")

    cmds.text(l='UV Faces w/Zero Area:', align="right")
    cmds.button("uvZeroAreaFaces_BUT", l='', h=14, bgc=defColor)
    cmds.text("uvZeroAreaFaces_TX", l='', align="left")

    cmds.text(l='Lamina Faces:', align="right")
    cmds.button("laminaFacesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("laminaFaces_TX", l='', align="left")

    cmds.text(l='Invalid Edges:', align="right")
    cmds.button("invalidEdgesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("invalidEdges_TX", l='', align="left")

    cmds.text(l='Invalid Vertices:', align="right")
    cmds.button("invalidVerticesSelect_BUT", l='', h=14, bgc=defColor)
    cmds.text("invalidVertices_TX", l='', align="left")

    cmds.rowColumnLayout(nc=1, cw=[(1, 280)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8)

    # Notice
    cmds.rowColumnLayout(nc=1, cw=[(1, warningTitleCW)], cs=[(1,10)],  p="mainUI_C")
    cmds.text(l="Notice:", font="boldLabelFont", align="left")

    cmds.rowColumnLayout("meshNotice_RCL", nc=1, cw=[(1, warningContentCW)], cs=[(1,20)], p="mainUI_C")

    # Warnings
    cmds.rowColumnLayout(nc=1, cw=[(1, warningTitleCW)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8, style='none')
    cmds.text(l="Warnings:", font="boldLabelFont", align="left")

    cmds.rowColumnLayout("meshWarnings_RCL", nc=1, cw=[(1, warningContentCW)], cs=[(1,15)], p="mainUI_C")

    # Errors
    cmds.rowColumnLayout(nc=1, cw=[(1, warningTitleCW)],cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=8, style='none')
    cmds.text(l="Errors:", font="boldLabelFont", align="left")

    cmds.rowColumnLayout("meshErrors_RCL", nc=1, cw=[(1, warningContentCW)], cs=[(1,15)], p="mainUI_C")

    # Action Button
    cmds.rowColumnLayout(nc=1, cw=[(1, 280)], cs=[(1,10)], p="mainUI_C")
    cmds.separator(h=10, style='none')
    cmds.button(l='Report', h=30, c=lambda args: generatePolyReport())
    cmds.separator(h=8, style='none')

def generatePolyReport():
    sel = cmds.ls(sl=True, o=True)
    if len(sel) != 1:
        cmds.warning("Please select a single object of type: mesh")
        return None
    sel = sel[0]
    shapes = cmds.listRelatives(sel, shapes=True, fullPath=True)
    if shapes is not None:
        for each in shapes:
            if cmds.nodeType(each) != "mesh":
                cmds.warning("Selection type must be of type: mesh")
                return None
    else:
        cmds.warning("Selection has no mesh components. Make sure you are in object mode.")
        return None

    # report list [0] = info, [1] = warnings, [2] = errors
    printReport = [[], [], []]

    # MESH
    meshReport = processMesh(sel)
    if meshReport[0]:
        printReport[0].extend(meshReport[0])
    if meshReport[1]:
        printReport[1].extend(meshReport[1])
    if meshReport[2]:
        printReport[2].extend(meshReport[2])

    # FACES
    facesReport = processFaces(sel)
    if facesReport[0]:
        printReport[0].extend(facesReport[0])
    if facesReport[1]:
        printReport[1].extend(facesReport[1])
    if facesReport[2]:
        printReport[2].extend(facesReport[2])

    # VERTICES
    vertexReport = processVertices(sel)
    if vertexReport[0]:
        printReport[0].extend(vertexReport[0])
    if vertexReport[1]:
        printReport[1].extend(vertexReport[1])
    if vertexReport[2]:
        printReport[2].extend(vertexReport[2])

    # processEdges(sel)

    # CLEANUP / EXAMINE
    cleanupReport = processCleanup(sel)
    if cleanupReport[0]:
        printReport[0].extend(cleanupReport[0])
    if cleanupReport[1]:
        printReport[1].extend(cleanupReport[1])
    if cleanupReport[2]:
        printReport[2].extend(cleanupReport[2])

    # UVs
    uvReport = processUvs(sel)
    if uvReport[0]:
        printReport[0].extend(uvReport[0])
    if uvReport[1]:
        printReport[1].extend(uvReport[1])
    if uvReport[2]:
        printReport[2].extend(uvReport[2])

    # Materials
    materialReport = processMaterials(sel)
    if materialReport[0]:
        printReport[0].extend(materialReport[0])
    if materialReport[1]:
        printReport[1].extend(materialReport[1])
    if materialReport[2]:
        printReport[2].extend(materialReport[2])

    # Write report to UI fields
    clearLayoutChildren("meshNotice_RCL")
    for info in printReport[0]:
        cmds.text(l=info, p="meshNotice_RCL", align="left")
    clearLayoutChildren("meshWarnings_RCL")
    for warning in printReport[1]:
        cmds.text(l=warning, p="meshWarnings_RCL", align="left")
    clearLayoutChildren("meshErrors_RCL")
    for error in printReport[2]:
        cmds.text(l=error, p="meshErrors_RCL", align="left")

def processMesh(sel):

    returnReport = [[], [], []]

    parents = cmds.listRelatives(sel, allParents=True)
    children = cmds.listRelatives(sel, ad=True, type="transform")
    shapes = cmds.listRelatives(sel, shapes=True)
    numVerts = cmds.polyEvaluate(sel, vertex=True)
    numEdges = cmds.polyEvaluate(sel, edge=True)
    numTriangles = cmds.polyEvaluate(sel, triangle=True)
    numFaces = cmds.polyEvaluate(sel, face=True)
    numMeshShells = cmds.polyEvaluate(sel, shell=True)
    cmds.text("meshName_TX", e=True, l=sel)
    cmds.text("numVerts_TX", e=True, l=numVerts)
    cmds.text("numEdges_TX", e=True, l=numEdges)
    cmds.text("numTriangles_TX", e=True, l=numTriangles)
    cmds.text("numFaces_TX", e=True, l=numFaces)
    cmds.text("numMeshShells_TX", e=True, l=numMeshShells)
    cmds.text("numShapes_TX", e=True, l=len(shapes))
    if parents is not None:
        for each in parents:
            s = cmds.listRelatives(each, shapes=True)
            if s is None:
                warning = "Mesh's parent has no shape node"
                if warning not in returnReport[0]:
                    returnReport[0].append(warning)
        cmds.text("parents_TX", e=True, l=len(parents))
    else:
        cmds.text("parents_TX", e=True, l="None")
    if children is not None:
        cmds.text("children_TX", e=True, l=len(children))
    else:
        cmds.text("children_TX", e=True, l="None")

    # Mesh history
    ch = cmds.listHistory(sel, pdo=True, il=2)
    if ch is None or not ch or ch[0] == "initialShadingGroup":
        cmds.text("hasHistory_TX", edit=True, l="No")
    else:
        cmds.text("hasHistory_TX", edit=True, l="Yes")
        warning = "Mesh has input/construction history"
        if warning not in returnReport[0]:
            returnReport[0].append(warning)

    # Multiple Shapes Warning
    if len(shapes) > 1:
        returnReport[1].append("Mesh has more than one shape")

    # Default mesh names warning
    defPolyMeshNames = ["Sphere", "Cube", "Cylinder", "Cone", "Torus", "Plane", "Disc", "Pipe", "Pyramid",
                        "Helix", "Surface"]
    for name in defPolyMeshNames:
        if name in sel and sel.startswith("p"):
            warning="Mesh name may be default"
            if warning not in returnReport[0]:
                returnReport[0].append(warning)

    # Transformations
    transAttrX = cmds.getAttr(sel + ".translateX")
    transAttrY = cmds.getAttr(sel + ".translateY")
    transAttrZ = cmds.getAttr(sel + ".translateZ")
    rotateAttrX = cmds.getAttr(sel + ".rotateX")
    rotateAttrY = cmds.getAttr(sel + ".rotateY")
    rotateAttrZ = cmds.getAttr(sel + ".rotateZ")
    scaleAttrX = cmds.getAttr(sel + ".scaleX")
    scaleAttrY = cmds.getAttr(sel + ".scaleY")
    scaleAttrZ = cmds.getAttr(sel + ".scaleZ")

    transformText = "No"

    if transAttrX != 0.0 or transAttrY != 0.0 or transAttrZ != 0.0:
        transformText = "Trns "
        warning = "Translate attributes are not (0, 0, 0)"
        if warning not in returnReport[0]:
            returnReport[0].append(warning)
    if rotateAttrX != 0.0 or rotateAttrY != 0.0 or rotateAttrZ != 0.0:
        transformText = transformText + "Rot "
        warning = "Rotate attributes are not (0, 0, 0)"
        if warning not in returnReport[0]:
            returnReport[0].append(warning)
    if scaleAttrX != 1.0 or scaleAttrY != 1.0 or scaleAttrZ != 1.0:
        transformText = transformText + "Scl"
        warning = "Scale attributes are not (1, 1, 1)"
        if warning not in returnReport[0]:
            returnReport[0].append(warning)

    cmds.text("transformations_TX", e=True, l=transformText)

    return returnReport

def processVertices(sel):
    returnReport = [[], [], []]
    numVerts = cmds.polyEvaluate(sel, vertex=True)

    twoEdgeVerts = []
    threeEdgeVerts = []
    fourEdgeVerts = []
    moreThanFourEdgeVerts = []
    for x in range(numVerts):
        vtxName = sel + ".vtx[" + str(x) + "]"
        vtxEdges = cmds.polyListComponentConversion(vtxName, te=True)
        vtxEdges = cmds.ls(vtxEdges, flatten=True)
        if len(vtxEdges) == 2:
            twoEdgeVerts.append(vtxName)
            warning = "One or more vertices only has two edges"
            if warning not in returnReport[1]:
                returnReport[1].append(warning)
        elif len(vtxEdges) == 3:
            threeEdgeVerts.append(vtxName)
        elif len(vtxEdges) == 4:
            fourEdgeVerts.append(vtxName)
        elif len(vtxEdges) > 4:
            moreThanFourEdgeVerts.append(vtxName)
            warning = "One or more vertices has more than 4 edges (poles)"
            if warning not in returnReport[0]:
                returnReport[0].append(warning)
        else:
            cmds.warning("Unknown number of edges per vertex")

    # Vertex Positions - Test for vertices in common location
    vertexPositions = []
    sharedVertexSpace = []
    for x in range(numVerts):
        vtxName = sel + ".vtx[" + str(x) + "]"
        vtxPos = cmds.xform(vtxName, q=True, t=True, ws=True)
        pos = [round(vtxPos[0], 5), round(vtxPos[1], 5), round(vtxPos[2], 5)]
        if pos in vertexPositions:
            if pos not in sharedVertexSpace:
                sharedVertexSpace.append(pos)
        vertexPositions.append(pos)
    verticesInSharedSpace = []
    if sharedVertexSpace:
        warning = "One or more vertices share space"
        if warning not in returnReport[1]:
            returnReport[1].append(warning)

        for x in range(numVerts):
            vtxName = sel + ".vtx[" + str(x) + "]"
            vtxPos = cmds.xform(vtxName, q=True, t=True, ws=True)
            pos = [round(vtxPos[0], 5), round(vtxPos[1], 5), round(vtxPos[2], 5)]
            for each in sharedVertexSpace:
                if pos == each:
                    verticesInSharedSpace.append(vtxName)

    if twoEdgeVerts:
        cmds.button("vtxTwoEdgesSelect_BUT", e=True, bgc=warningColor, c=lambda args: selectComponent(sel, twoEdgeVerts, "none"))
    else:
        cmds.button("vtxTwoEdgesSelect_BUT", e=True, bgc=defColor)
    cmds.text("vtxTwoEdges_TX", e=True, l=len(twoEdgeVerts))

    cmds.text("vtxThreeEdges_TX", e=True, l=len(threeEdgeVerts))
    cmds.button("vtxThreeEdgesSelect_BUT", e=True, c=lambda args: selectComponent(sel, threeEdgeVerts, "none"))

    cmds.text("vtxFourEdges_TX", e=True, l=len(fourEdgeVerts))
    cmds.button("vtxFourEdgesSelect_BUT", e=True, c=lambda args: selectComponent(sel, fourEdgeVerts, "none"))

    if moreThanFourEdgeVerts:
        cmds.button("vtxFivePlusEdgesSelect_BUT", e=True, bgc=warningColor,
                    c=lambda args: selectComponent(sel, moreThanFourEdgeVerts, "none"))
    else:
        cmds.button("vtxFivePlusEdgesSelect_BUT", e=True, bgc=defColor)
    cmds.text("vtxFivePlusEdges_TX", e=True, l=len(moreThanFourEdgeVerts))

    if verticesInSharedSpace:
        cmds.text("vtxSharingSpace_TX", e=True, l=len(verticesInSharedSpace))
        cmds.button("vtxSharingSpaceSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, verticesInSharedSpace, "none"))
    else:
        cmds.button("vtxSharingSpaceSelect_BUT", e=True, bgc=passColor)
        cmds.text("vtxSharingSpace_TX", e=True, l="None")

    return returnReport

def processFaces(sel):
    returnReport = [[], [], []]

    numFaces = cmds.polyEvaluate(sel, face=True)

    faceAreas = []
    zeroFaceArea = []
    for x in range(numFaces):
        faceName = sel + ".f[" + str(x) + "]"
        faceArea = cmds.polyEvaluate(faceName, faceArea=True)
        faceArea = float("%.5f" % faceArea[0])
        faceAreas.append(faceArea)
        if faceArea == 0.0:
            warning = "One or more faces has zero area"
            if warning not in returnReport[2]:
                returnReport[2].append(warning)
            zeroFaceArea.append(faceName)

    # Face Connections
    twoEdgeFaces = []
    threeEdgeFaces = []
    fourEdgeFaces = []
    moreThanFourEdgeFaces = []
    for x in range(numFaces):
        faceName = sel + ".f[" + str(x) + "]"
        faceEdges = cmds.polyListComponentConversion(faceName, te=True)
        faceEdges = cmds.ls(faceEdges, flatten=True)
        if len(faceEdges) == 2:
            warning = "One or more faces has only two edges"
            if warning not in returnReport[2]:
                returnReport[2].append(warning)
            twoEdgeFaces.append(faceName)
        elif len(faceEdges) == 3:
            threeEdgeFaces.append(faceName)
        elif len(faceEdges) == 4:
            fourEdgeFaces.append(faceName)
        elif len(faceEdges) > 4:
            warning = "One or more faces has more than 4 edges (n-gons)"
            if warning not in returnReport[0]:
                returnReport[0].append(warning)
            moreThanFourEdgeFaces.append(faceName)
        else:
            cmds.warning("Unknown number of edges per face")

    if twoEdgeFaces:
        cmds.text("faceTwoEdges_TX", e=True, l=len(twoEdgeFaces))
        cmds.button("faceTwoEdgesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, twoEdgeFaces, "none"))
    else:
        cmds.button("faceTwoEdgesSelect_BUT", e=True, bgc=passColor)
        cmds.text("faceTwoEdges_TX", e=True,  l="None")

    cmds.text("triangleFaces_TX", e=True, l=len(threeEdgeFaces))
    cmds.button("triangleFaces_BUT", e=True, c=lambda args: selectComponent(sel, threeEdgeFaces, "none"))

    cmds.text("quadFaces_TX", e=True, l=len(fourEdgeFaces))
    cmds.button("quadFaces_BUT", e=True, c=lambda args: selectComponent(sel, fourEdgeFaces, "none"))

    if moreThanFourEdgeFaces:
        cmds.button("faceFivePlusEdgesSelect_BUT", e=True, bgc=warningColor,
                    c=lambda args: selectComponent(sel, moreThanFourEdgeFaces, "none"))
    else:
        cmds.button("faceFivePlusEdgesSelect_BUT", e=True, bgc=defColor)
    cmds.text("faceFivePlusEdges_TX", e=True, l=len(moreThanFourEdgeFaces))

    if zeroFaceArea:
        cmds.text("faceZeroArea_TX", e=True, l=len(zeroFaceArea))
        cmds.button("faceZeroAreaSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, zeroFaceArea, "faceToVertex"))
    else:
        cmds.button("faceZeroAreaSelect_BUT", e=True, bgc=passColor)
        cmds.text("faceZeroArea_TX", e=True, l="None")

    return returnReport

def processUvs(sel):
    returnReport = [[], [], []]

    uvPoints = cmds.polyEvaluate(sel, uv=True)
    uvShells = cmds.polyEvaluate(sel, us=True)
    uvSets = cmds.polyUVSet(sel, q=True, allUVSets=True)

    numFaces = cmds.polyEvaluate(sel, face=True)
    uvZeroAreaFaces = []
    for x in range(numFaces):
        faceName = sel + ".f[" + str(x) + "]"
        uvFaceArea = cmds.polyEvaluate(faceName, ufa=True)

        if uvFaceArea:
            if uvFaceArea[0] == 0.0:
                uvZeroAreaFaces.append(faceName)
        else:
            warning = "Mesh has no UVs"
            if warning not in returnReport[0]:
                returnReport[0].append(warning)

    cmds.text("uvPoints_TX", e=True, l=uvPoints)
    cmds.text("uvShells_TX", e=True, l=uvShells)
    cmds.text("uvSets_TX", e=True, l=len(uvSets))

    if uvZeroAreaFaces:
        cmds.text("uvZeroAreaFaces_TX", e=True, l=len(uvZeroAreaFaces))
        cmds.button("uvZeroAreaFaces_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, uvZeroAreaFaces, "none"))
        warning = "One or more UV faces has zero area"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
    else:
        cmds.button("uvZeroAreaFaces_BUT", e=True, bgc=passColor)
        cmds.text("uvZeroAreaFaces_TX", e=True, l="None")

    return returnReport

def processMaterials(sel):
    returnReport = [[], [], []]

    shape = cmds.listRelatives(sel, shapes=True, fullPath=True)
    shadingEngine = cmds.listConnections(shape, type="shadingEngine")
    materials = []
    for each in shadingEngine:
        conn = cmds.listConnections(each)
        mat = cmds.ls(conn, materials=True)
        mat = mat[0]
        if mat not in materials:
            materials.append(mat)

    if materials:
        cmds.text("materials_TX", e=True, l=len(materials))
        if len(materials) > 1:
            warning = "Mesh has more than one material"
            if warning not in returnReport[0]:
                returnReport[0].append(warning)
        defMatNames = ["lambert", "phong", "blinn", "Stingray"]
        for each in materials:
            for name in defMatNames:
                if name in each:
                    warning = "One or more materials may have a default name"
                    if warning not in returnReport[0]:
                        returnReport[0].append(warning)

    return returnReport

def processCleanup(sel):
    returnReport = [[], [], []]

    nonManifoldEdges = cmds.polyInfo(sel, nme=True)
    nonManifoldUvEdges = cmds.polyInfo(sel, nue=True)
    nonManifoldUvs = cmds.polyInfo(sel, nuv=True)
    laminaFaces = cmds.polyInfo(sel, lf=True)
    invalidEdges = cmds.polyInfo(sel, ie=True)
    invalidVertices = cmds.polyInfo(sel, iv=True)

    if nonManifoldEdges is not None:
        warning = "One or more edges are nonmanifold"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("nonmanifoldEdges_TX", e=True, l=len(nonManifoldEdges))
        cmds.button("nonmanifoldEdgesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, nonManifoldEdges, "none"))
    else:
        cmds.button("nonmanifoldEdgesSelect_BUT", e=True, bgc=passColor)
        cmds.text("nonmanifoldEdges_TX", e=True, l="None")

    if nonManifoldUvEdges is not None:
        warning = "One or more UV edges are nonmanifold"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("nonmanifoldUvEdges_TX", e=True, l=len(nonManifoldUvEdges))
        cmds.button("nonmanifoldUvEdgesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, nonManifoldUvEdges, "none"))
    else:
        cmds.button("nonmanifoldUvEdgesSelect_BUT", e=True, bgc=passColor)
        cmds.text("nonmanifoldUvEdges_TX", e=True, l="None")

    if nonManifoldUvs is not None:
        warning = "One of more UV points are nonmanifold"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("nonmanifoldUvs_TX", e=True, l=len(nonManifoldUvs))
        cmds.button("nonmanifoldUvsSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, nonManifoldUvs, "none"))
    else:
        cmds.button("nonmanifoldUvsSelect_BUT", e=True, bgc=passColor)
        cmds.text("nonmanifoldUvs_TX", e=True, l="None")

    if laminaFaces is not None:
        warning = "One or more faces share all edges (lamina)"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("laminaFaces_TX", e=True, l=len(laminaFaces))
        cmds.button("laminaFacesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, laminaFaces, "none"))
    else:
        cmds.button("laminaFacesSelect_BUT", e=True, bgc=passColor)
        cmds.text("laminaFaces_TX", e=True, l="None")

    if invalidEdges is not None:
        warning = "One or more edges have no face association (invalid)"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("invalidEdges_TX", e=True, l=len(invalidEdges))
        cmds.button("invalidEdgesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, invalidEdges, "none"))
    else:
        cmds.button("invalidEdgesSelect_BUT", e=True, bgc=passColor)
        cmds.text("invalidEdges_TX", e=True, l="None")

    if invalidVertices is not None:
        warning = "One or more vertices have no face association (invalid)"
        if warning not in returnReport[2]:
            returnReport[2].append(warning)
        cmds.text("invalidVertices_TX", e=True, l=len(invalidVertices))
        cmds.button("invalidVerticesSelect_BUT", e=True, bgc=errorColor, c=lambda args: selectComponent(sel, invalidVertices, "none"))
    else:
        cmds.button("invalidVerticesSelect_BUT", e=True, bgc=passColor)
        cmds.text("invalidVertices_TX", e=True, l="None")

    return returnReport

def clearLayoutChildren(layout):
    children = cmds.layout(layout, q=True, ca=True)
    if children is not None:
        for each in children:
            cmds.deleteUI(each)
        cmds.window("jbPrWin", e=True, h=1)

def selectComponent(sel, comp, convert):
    cmds.select(clear=True)
    if len(comp) == 0:
        cmds.select(sel, r=True)
        return None

    if convert == "none":
        comp = comp
    elif convert == "faceToVertex":
        for each in comp:
            vtxFaces = cmds.polyListComponentConversion(each, tv=True)
            vtxFaces = cmds.ls(vtxFaces, flatten=True)
        comp = vtxFaces

    cmds.select(clear=True)
    cmds.hilite(sel, r=True)
    for each in comp:
        cmds.select(each, add=True)


# dataset settings
dataset_type = 'WHS2dDataset_forAdap'
data_root = 'data/WHS_CT-MR_2d'
img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (384, 384)
train_pipeline = [
    dict(type='LoadImageFromFile_forAdap'),
    dict(type='LoadAnnotations'),
    dict(type='Resize', img_scale=(416, 416), B_img_scale=(416, 416), ratio_range=(0.5, 2.0)), #recommed to set img_scale because img and B_img may have different scals
    dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75),
    dict(type='RandomFlip', prob=0.5),
    dict(type='PhotoMetricDistortion'),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'B_img', 'gt_semantic_seg']),
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(416, 416),
        # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),
        ])
]
data = dict(
    samples_per_gpu=4,
    workers_per_gpu=4,
train=dict(
    type=dataset_type,
    data_root=data_root,
    #img_dir='CT_withGT/images',
    #ann_dir='CT_withGT/annotations',
    #split='CT_withGT/train.txt',
    #B_img_dir = 'MR_withGT/images',
    #B_split = 'MR_withGT/train.txt',
    img_dir='MR_withGT/images',
    ann_dir='MR_withGT/annotations',
    split='MR_withGT/train.txt',
    B_img_dir = 'CT_withGT/images',
    B_split = 'CT_withGT/train.txt',
    pipeline=train_pipeline),
# target domain for validation
val=dict(
    type=dataset_type,
    data_root=data_root,
    #img_dir='MR_withGT/images',
    #ann_dir='MR_withGT/annotations',
    #split='MR_withGT/val.txt',
    img_dir='CT_withGT/images',
    ann_dir='CT_withGT/annotations',
    split='CT_withGT/val.txt',
    pipeline=test_pipeline),
test=dict(
    type=dataset_type,
    data_root=data_root,
    img_dir='CT_withGT/images',
    ann_dir='CT_withGT/annotations',
    split='CT_withGT/val.txt',
    #img_dir='MR_withGT/images',
    #ann_dir='MR_withGT/annotations',
    #split='MR_withGT/val.txt',
    pipeline=test_pipeline)
    )


from fastapi import Depends

from sqlalchemy.orm import Session
from typing import Union

from src.car import models, schemas

def get_cars(db: Session, skip: int = 0, limit: int = 10, user_id: Union[int, None]=None):
    queryset = db.query(models.Car)
    if user_id:
        queryset = queryset.filter(models.Car.owner_id == user_id)
    return queryset.offset(skip).limit(limit).all()

def get_car_by_plate_number(db: Session, plate_number: str):
    return db.query(models.Car).filter(plate_number == models.Car.plate_number).first()

def get_user_cars(db: Session, user_id: int, skip: int = 0, limit: int = 10):
    return (
        db.query(models.Car)
        .filter(models.Car.owner_id == user_id)
        .offset(skip)
        .limit(limit)
        .all()
    )

def create_user_car(db: Session, car: schemas.CarCreate, user_id: int):
    db_car = models.Car(**car.dict(), owner_id=user_id)
    db.add(db_car)
    db.commit()
    db.refresh(db_car)
    return db_car

def get_or_create_user_car(
    db: Session, car: Depends(get_car_by_plate_number), plate_number: str, user_id=int
):
    create_flag = False
    if car:
        return car, create_flag
    car = create_user_car(car={"plate_number": plate_number}, user_id=user_id)


#SVM
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing the datasetset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values.reshape(-1,1)
y = dataset.iloc[:,2].values.reshape(-1,1)

#the svr class does not have feature scaling
# feature scaling
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
sc_y = StandardScaler()
x = sc_x.fit_transform(x)
y = sc_y.fit_transform(y)

#fitting  regression model to thr data set
#here we will create future non regression model

from sklearn.svm import SVR
regressor =SVR(kernel = 'rbf')
regressor.fit(x,y)

#predicting a new result

y_pred = sc_y.inverse_transform(regressor.predict(sc_x.transform(np.array([[6.5]]))))

#visualizing the   Regression model
plt.scatter(x,y,color = 'red')
plt.plot(x,regressor.predict(x),color = 'blue')
plt.title('truth or bluff ( SVR)')
plt.xlabel('Position level')
plt.ylabel('salary')
plt.show()

#visualizing the SVR for heigher resolution and smoother curve
x_grid = np.arange(min(x),max(x),0.1)# this will aslo predict 90  imaginary level
 #this will gives us vector and we need matrix so so we have to use reahpe function
x_grid = x_grid.reshape((len(x_grid),1))
plt.scatter(x,y,color = 'red')
plt.plot(x,regressor.predict(x),color = 'blue')
plt.title('truth or bluff ( SVR)')
plt.xlabel('Position level')
plt.ylabel('salary')
plt.show()


from machine import Pin

dr1 = Pin(21, Pin.OUT)
dr2 = Pin(19, Pin.OUT)

en1 = Pin(18, Pin.OUT)

def cw():
    dr1.value(0)
    dr2.value(1)

def ccw():
    dr1.value(1)
    dr2.value(0)

def start(rotation):
    pwm.init(freq=1, duty=512)
    if(ritation=='cw'):
        cw()
    elif(rotation=='ccw'):
        ccw()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# from __future__ import ( division, absolute_import, print_function, unicode_literals )

import sys
import os
import argparse
from termcolor import colored
import json
from json import encoder

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse

global gSettings

def treatCmdOpts(argv):
    """
    Treats the command line options

    :param argv: the options
    :type argv: list of string

    url = "ftp://cddis.gsfc.nasa.gov/pub/gps/data/daily/2018/318/18d/CORD00ARG_R_20183180000_01D_30S_MO.crx.gz"

    """
    # print('argv (treat daily-duty) = %s' % argv)
    global cBaseName  # colored version
    baseName = os.path.basename(__file__)
    cBaseName = colored(baseName, 'yellow')

    helpTxt = baseName + ' downloads files according to specified protocol to location. Example: url = ftp://cddis.gsfc.nasa.gov/pub/gps/data/daily/2018/318/18d/CORD00ARG_R_20183180000_01D_30S_MO.crx.gz'

    # create the parser for command line arguments
    parser = argparse.ArgumentParser(description=helpTxt)

    parser.add_argument('-p', '--protocol', help='Download protocol', required=True, type=str)
    parser.add_argument('-s', '--server', help='IGS', required=True, type=str)
    parser.add_argument('-r', '--dir_remote', help='Remote directory', required=True, type=str)
    parser.add_argument('-f', '--file_remote', help='Remote file', required=True, type=str)
    parser.add_argument('-l', '--dir_local', help='Local directory', required=True, type=str)

    parser.add_argument('-v', '--verbose', help='increase output verbosity (default False)',
                        action='store_true', required=False, default=False)

    # drop argv[0]
    args = parser.parse_args(argv)

    # return arguments
    return args.protocol, args.server, args.dir_remote, args.file_remote, args.dir_local, args.verbose

def download_file(url, proxy, dest=None, verbose=False):
    """
    Download and save a file specified by url to dest directory,
    """
    proxies = {"http":"http://%s" % proxy}
    proxy_support = urllib2.ProxyHandler(proxies)
    opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
    urllib2.install_opener(opener)

    req = urllib2.Request(url)
    req.add_unredirected_header('User-Agent', 'Mozilla/5.0')
    u = urllib2.urlopen(req)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if dest:
        filename = os.path.join(dest, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])

        if verbose:
            print("... Downloading: {0} (Bytes: {1})".format(url, file_size))

        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)

            status = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
            status += chr(13)
            if verbose:
                print(status, end="")

        if verbose:
            print()

    return filename

def main(argv):
    """
    ``download_file`` downloads a file from a server according to an Internet Protocol
    """

    # limit float precision
    encoder.FLOAT_REPR = lambda o: format(o, '.3f')
    cFuncName = colored(sys._getframe().f_code.co_name, 'green')

    # treat command line options
    protocol, server, dir_remote, filename, dir_local, verbose = treatCmdOpts(argv)

    # store in dictionary
    gSettings = {}
    # settings of remote file
    gSettings['remote'] = {}
    gSettings['remote']['protocol'] = protocol
    gSettings['remote']['IGS'] = server
    gSettings['remote']['dir_remote'] = dir_remote
    gSettings['remote']['file_remote'] = filename
    # settings of local file
    gSettings['local'] = {}
    gSettings['local']['dir_local'] = dir_local

    gSettings['proxy'] = {}
    gSettings['proxy']['http'] = os.environ.get("http_proxy")
    gSettings['proxy']['https'] = os.environ.get("https_proxy")

    # create download url
    gSettings['remote']['url'] = gSettings['remote']['protocol'] + '://' + gSettings['remote']['IGS'] + os .path.join(gSettings['remote']['dir_remote'], gSettings['remote']['file_remote'])

    if verbose:
        print('%s:\n... %s:' % (cBaseName, colored('global Settings', 'green')))
        print(json.dumps(gSettings, sort_keys=True, indent=4))

    # download the url
    gSettings['local']['filename'] = download_file(url=gSettings['remote']['url'], dest=gSettings['local']['dir_local'], proxy=gSettings['proxy']['http'], verbose=verbose)

    # inform the user and save the json file'
    if verbose:
        print('%s: %s\n... %s:' % (cBaseName, cFuncName, colored('global Settings', 'green')))
        print(json.dumps(gSettings, sort_keys=True, indent=4))

    # # url = "http://download.thinkbroadband.com/10MB.zip"
    # url = "ftp://cddis.gsfc.nasa.gov/pub/gps/data/daily/2018/318/18d/CORD00ARG_R_20183180000_01D_30S_MO.crx.gz"
    # filename = download_file(url)
    # print(filename)

    # url = "ftp://cddis.gsfc.nasa.gov/pub/gps/data/daily/2018/200/18d/cord2000.18d.Z"
    # filename = download_file(url)
    # print(filename)

    # url = "ftp://cddis.gsfc.nasa.gov/pub/gps/products/2027/igr20270.sp3.Z"
    # filename = download_file(url)
    # print(filename)

    # url = "ftp://cddis.gsfc.nasa.gov/pub/gps/data/daily/2018/318/18n/brdc3180.18n.Z"
    # filename = download_file(url)
    # print(filename)

    # url = "ftp://cddis.gsfc.nasa.gov/pub/glonass/data/daily/2018/318/18g/brdc3180.18g.Z"
    # filename = download_file(url)
    # print(filename)

    # gunzip -c CORD00ARG_R_20183190000_01D_30S_MO.crx.gz | CRX2RNX - | gfzrnx_lx -kv -fout CORD00ARG_R_20183190000_01D_30S_MO.rnx -f

if __name__ == "__main__":  # Only run if this file is called directly
    main(sys.argv[1:])


#!/usr/bin/env python
import pytest

import sklearn.datasets as datasets
try:
    import sklearn.discriminant_analysis as da
except ImportError:
    pass

import pandas_ml as pdml
import pandas_ml.util.testing as tm

class TestDiscriminantAnalysis(tm.TestCase):

    def test_objectmapper(self):
        df = pdml.ModelFrame([])
        self.assertIs(df.discriminant_analysis.LinearDiscriminantAnalysis,
                      da.LinearDiscriminantAnalysis)
        self.assertIs(df.discriminant_analysis.QuadraticDiscriminantAnalysis,
                      da.QuadraticDiscriminantAnalysis)

        self.assertIs(df.da.LinearDiscriminantAnalysis,
                      da.LinearDiscriminantAnalysis)
        self.assertIs(df.da.QuadraticDiscriminantAnalysis,
                      da.QuadraticDiscriminantAnalysis)

    def test_objectmapper_deprecated(self):
        df = pdml.ModelFrame([])
        with tm.assert_produces_warning(FutureWarning):
            self.assertIs(df.lda.LinearDiscriminantAnalysis,
                          da.LinearDiscriminantAnalysis)
        with tm.assert_produces_warning(FutureWarning):
            self.assertIs(df.qda.QuadraticDiscriminantAnalysis,
                          da.QuadraticDiscriminantAnalysis)

    @pytest.mark.parametrize("algo", ['LinearDiscriminantAnalysis'])
    def test_LDA(self, algo):
        diabetes = datasets.load_diabetes()
        df = pdml.ModelFrame(diabetes)

        mod1 = getattr(df.da, algo)()
        mod2 = getattr(da, algo)()

        df.fit(mod1)
        mod2.fit(diabetes.data, diabetes.target)

        result = df.predict(mod1)
        expected = mod2.predict(diabetes.data)
        self.assertIsInstance(result, pdml.ModelSeries)
        self.assert_numpy_array_almost_equal(result.values, expected)


#!/usr/bin/env python

##############################################################################
# no_dmc_metadata_fix_backendname.py
#
# This python script aims to fix 'backendname' entry in "no_dmc_metadata.txt"
# files according to a specified pattern, so that only files containing the
# matching path will be updated.
#
# You may use this script when you move object data (and metadata) to another
# directory so that NO_DMC_LIB can still access to them.
#
# NOTE: this script does NOT require DMC stuff!
#
# Author  : Christian Madsen
# Date    : 2015-06-02
# version : Initial
##############################################################################

import os

### Parameters
METADATA_FILENAME = "no_dmc_metadata.txt"

NODMCMETADATA_BACKENDNAME = "Backendname"

# Debug and verbose mode
DEBUG = False # Set to True if you want debug message to be print
VERBOSE = True # Set to True if you want more log message

#-----------------------------------------------------------------------------

def logDebug(msg):
  """Print message only if DEBUG is set to True.
  """
  if DEBUG:
    print("[DBG] %s" % msg)

#-----------------------------------------------------------------------------

def log(msg):
  """Print message only if VERBOSE is set to True.
  """
  if VERBOSE:
    print(msg)

#-----------------------------------------------------------------------------

def printUsage(cmd):
  print("Usage: %s <workingDir> <old_pattern> <new_pattern>" % cmd)

#-----------------------------------------------------------------------------

def getAllMetadataFiles(workingDir):
  import os.path

  res_list = []
  for dirpath, dirnames, filenames in os.walk(workingDir):
    for filename in filenames:
      if filename == METADATA_FILENAME:
        res_list.append(os.path.join(dirpath, filename))

  return res_list

#-----------------------------------------------------------------------------

def getSelectedMetadataFiles(files, old_pattern):
  res_selectedFiles = []

  for file in files:
    if old_pattern in open(file).read():
      res_selectedFiles.append(file)

  return res_selectedFiles

#-----------------------------------------------------------------------------

def replacePatternInMetadataFiles(selectedMetadataFiles, old_pattern, new_pattern):
  import fileinput

  # Loop on all files to be proceed
  for file in selectedMetadataFiles:
    log("  . Proceed file %s" % file)

    # Open file for reading
    s = open(file).read()

    # Replace
    s = s.replace(old_pattern, new_pattern)

    # write result
    f = open(file, 'w')
    f.write(s)
    f.flush()
    f.close()

#-----------------------------------------------------------------------------

##############################################################################
# MAIN
# This code allow to execute the module as a standalone script.
##############################################################################
if __name__ == "__main__":
  import sys

  shortName = sys.argv[0].split("/")[-1]

  log("")
  log("*******************************************************************************")
  log("* %s" % shortName)
  log("* This is the NO_DMC_LIB metadata fix backendname script")
  log("*******************************************************************************")
  log("")

  if len(sys.argv) != 4:
    printUsage(shortName)
    exit(1)

  # Retrieve the working dir
  workingDir = sys.argv[1]

  # Retrieve the old_pattern (the one to be replaced)
  old_pattern = sys.argv[2]

  # Retrieve the new_pattern (the one that will replace the old one)
  new_pattern = sys.argv[3]

  log("workingDir  = %s" % workingDir)
  log("old_pattern = '%s'" % old_pattern)
  log("new_pattern = '%s'" % new_pattern)
  log("")

  ### 1) Find all metadata file
  allMetadataFiles = getAllMetadataFiles(workingDir)
  #logDebug("allMetadataFiles = %s" % allMetadataFiles)
  log("> Found a total of %d metadata files" % len(allMetadataFiles))

  ### 2) Select those that match old_pattern for 'Backendname'
  selectedMetadataFiles = getSelectedMetadataFiles(allMetadataFiles, old_pattern)
  log("> %d contains the <old_pattern>" % len(selectedMetadataFiles))

  ### 3) Apply change
  replacePatternInMetadataFiles(selectedMetadataFiles, old_pattern, new_pattern)

  # Successfull end
  print("")
  print("Done.")


import csv
import re

# Fungsi untuk melakukan ekstraksi dengan menggunakan regex
def extract_pasal(text):
    pasal = re.findall(r"Pasal\s+(\d+)", text, re.IGNORECASE)

    return ';'.join(pasal) if pasal else ''

# Nama file input dan output
input_file = 'output_model_8_v1.csv'
output_file = 'output3.csv'

# Buka file input dan buat file output
with open(input_file, 'r') as file_in, open(output_file, 'w', newline='') as file_out:
    reader = csv.reader(file_in)
    writer = csv.writer(file_out)

    # Menulis header untuk file output
    writer.writerow(['Pasal'])

    # Membaca baris-baris dari file input
    for row in reader:
        text = row[0]  # Asumsikan teks berada di kolom pertama

        # Mengekstrak informasi pasal menggunakan fungsi extract_pasal
        extracted_pasal = extract_pasal(text)

        # Menulis baris dengan informasi pasal yang diekstraksi ke dalam file output
        writer.writerow([extracted_pasal])

print("Ekstraksi pasal selesai. File output.csv telah dibuat.")


#!/usr/bin/env python

import os
import tensorflow as tf
import model
import params
import time
import cv2
import numpy as np

from get_val_data import val_data
from get_train_data import train_data

sess = tf.InteractiveSession()
LR = 1e-4

# loss = tf.losses.absolute_difference(model.y_, model.y)
loss = tf.losses.mean_squared_error(model.y_, model.y)
train = tf.train.AdamOptimizer(LR).minimize(loss)

saver = tf.train.Saver()

sess.run(tf.global_variables_initializer())

# get the val data
val_X, val_Y = val_data()
# finish get val data

file_list = os.listdir('/raw_data/balanced_data')
for i in range(params.epoch):
	# prepare data for training
	for file in file_list:
		if file.endswith('.npy'):
			print("Start process on file : " , file)
			train_X, train_Y = train_data(file)
		    	#finishing getting the training data

			# start the train on the data

			# seperate the data into batch size
			batch_iteration = int(train_X.shape[0] / params.batch)
			for iteration in range(batch_iteration):
				batch_X = train_X[iteration*params.batch:(iteration+1)*params.batch]
				batch_Y = train_Y[iteration*params.batch:(iteration+1)*params.batch]

				train.run(feed_dict={model.x: batch_X, model.y_: batch_Y, model.keep_prob: 0.8})

				t_loss = loss.eval(feed_dict={model.x: batch_X, model.y_: batch_Y, model.keep_prob: 1.0})
				v_loss = loss.eval(feed_dict={model.x: val_X, model.y_: val_Y, model.keep_prob: 1.0})
				#v_acc = acc.eval(feed_dict={model.x: val_X, model.y_: val_Y, model.keep_prob: 1.0})

				print ("epoch {} of {}, batch {} of {}, train loss {}, val loss {}".format(i, params.epoch,iteration,batch_iteration,t_loss, v_loss))

	model_name = "./weight/SSC_epoch_{}_LR_{}.model".format(i,LR)
	save_path = saver.save(sess, model_name)


#!/usr/bin/env python3
"""
10-update_topics module
changes all topics of school doc based on name
"""
from pymongo import MongoClient

def update_topics(mongo_collection, name, topics):
    """update_topics function"""
    mongo_collection.update_many(
        { "name": name },
        { "$set": { "topics": topics } }
    )


#!/usr/bin/python
# -*- coding: utf-8 -*-

from os.path import basename
from paste.script import command
from plone.app.themeeditor.interfaces import _
from plone.app.themeeditor.interfaces import IResourceRetriever
from plone.app.themeeditor.utils import dumpSkin
from plone.z3cform.layout import FormWrapper
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from templer.localcommands import TemplerLocalCommand
from z3c.form import form, field, button
from zope import interface, schema
from zope.component import getUtility
import fileinput
import logging
import os
import shutil
import sys
import tarfile
import tempfile

JBOTCOMPATIBLE = ('zopeview', 'portlet', 'view', 'viewlet')
_templates_dir = os.path.join(os.path.dirname(__file__))
_templates_dir = os.path.join(_templates_dir, '..', 'templates')

LOGGER = 'plone.app.themeeditor'

class JBOTResourceException(Exception):

    def __init__(self, value):
        self.parameter = value

    def __str__(self):
        return repr(self.parameter)

def info(msg, *args):
    logging.getLogger(LOGGER).info(msg, *args)

class IThemeEditorExportForm(interface.Interface):

    name = schema.TextLine(title=_(u'Name'))
    version = schema.TextLine(title=_(u'Version'))
    description = schema.TextLine(title=_(u'Description'))
    author = schema.TextLine(title=_(u'Author'))
    author_email = schema.TextLine(title=_(u'Author Email'))

class ThemeEditorExportForm(form.Form):

    fields = field.Fields(IThemeEditorExportForm)
    ignoreContext = True  # don't use context to get widget data
    label = _(u'Export your customizations')
    template = ViewPageTemplateFile('export_form.pt')

    @button.buttonAndHandler(_(u'Export Customizations'))
    def handleApply(self, action):
        (data, errors) = self.extractData()
        if errors:
            return
        (output_dir, namespace_package, name, package_name) = \
            self.theme_skel(data)
        self.theme_populate(output_dir, namespace_package, name,
                            data['version'])
        self.write_setuppy(data, namespace_package, package_name,
                           output_dir)
        tarball = self.theme_tarball(output_dir, namespace_package,
                name, data['version'])
        self.theme_download(tarball)
        shutil.rmtree(output_dir)
        return 'hello universe'

    def theme_skel(self, data):
        ''' method that generates a theme skeleton '''
        name = data.pop('name')
        data['add_profile'] = True
        (data['namespace_package'], data['package']) = name.split('.')
        (tpl, create, output_dir) = _create_tpl()
        info('ThemeEditorExportForm.theme_skel: Creating theme skeleton outputdir=%s, theme_name=%s'
             , output_dir, name)
        vars = [str('%s=%s') % (k, v) for (k, v) in data.items()]

        create.run([
            '--no-interactive',
            '--output-dir',
            output_dir,
            '-t',
            'plone_basic',
            name,
            ] + vars)
        cwd = os.getcwd()
        try:
            os.chdir('/'.join([output_dir, name, 'src']))
            add = TemplerLocalCommand('add')
            add.template_vars['view_name'] = 'example'
            add.run(['browserview', 'view_name=example'])
        finally:
            os.chdir(cwd)
        package_name = name

        return (output_dir, data['namespace_package'], data['package'],
                package_name)

    def theme_populate(
        self,
        output_dir,
        namespace_package,
        name,
        make_jbot_zcml=0,
        dump_cmfskins=0,
        base_theme='Plone Default',
        version='100',
        ):
        '''
        retreive all the customized items and export to the theme_skel
        '''

        rm = getUtility(IResourceRetriever)
        customized_resources = list(rm.iter_resources(tags=['customized'
                                    ]))

        # iterate over customized resources and export to theme_skel

        for resource in customized_resources:
            resource = resource[0]
            if resource.type in JBOTCOMPATIBLE:
                make_jbot_zcml = 1
                self.resource_to_jbot(resource, output_dir,
                        namespace_package, name)
            else:
                dump_cmfskins = 1
                try:
                    base_theme = resource.base_skin
                except AttributeError:
                    base_theme = ''
        if dump_cmfskins == 1:
            self.dump_cmfskins(output_dir, namespace_package, name,
                               base_theme, version)
        if make_jbot_zcml == 1:
            self.create_jbot_zcml(output_dir, namespace_package, name)
        self.write_zcml_and_generic_setup(output_dir,
                namespace_package, name, base_theme, version)

    def write_setuppy(
        self,
        data,
        namespace_package,
        package_name,
        output_dir,
        ):

        setup_vars = {
            'version': data['version'],
            'theme_name': package_name,
            'namespace_package': namespace_package,
            'namespace': namespace_package,
            'theme_description': data['description'],
            'author': data['author'],
            'author_email': data['author_email'],
            }
        template = os.path.join(_templates_dir, 'setup.py.tmpl')
        output_file = os.path.join(output_dir, package_name, 'setup.py')
        self.write_tmpl(template, output_file, vars=setup_vars)

    def theme_tarball(
        self,
        output_dir,
        namespace_package,
        name,
        version='0',
        ):
        '''
        convert the theme into a tarball
        '''

        tarballname = '%s.%s-%s.tar.gz' % (namespace_package, name,
                version)

        # while working, we store the original directory so that we can
        # reset it later

        original_dir = os.getcwd()
        os.chdir(output_dir)
        tar = tarfile.open('sample.tar.gz', 'w:gz')
        tar = tarfile.open(tarballname, 'w:gz')
        tar.add('%s.%s' % (namespace_package, name))
        tar.close()

        # reset the working directory if we don't do this, it won't be
        # able to find the egg_info_dir in the future

        os.chdir(original_dir)
        return os.path.join(output_dir, tarballname)

    def theme_download(self, path, blocksize=32768):
        self.context.REQUEST.RESPONSE.setHeader('content-type',
                'application/x-tar')
        self.context.REQUEST.RESPONSE.setHeader('content-length',
                str(os.stat(path)[6]))
        self.context.REQUEST.RESPONSE.setHeader('Content-Disposition',
                ' attachment; filename=' + basename(path))
        download = open(path, 'rb')
        while True:
            data = download.read(blocksize)
            if data:
                self.context.REQUEST.RESPONSE.write(data)
            else:
                break
        download.close()

    def dump_cmfskins(
        self,
        output_dir,
        namespace_package,
        name,
        base_theme,
        version,
        ):
        '''
        convert resource to filesystem directory
        '''
        zmi_skin_names = ['custom']
        fs_dest_directory = output_dir
        fs_product_name = '%s.%s' % (namespace_package, name)
        dumpSkin(self.context, zmi_skin_names, fs_dest_directory,
                 fs_product_name, erase_from_skin=0)

    def write_zcml_and_generic_setup(
        self,
        output_dir,
        namespace_package,
        name,
        base_theme,
        version,
        ):

        package_name = '%s.%s' % (namespace_package, name)

        # overwrite the existing skins.zcml file

        skin_vars = {
            'name': name,
            'namespace': namespace_package,
            'package_name': package_name,
            'theme_name': package_name,
            'base_theme': base_theme,
            'version': version,
            }

        template = os.path.join(_templates_dir, 'skins.zcml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'skins.zcml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

        # custom skins.xml

        template = os.path.join(_templates_dir, 'skins.xml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'profiles',
            'default',
            'skins.xml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

        # custom viewlets.xml

        template = os.path.join(_templates_dir, 'viewlets.xml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'profiles',
            'default',
            'viewlets.xml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

        # custom metadata.xml

        template = os.path.join(_templates_dir, 'metadata.xml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'profiles',
            'default',
            'metadata.xml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

        # custom profile.zcml

        template = os.path.join(_templates_dir, 'profiles.zcml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'profiles.zcml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

        # custom browser/configure.zcml

        template = os.path.join(_templates_dir,
                                'browser_configure.zcml.tmpl')
        output_file = os.path.join(
            output_dir,
            package_name,
            'src',
            namespace_package,
            name,
            'browser',
            'configure.zcml',
            )
        self.write_tmpl(template, output_file, vars=skin_vars)

    def write_tmpl(
        self,
        tmpl,
        output_file,
        vars,
        ):

        _template = open(tmpl)
        _content = _template.read()
        _template.close()
        _content = _content % vars
        f = open(output_file, 'w')
        f.write(_content)
        f.close()

    def resource_to_jbot(
        self,
        resource,
        output_dir,
        namespace_package,
        name,
        ):
        '''
        convert resource to just a bunch of templates (jbot)
        we assume that this is an already customized resource
        '''
        try:
            resource_info = self.jbot_resource_info(resource)
        except JBOTResourceException:

            # XXX Fixme - should use a more robust test skip this
            # resource

            return
        (jbotname, tmpl_text) = resource_info
        package_name = '%s.%s' % (namespace_package, name)

        jbot_dir = os.path.join(output_dir, package_name, 'src',
                                namespace_package, name, 'jbot')

        if not os.path.exists(jbot_dir):
            os.makedirs(jbot_dir)
        jbot_file = os.path.join(jbot_dir, jbotname)
        f = open(jbot_file, 'w')
        f.write(tmpl_text)
        f.close()

    def create_jbot_zcml(
        self,
        output_dir,
        namespace_package,
        name,
        ):

        package_name = '%s.%s' % (namespace_package, name)
        jbot_vars = {'package_name': package_name}
        template = os.path.join(_templates_dir, 'jbot.zcml.tmpl')
        output_file = os.path.join(output_dir, package_name, 'src',
                                   namespace_package, name, 'jbot.zcml')
        self.write_tmpl(template, output_file, vars=jbot_vars)

        configure_zcml = os.path.join(output_dir, package_name, 'src',
                namespace_package, name, 'configure.zcml')

        # insert jbot zcml file include (after the 9th line)

        for (i, line) in enumerate(fileinput.input(configure_zcml,
                                   inplace=1)):
            sys.stdout.write(line)
            if i == 8:
                sys.stdout.write('  <include file="jbot.zcml" />\n')

    def jbot_resource_info(self, resource):
        rm = getUtility(IResourceRetriever)
        resources = rm.iter_resources(name=resource.name,
                exact=True).next()
        if resources[-1].info.startswith(u'On the filesystem'):
            path = resources[-1].path
        else:
            raise JBOTResourceException('%s is not a working properly with jbot this may be a bug in plone.app.themeeditor '
                    , resource.name)
        context = resources[-1].context
        if isinstance(context, (list, tuple)):
            context = context[-1]
        context_prefix = context.split('.interfaces')[0]
        jbotname = '.'.join([context_prefix, basename(path)])
        tmpl_text = resource.text
        return (jbotname, tmpl_text)

class ThemeEditorExportView(FormWrapper):

    form = ThemeEditorExportForm

    def __init__(self, context, request):
        FormWrapper.__init__(self, context, request)
        request.set('disable_border', 1)

def _create_tpl():
    commands = command.get_commands()
    create = commands['create'].load()
    create = create('any name here')
    output_dir = tempfile.mkdtemp()

    # tpl = zopeskel.plone3_theme.Plone3Theme("new template")

    tpl = None

    return (tpl, create, output_dir)


"""
Import necessary libraries to create a variational autoencoder
The code is mainly developed using the PyTorch library
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
import os
import numpy as np
import copy
import pickle
from torch.utils.tensorboard import SummaryWriter
from progress.bar import Bar
import torchvision
import socket
from mpi4py import MPI
import time

model_name = 'VAE_MNIST'
"""
Initialize Hyperparameters
"""
batch_size = 2#2
learning_rate = 1e-4
num_epochs = 50
input_size = 20#82
imgChannels = 1#3
n_filters = 5
imsize2 = input_size - (n_filters-1) * 3
convdim1 = 8
convdim2 = 16
convdim3 = 32
zDim = 300

writer = SummaryWriter(log_dir='/local/scratch/jrs596/VAE/logs')

"""
Create dataloaders
"""

data_transforms = transforms.Compose([
        transforms.Resize((input_size,input_size)),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor()])

#train_dir = '/local/scratch/jrs596/dat/ResNetFung50+_images_unorganised'
#train_dir = '/local/scratch/jrs596/dat/ResNetFung50+_images_unorganised_test'
#train_dataset = datasets.ImageFolder(train_dir, data_transforms['train'])
#train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)

mnist_data = torchvision.datasets.MNIST('/local/scratch/jrs596/dat/mnist', transform=data_transforms)
train_loader = torch.utils.data.DataLoader(mnist_data,
                                          batch_size=2,
                                          shuffle=True,
                                          num_workers=4)

n = len(train_loader.dataset)
if n%batch_size != 0:
    print('Total N samples must be divisable by batch size')
    print('N = ' + str(n))
    exit(0)

class VAE(nn.Module):
    def __init__(self, imgChannels=imgChannels, featureDim=int((batch_size*convdim3*imsize2*imsize2)/4),
        zDim=zDim):
        super(VAE, self).__init__()

        # Initializing the 2 convolutional layers and 2 full-connected layers for the encoder
        layer2=int(featureDim/10)
        self.encConv1 = nn.Conv2d(imgChannels, convdim1, n_filters).to('cuda:0')
        self.encConv2 = nn.Conv2d(convdim1, convdim2, n_filters).to('cuda:0')
        self.encConv3 = nn.Conv2d(convdim2, convdim3, n_filters).to('cuda:0')
        self.pool = nn.MaxPool2d(2, stride=2, return_indices=True).to('cuda:0')
        self.unPool = nn.MaxUnpool2d(2, stride=2).to('cuda:0')
        self.batchNorm = nn.BatchNorm2d(16).to('cuda:0')
        self.encFC1 = nn.Linear(featureDim, layer2).to('cuda:0')
        self.encFC1_1 = nn.Linear(layer2, layer2).to('cuda:0')
        self.encFC1_2 = nn.Linear(layer2, zDim).to('cuda:0')
        self.encFC2 = nn.Linear(featureDim, layer2).to('cuda:0')
        self.encFC2_1 = nn.Linear(layer2, layer2).to('cuda:0')
        self.encFC2_2 = nn.Linear(layer2, zDim).to('cuda:0')

        # Initializing the fully-connected layer and 2 convolutional layers for decoder
        self.decFC1_1 = nn.Linear(zDim, layer2).to('cuda:0')
        self.decFC1_2 = nn.Linear(layer2, layer2).to('cuda:0')
        self.decFC1 = nn.Linear(layer2, featureDim).to('cuda:1')
        self.decConv1 = nn.ConvTranspose2d(convdim3, convdim2, n_filters).to('cuda:0')
        self.decConv2 = nn.ConvTranspose2d(convdim2, convdim1, n_filters).to('cuda:0')
        self.decConv3 = nn.ConvTranspose2d(convdim1, imgChannels, n_filters).to('cuda:0')

    def encoder(self, x):

        # Input is fed into 2 convolutional layers sequentially
        # The output feature map are fed into 2 fully-connected layers to predict mean (mu) and variance (logVar)
        # Mu and logVar are used for generating middle representation z and KL divergence loss
        x = F.relu(self.encConv1(x.to('cuda:0')))
        #x = self.pool(x)
        x = F.relu(self.encConv2(x))
        #x = self.pool(x)
        x = self.batchNorm(x)
        x = F.relu(self.encConv3(x))
        x, indices = self.pool(x)
        x_dim = np.prod(list(x.shape))
        x = x.view(-1, x_dim)
        mu = self.encFC1(x)
        mu = self.encFC1_1(mu)
        mu = self.encFC1_2(mu)
        logVar = self.encFC2(x)
        logVar = self.encFC2_1(logVar)
        logVar = self.encFC2_2(logVar)
        return mu, logVar, indices

    def reparameterize(self, mu, logVar):

        #Reparameterization takes in the input mu and logVar and sample the mu + std * eps
        std = torch.exp(logVar/2)
        eps = torch.randn_like(std)
        return mu + std * eps

    def decoder(self, z, indices):

        # z is fed back into a fully-connected layers and then into two transpose convolutional layers
        # The generated output is the same size of the original input
        x = F.relu(self.decFC1_1(z))
        x = F.relu(self.decFC1_2(x))
        x = F.relu(self.decFC1(x.to('cuda:1')))
        x = x.view(batch_size, convdim3, int(imsize2/2) ,int(imsize2/2))
        x = self.unPool(x.to('cuda:0'), indices, output_size=([batch_size,convdim3,imsize2,imsize2]))
        x = F.relu(self.decConv1(x))
        x = F.relu(self.decConv2(x))
        x = torch.sigmoid(self.decConv3(x))
        return x

    def forward(self, x):

        # The entire pipeline of the VAE: encoder -> reparameterization -> decoder
        # output, mu, and logVar are returned for loss computation
        mu, logVar, indices = self.encoder(x)
        z = self.reparameterize(mu, logVar)
        out = self.decoder(z, indices)
        return out, mu, logVar

model = VAE()

"""
Training
"""
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)

for epoch in range(num_epochs):
    running_ELBO = 0.0
    running_CE = 0.0
    running_KL = 0.0

    with Bar('Learning...', max=n/batch_size) as bar:
          for idx, data in enumerate(train_loader):

            imgs = data[0]
            labels = imgs.to('cuda:0')
            # Feeding a batch of images into the network to obtain the output image, mu, and logVar

            out, mu, logVar = model(imgs)

            kl_divergence = 0.5 * torch.sum(torch.exp(logVar) + mu**2 - 1. - logVar)

            binary_cross_entropy = F.binary_cross_entropy(out, labels)
            loss = binary_cross_entropy + kl_divergence

            running_ELBO += loss.item() * imgs.shape[0]
            running_CE += binary_cross_entropy.item() * imgs.shape[0]
            running_KL += kl_divergence.item() * imgs.shape[0]

            # Backpropagation
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            bar.next()

    epoch_loss = round(float(running_ELBO / n),4)
    epoch_CE = round(float(running_CE / n),4)
    epoch_KL = round(float(running_KL / n),4)

    writer.add_scalar("ELBO/train", epoch_loss, epoch)
    writer.add_scalar("Cross entropy/train", epoch_CE, epoch)
    writer.add_scalar("KL divergence/train", epoch_KL, epoch)

    if epoch%10 == 0:
        print('Saving checkpoint')
        PATH = '/local/scratch/jrs596/VAE/models'
        torch.save(model.state_dict(), os.path.join(PATH, model_name + '.pth'))

    print('Epoch {}: ELBO loss {}'.format(epoch, epoch_loss))
    print('KL divergence {}: Binary Cross Entropy {}'.format(epoch_KL, epoch_CE))

writer.flush()
writer.close()


# coding=utf-8
from __future__ import print_function

from six import string_types
import importlib
import inspect

from fancytools.fcollections.NestedOrderedDict import NestedOrderedDict

class GetCallablesInPackage(NestedOrderedDict):
    """
    Return a NestedOrderedDict of all functions and classes within a given package.
    excluding 'private' modules beginning with '_'

    =========  ======================================
    Arguments  Description
    =========  ======================================
    package    package or string of path to package
               to get all callables from
    =========  ======================================

    =====================  =======  ===============================
    Optional               Default  Description
    =====================  =======  ===============================
    modules_in_structure   False    include the modules of the
                                    callables in the output
    include_classes        True     include classes in the output
    include_functions      True     include functions in the output
    min_level              0        minimum depth level in the
                                    package structure
    max_level              None     maximum depth level in the
                                    package structure
    exclude_empty_pck      True     exclude sub-packages without
                                    any callables from the output
    =====================  =======  ===============================

    """

    def __init__(self, package, modules_in_structure=False,
                 include_classes=True, include_functions=False,
                 min_level=0, max_level=None, exclude_empty_pck=True):
        """
        """

        NestedOrderedDict.__init__(self)

        if isinstance(package, string_types):
            package = importlib.import_module(package)

        self._package = package
        self._include_classes = include_classes
        self._include_functions = include_functions
        self._modules_in_structure = modules_in_structure
        self._min_level = min_level
        self._max_level = max_level

        self._objects = [package]

        self._buildRecursive(package, self, 0)

        if exclude_empty_pck:
            self._cleanRecursive(self)

    def _cleanRecursive(self, subSelf):
        """
        Delete all NestedOrderedDict that haven't any entries.
        """
        for key, item in list(subSelf.items()):
            if self.isNestedDict(item):
                if not item:
                    subSelf.pop(key)
                else:
                    self._cleanRecursive(item)

    def _buildRecursive(self, module, subSelf, level):

        for (name, obj) in inspect.getmembers(module):
            # take only 'public' modules
            if name[0] == '_':
                continue
            # print name, level
            if inspect.ismodule(obj):
                # don't handle modules thats have been used before:
                if obj in self._objects:
                    continue
                self._objects.append(obj)

                if obj.__name__.startswith(self._package.__name__):
                    # either use module for submenus or check whether module is
                    # actually a package:
                    if self._modules_in_structure or obj.__file__.endswith(
                            '__init__.pyc'):
                        # limit max recursion level
                        if not self._max_level or level <= self._max_level:
                            # if self._max_level:
                            l = subSelf[name] = NestedOrderedDict()
                            self._buildRecursive(obj, l, level + 1)
                    else:
                        # use same menu for all classes of all files on one
                        # folder/module
                        self._buildRecursive(obj, subSelf, level)

            elif level >= self._min_level:
                    # if object is a class
                if (
                    # ( not self._include_classes or ( self._include_classes and inspect.isclass(obj) ) or
                    (self._include_classes and inspect.isclass(obj)) or
                    # and/or a function
                   # ( not self._include_functions or ( self._include_functions and inspect.isfunction(obj)) )
                   (self._include_functions and inspect.isfunction(obj))
                   ):
                        # if object belongs to its parent module (mod is not imported)
                        # OR module paths are the same (in case of from mod
                        # import cls and cls.name == mod.name)
                    try:
                        if self.belongsToModule(obj, module):
                            subSelf[name] = obj
                    except AttributeError:
                        pass  # obj has no __module__ is e.g. a string

    @staticmethod
    def belongsToModule(obj, module):
        """Returns True is an object belongs to a module."""
        return obj.__module__ == module.__name__ or obj.__module__.startswith(
            module.__name__)

    def buildHirarchy(self, horizontal_operation=None,
                      vertical_operation=None):
        """Walk through the nested dict structure and executes
        horizontal_operation(name, callable) resp.
        vertical_operation(name, callable) if defined.
        """
        def buildRecursive(pkey, pval):
            if self.isNestedDict(pval):
                if vertical_operation:
                    vertical_operation(pkey, pval)
                for key, val in list(pval.items()):
                    # if not isinstance(val, NestedOrderedDict):
                    buildRecursive(key, val)
            else:
                if horizontal_operation:
                    horizontal_operation(pkey, pval)
        buildRecursive(self._package.__name__, self)

    @staticmethod
    def isNestedDict(instance):
        """convenience function for

        >>> isinstance(instance, NestedOrderedDict)"""
        return isinstance(instance, NestedOrderedDict)

if __name__ == '__main__':
    import sys
    import numpy
    g = GetCallablesInPackage(numpy, include_functions=True)
    print(g)

    class printClassStructure(object):

        def __init__(self):
            self.indent = ''
            self._hor_as_last_called = True

        def hor(self, key, item):
            sys.stdout.write("%s%s - " % (self.indent, key))
            self.indent = ''
            self._hor_as_last_called = True

        def vert(self, key, item):
            if self._hor_as_last_called:
                print('')
            print("%s-> %s" % (self.indent, key))
            self.indent += '\t'
            self._hor_as_last_called = False

    p = printClassStructure()

    g.buildHirarchy(horizontal_operation=p.hor,
                    vertical_operation=p.vert)


import os

from molotov.ui.app import MolotovApp
from molotov.util import printable_error

class Console:
    def __init__(
        self,
        interval=0.3,
        max_lines_displayed=25,
        simple_console=False,
        single_process=True,
    ):
        self._interval = interval
        self._stop = True
        self._creator = os.getpid()
        self._stop = False
        self._max_lines_displayed = max_lines_displayed
        self._simple_console = simple_console
        self.ui = MolotovApp(
            refresh_interval=interval,
            max_lines=max_lines_displayed,
            simple_console=simple_console,
            single_process=single_process,
        )
        self.terminal = self.ui.terminal
        self.errors = self.ui.errors
        self.status = self.ui.status
        self.started = False

    async def start(self):
        await self.ui.start()
        self.started = True

    async def stop(self):
        await self.ui.stop()
        self.started = False

    def print_results(self, results):
        self.status.update(results)

    def print(self, data):
        if self.terminal is None:
            return
        for line in data.split("\n"):
            line = line.strip()
            self.terminal.write_line(line)

    def print_error(self, error, tb=None):
        if self.errors is None:
            return
        if isinstance(error, str):
            for line in error.split("\n"):
                line = line.strip()
                self.errors.write_line(line, fg="gray")
            return

        for line in printable_error(error, tb):
            self.errors.write_line(line, fg="gray")

        self.errors.write_line("", fg="gray")

    def print_block(self, start, callable, end="OK"):
        if self.terminal is None:
            return callable()

        self.terminal.write_line(f"{start}...")
        try:
            return callable()
        finally:
            self.terminal.write_line("OK")


from heapq import *

class Node:
    def __init__(self, char, frequency):
        self.char = char
        self.frequency = frequency
        self.left = None
        self.right = None

    def __lt__(self, other):
        return self.frequency < other.frequency

def build_huffman_tree(frequency_table):
    pq = []
    for c, f in frequency_table.items():
        heappush(pq, Node(c, f))

    while len(pq) > 1:
        left = heappop(pq)
        right = heappop(pq)
        frequency = left.frequency + right.frequency
        parent = Node('\0', frequency)
        parent.left = left
        parent.right = right
        heappush(pq, parent)

    return pq[0]

def get_codes(root, codes, code):
    if root is None:
        return
    if root.left is None and root.right is None:
        codes[root.char] = code
        return
    get_codes(root.left, codes, code + "0")
    get_codes(root.right, codes, code + "1")

def create_frequency_table(message):
    frequency_table = {}
    for s in message:
        if s in frequency_table:
            frequency_table[s] += 1
        else:
            frequency_table[s] = 1

    return frequency_table

def encode(message, codes):
    encoded_message = ""
    for s in message:
        encoded_message += codes[s]
    return encoded_message

def decode(encoded_message, root):
    decoded_message = ""
    current_node = root
    for bit in encoded_message:
        if bit == '0':
            current_node = current_node.left
        else:
            current_node = current_node.right

        if current_node.left is None and current_node.right is None:
            decoded_message += current_node.char
            current_node = root

    return decoded_message

def decode_build_huffman_tree(huffman_table):
    nodes = [(value, char) for char, value in huffman_table.items()]
    nodes.sort()
    root = Node(None, None)
    for value, char in nodes:
        curr = root
        for c in value:
            if c == '0':
                if curr.left is None:
                    curr.left = Node(None, None)
                curr = curr.left
            else:
                if curr.right is None:
                    curr.right = Node(None, None)
                curr = curr.right
        curr.char = char
    return root

def print_tree(root, code=""):
    if root is None:
        return
    if root.left is None and root.right is None:
        print(root.char, code)
        return
    print_tree(root.left, code + "0")
    print_tree(root.right, code + "1")


import ujson
from django.test import Client
from django.test.testcases import TestCase

class EventAPIViewTests(TestCase):
    def setUp(self):
        self.path = '/event'
        self.client = Client()

    def test_post_event_api_view(self):
        data = {'type': 'deposit', 'destination': '100', 'amount': 10}

        response = self.client.post(self.path, data, content_type='application/json')

        self.assertEqual(201, response.status_code)
        expected = {'destination': {'id': '100', 'balance': 10}}
        self.assertEqual(expected, ujson.loads(response.content))

    def test_post_event_api_view_with_non_existing_account(self):
        data = {'type': 'withdraw', 'origin': '200', 'amount': 10}

        response = self.client.post(self.path, data, content_type='application/json')

        self.assertEqual(404, response.status_code)


from PySide6.QtWidgets import QDialog, QWidget, QGroupBox, QScrollArea, QVBoxLayout, QTableWidget, QAbstractItemView
from PySide6.QtCharts import QChart, QLineSeries, QDateTimeAxis, QValueAxis, QChartView, QBarSeries
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont

class StockInfoForecasts(QDialog):
    def __init__(self):
        super().__init__()
        self.setStyleSheet('background-color: deepskyblue')
        self.chart_groupbox = QGroupBox(self)
        self.chart_groupbox.setTitle("Charts and Graphs")
        self.chart_groupbox.setGeometry(0, 0, 1300, 600)
        self.chart_groupbox.content_container = QScrollArea(self)
        self.prediction_chart_widget = QWidget()
        self.prediction_chart_widget.resize(1300, 2000)
        self.prediction_chart_widget.setLayout(QVBoxLayout())
        self.chart_groupbox.content_container.setWidget(self.prediction_chart_widget)
        self.chart_groupbox.content_container.setGeometry(5, 15, 1290, 650)
        self.ptchart = QChart()
        ptlineseries = QLineSeries()
        ptlineseries.setName("stock")
        self.ptchart.addSeries(ptlineseries)
        x_axis = QDateTimeAxis()
        x_axis.setTickCount(7)
        x_axis.setFormat("MM-dd-yyyy")
        x_axis.setTitleText("Date")
        x_axis.setVisible(True)
        self.ptchart.addAxis(x_axis, Qt.AlignmentFlag.AlignBottom)
        ptlineseries.attachAxis(x_axis)
        y_axis = QValueAxis()
        self.ptchart.addAxis(y_axis, Qt.AlignmentFlag.AlignLeft)
        ptlineseries.attachAxis(y_axis)
        self.ptchartview = QChartView(self.ptchart)
        self.pt_groupbox = QGroupBox(self.prediction_chart_widget)
        self.pt_groupbox.setTitle("Analyst Price Targets")
        self.pt_groupbox.setGeometry(10, 10, 1200, 350)
        self.ptchartview.setParent(self.pt_groupbox)
        self.ptchartview.setGeometry(10, 15, 800, 300)
        self.ptchartview.setVisible(True)
        self.pt_label_container = QWidget(self.pt_groupbox)
        self.pt_label_container.setStyleSheet('background-color: white')
        self.pt_label_container.setGeometry(820, 22, 350, 285)
        self.pt_label_container.setLayout(QVBoxLayout())
        self.qtr_earnings_chart = QChart()
        self.qtr_earnings_chart.setTitle("Quarterly EPS")
        self.qtr_earnings_barseries = QBarSeries()
        self.qtr_earnings_barseries.setName("Earnings")
        self.qtr_earnings_chart.addSeries(self.qtr_earnings_barseries)
        self.qtr_earnings_groupbox = QGroupBox(self.prediction_chart_widget)
        self.qtr_earnings_groupbox.setTitle("Earnings History and Projections")
        self.qtr_earnings_groupbox.setGeometry(10, 370, 1200, 350)
        self.qtr_earnings_chartview = QChartView(self.qtr_earnings_chart)
        self.qtr_earnings_chartview.setParent(self.qtr_earnings_groupbox)
        self.qtr_earnings_chartview.setVisible(True)
        self.qtr_earnings_chartview.setGeometry(10, 15, 800, 300)
        self.qtr_earnings_table = QTableWidget(self.qtr_earnings_groupbox)
        self.qtr_earnings_table.setGeometry(820, 20, 350, 290)
        self.qtr_earnings_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.qtr_earnings_table.setFont(QFont('arial', 10))
        self.qtr_earnings_table.setStyleSheet('background-color: white;')
        self.qtr_revtrend_chart = QChart()
        self.qtr_revtrend_chart.setTitle("Quarterly Revenue Trend")
        self.qtr_revtrend_barseries = QBarSeries()
        self.qtr_revtrend_chart.addSeries(self.qtr_revtrend_barseries)
        self.qtr_revtrend_gb = QGroupBox(self.prediction_chart_widget)
        self.qtr_revtrend_gb.setTitle("Revenue History and Projections")
        self.qtr_revtrend_gb.setGeometry(10, 730, 1200, 350)
        self.qtr_revtrend_chartview = QChartView(self.qtr_revtrend_chart)
        self.qtr_revtrend_chartview.setParent(self.qtr_revtrend_gb)
        self.qtr_revtrend_chartview.setVisible(True)
        self.qtr_revtrend_chartview.setGeometry(10, 15, 800, 300)
        self.qtr_revtrend_label_container = QWidget(self.qtr_revtrend_gb)
        self.qtr_revtrend_label_container.setGeometry(820, 20, 350, 290)
        self.qtr_revtrend_label_container.setStyleSheet('background-color: white;')
        self.qtr_revtrend_label_container.setLayout(QVBoxLayout())
        self.yr_earnings_chart = QChart()
        self.yr_earnings_chart.setTitle("Yearly EPS")
        self.yr_earnings_barseries = QBarSeries()
        self.yr_earnings_barseries.setName("Earnings")
        self.yr_earnings_chart.addSeries(self.yr_earnings_barseries)
        self.yr_earnings_groupbox = QGroupBox(self.prediction_chart_widget)
        self.yr_earnings_groupbox.setTitle("Earnings History and Projections")
        self.yr_earnings_groupbox.setGeometry(10, 1090, 1200, 350)
        self.yr_earnings_chartview = QChartView(self.yr_earnings_chart)
        self.yr_earnings_chartview.setParent(self.yr_earnings_groupbox)
        self.yr_earnings_chartview.setVisible(True)
        self.yr_earnings_chartview.setGeometry(10, 15, 800, 300)
        self.yr_earnings_label_container = QWidget(self.yr_earnings_groupbox)
        self.yr_earnings_label_container.setGeometry(820, 20, 350, 290)
        self.yr_earnings_label_container.setStyleSheet('background-color: white;')
        self.yr_earnings_label_container.setLayout(QVBoxLayout())
        self.yr_revtrend_chart = QChart()
        self.yr_revtrend_chart.setTitle("Yearly Revenue Trend")
        self.yr_revtrend_barseries = QBarSeries()
        self.yr_revtrend_chart.addSeries(self.yr_revtrend_barseries)
        self.yr_revtrend_gb = QGroupBox(self.prediction_chart_widget)
        self.yr_revtrend_gb.setTitle("Revenue History and Projections")
        self.yr_revtrend_gb.setGeometry(10, 1450, 1200, 360)
        self.yr_revtrend_chartview = QChartView(self.yr_revtrend_chart)
        self.yr_revtrend_chartview.setParent(self.yr_revtrend_gb)
        self.yr_revtrend_chartview.setVisible(True)
        self.yr_revtrend_chartview.setGeometry(10, 15, 800, 300)
        self.yr_revtrend_label_container = QWidget(self.yr_revtrend_gb)
        self.yr_revtrend_label_container.setGeometry(820, 20, 350, 290)
        self.yr_revtrend_label_container.setStyleSheet('background-color: white;')
        self.yr_revtrend_label_container.setLayout(QVBoxLayout())


# https://school.programmers.co.kr/learn/courses/30/lessons/17682

def interpret(dr):
    bonus = ['S','D','T','#','*']
    tmp = ''
    tmp2 = ''
    score = []
    option = []
    for i in range(len(dr)):

        if dr[i] not in bonus:
            tmp+=dr[i]
            if tmp2 != '':
                option.append(tmp2)
                tmp2 = ''
        else:
            tmp2+=dr[i]

            if tmp != '':
                score.append(tmp)
                tmp = ''
            if i == len(dr)-1:
                option.append(tmp2)
    return score, option

def solution(dr):
    answer = 0
    s, b = interpret(dr)
    score = []
    tmp = 0
    star = False
    for i in range(len(s)):
        tmp = int(s[i])
        for j in range(len(b[i])):
            if b[i][j]=='D':
                tmp=tmp**2
            elif b[i][j]=='T':
                tmp = tmp**3
            elif b[i][j]=='*':
                tmp *=2
                if len(score) != 0:
                    score[-1] *= 2
            elif b[i][j]=='#':
                tmp *= (-1)
            else:
                pass
        score.append(tmp)
    answer = sum(score)
    return answer

Programmers_Coding Questions/LV-1/34.Python_Dart Shooting Game(Kakao)/test.py


import time

time.sleep(1)
def duplicate_count(text):
    text = text.lower()
    counter = 0
    texto = ""
    for i in range(len(text)):
        if text.count(text[i])>1:
            if text[i] not in texto:
                texto += text[i]
                counter +=1
    return counter

print(duplicate_count("abcdeaB"))


import pandas as pd
import itertools
import numpy as np

def LiczenieEntropii(etykieta, tabela, x):
    n1_plus = tabela.sum(axis=1)[x]  # liczebnosc atrybutu
    lista_n1_plus = [0, 0, 0, 0]

    for i in range(len(tabela.columns)):
        try:
            if tabela.iloc[-4][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_plus[0] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-3][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_plus[1] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-2][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_plus[2] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-1][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_plus[3] += 1
        except KeyError:
            continue

    logarytmy_plus = [0, 0, 0, 0]

    for i in range(len(lista_n1_plus)):
        if lista_n1_plus[i] != 0 and n1_plus != 0:
            logarytmy_plus[i] = np.log2(lista_n1_plus[i] / n1_plus)
        else:
            logarytmy_plus[i] = 0

    if n1_plus != 0:
        entropia_1plus = -(lista_n1_plus[0] / n1_plus) * logarytmy_plus[0] - (lista_n1_plus[1] / n1_plus) * \
                         logarytmy_plus[
                             1] - (lista_n1_plus[2] / n1_plus) * logarytmy_plus[2] - (lista_n1_plus[3] / n1_plus) * \
                         logarytmy_plus[3]
    else:
        entropia_1plus = 0

    n1_minus = n - n1_plus

    lista_n1_minus = [0, 0, 0, 0]
    logarytmy_minus = [0, 0, 0, 0]

    for i in range(len(tabela.columns)):
        try:
            if tabela.iloc[-4][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_minus[0] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-3][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_minus[1] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-2][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_minus[2] += 1
        except KeyError:
            continue
        try:
            if tabela.iloc[-1][i] == 1 and tabela.loc[etykieta][i] == 1:
                lista_n1_minus[3] += 1
        except KeyError:
            continue

    for i in range(len(lista_n1_minus)):
        if lista_n1_minus[i] != 0 and n1_minus != 0:
            logarytmy_minus[i] = np.log2(lista_n1_minus[i] / n1_minus)
        else:
            logarytmy_minus[i] = 0

    if n1_minus != 0:
        entropia_1minus = -(lista_n1_minus[0] / n1_minus) * logarytmy_minus[0] - (lista_n1_minus[1] / n1_minus) * \
                          logarytmy_minus[1] - (lista_n1_minus[2] / n1_minus) * logarytmy_minus[2] - (
                                  lista_n1_minus[3] / n1_minus) * logarytmy_minus[3]
    else:
        entropia_1minus = 0

    e1 = (n1_plus / n) * entropia_1plus + (n1_minus / n) * entropia_1minus
    return e1

def drzewo_binarne(tabela, przes, decyzja, level):
    gatunki = list(tabela.index[-4:-1])
    gatunki.append(tabela.index[-1])
    # gatunki = ['Horror', 'Komedia', 'Romans', 'Akcja']
    pozostale = 0
    for k in tabela.index:
        if k in gatunki:
            pozostale += 1
    minimum = 9999
    indeks = 0
    for j in range(-pozostale, 0):
        if len(np.unique(tabela.iloc[j])) == 1:
            if tabela.iloc[j][0] == 1:
                print("   " * level + "|---" + tabela.index[j])
                return 0
    for i in range(len(tabela.index[:len(tabela.index) - len(gatunki)])):  # znajduje atrybut z najmniejszą entropią
        if LiczenieEntropii(tabela.index[i], tabela, i) < minimum:
            minimum = LiczenieEntropii(tabela.index[i], tabela, i)
            indeks = i
    kryteria = (tabela.iloc[indeks] == decyzja)
    tabela2 = tabela[kryteria.index[kryteria]]

    if decyzja == 1:
        print("   " * level + "|---" + tabela2.index[indeks] + " TAK")
    else:
        print("   " * level + "|---" + tabela2.index[indeks] + " NIE")
    level += 1
    for kategoria in przes:
        if tabela2.index[indeks] in kategoria:
            for atrybut in kategoria:
                if atrybut != tabela2.index[indeks]:
                    try:
                        if len(np.unique(tabela2.loc[atrybut])) == 1:
                            tabela2 = tabela2.drop(index=atrybut)
                    except KeyError:
                        continue

    tabela2 = tabela2.drop(tabela2.index[indeks])  # usuwam rząd z najniższą entropią
    tabela2.columns = np.arange(len(tabela2.columns))

    x = drzewo_binarne(tabela2, przes, 1, level)
    if x != 0:
        drzewo_binarne(tabela2, przes, 0, level)

wiek = ["5-12", "13-25", "26-49", "50+"]
plec = ["M", "K"]
z_kim = ["Sam", "Z rodziną", "Ze znajomymi"]
pora_dnia = ["Rano", "Popołudnie", "Wieczór"]
gdzie = ["Telewizor", "Telefon", "Kino"]
przeslanki = [wiek, plec, z_kim, pora_dnia, gdzie]

"""
MOŻNA GENEROWAĆ TABELE I PRZESŁANKI W PROGRAMIE JEŚLI JEST TAKA POTRZEBA
il_kartezjanski = itertools.product(wiek, plec, z_kim, pora_dnia, gdzie)
lista_kartezjanska = list(il_kartezjanski)
# print(lista_kartezjanska)

wiek_kolumna = []
plec_kolumna = []
z_kim_kolumna = []
pora_dnia_kolumna = []
gdzie_kolumna = []

for z in lista_kartezjanska:
    wiek_osoby = []
    for w in wiek:
        if z[0] == w:
            wiek_osoby.append(1)
        else:
            wiek_osoby.append(0)
    wiek_kolumna.append(wiek_osoby)

for z in lista_kartezjanska:
    plec_osoby = []
    for w in plec:
        if z[1] == w:
            plec_osoby.append(1)
        else:
            plec_osoby.append(0)
    plec_kolumna.append(plec_osoby)

for z in lista_kartezjanska:
    z_kim_osoby = []
    for w in z_kim:
        if z[2] == w:
            z_kim_osoby.append(1)
        else:
            z_kim_osoby.append(0)
    z_kim_kolumna.append(z_kim_osoby)

for z in lista_kartezjanska:
    pora_dnia_osoby = []
    for w in pora_dnia:
        if z[3] == w:
            pora_dnia_osoby.append(1)
        else:
            pora_dnia_osoby.append(0)
    pora_dnia_kolumna.append(pora_dnia_osoby)

for z in lista_kartezjanska:
    gdzie_osoby = []
    for w in gdzie:
        if z[4] == w:
            gdzie_osoby.append(1)
        else:
            gdzie_osoby.append(0)
    gdzie_kolumna.append(gdzie_osoby)

tabela0 = pd.DataFrame(wiek_kolumna).T
tabela0 = tabela0.rename(index={0: "5-12", 1: "13-25", 2: "26-49", 3: "50+"})

tabela_plec = pd.DataFrame(plec_kolumna).T
tabela_plec = tabela_plec.rename(index={0: "M", 1: "K"})
tabela0 = tabela0.append(tabela_plec)

tabela_z_kim = pd.DataFrame(z_kim_kolumna).T
tabela_z_kim = tabela_z_kim.rename(index={0: "Sam", 1: "Z rodziną", 2: "Ze znajomymi"})
tabela0 = tabela0.append(tabela_z_kim)

tabela_pora_dnia = pd.DataFrame(pora_dnia_kolumna).T
tabela_pora_dnia = tabela_pora_dnia.rename(index={0: "Rano", 1: "Popołudnie", 2: "Wieczór"})
tabela0 = tabela0.append(tabela_pora_dnia)

tabela_gdzie = pd.DataFrame(gdzie_kolumna).T
tabela_gdzie = tabela_gdzie.rename(index={0: "Telewizor", 1: "Telefon", 2: "Kino"})
tabela0 = tabela0.append(tabela_gdzie)

horror_film = []
komedia_film = []
romans_film = []
akcja_film = []
for z in range(217):
    if z in range(1, 30):
        komedia_film.append(1)
        horror_film.append(0)
        romans_film.append(0)
        akcja_film.append(0)
    elif z in range(30, 90):
        komedia_film.append(0)
        horror_film.append(1)
        romans_film.append(0)
        akcja_film.append(0)
    elif z in range(90, 150):
        komedia_film.append(0)
        horror_film.append(0)
        romans_film.append(0)
        akcja_film.append(1)
    elif z in range(150, 217):
        komedia_film.append(0)
        horror_film.append(0)
        romans_film.append(1)
        akcja_film.append(0)

konkluzja_horror = pd.DataFrame(horror_film).T.rename(index={0: "Horror"})
konkluzja_komedia = pd.DataFrame(komedia_film).T.rename(index={0: "Komedia"})
konkluzja_akcja = pd.DataFrame(akcja_film).T.rename(index={0: "Akcja"})
konkluzja_romans = pd.DataFrame(romans_film).T.rename(index={0: "Romans"})
print(konkluzja_horror)

tabela0 = tabela0.append(konkluzja_horror)
tabela0 = tabela0.append(konkluzja_komedia)
tabela0 = tabela0.append(konkluzja_akcja)
tabela0 = tabela0.append(konkluzja_romans)

"""
tabela0 = pd.read_excel("konkluzje.xlsx", index_col=0)
n1 = tabela0.sum(axis=1)[-4]
n2 = tabela0.sum(axis=1)[-3]
n3 = tabela0.sum(axis=1)[-2]
n4 = tabela0.sum(axis=1)[-1]
# tabela0.to_excel("konkluzje.xlsx")
n = tabela0.shape[1]
entropia = (-n1 / n) * np.log2(n1 / n) - (n2 / n) * np.log2(n2 / n) - (n3 / n) * np.log2(n3 / n) - (n4 / n) * np.log2(
    n4 / n)
poziom = 0
drzewo_binarne(tabela0, przeslanki, 1, poziom)
drzewo_binarne(tabela0, przeslanki, 0, poziom)
input()


def parse_int_list(string):
    """
    Parses a string of numbers and ranges into a list of integers. Ranges
    are separated by dashes and inclusive of both the start and end number.

    Example:
        parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13]
    """
    integers = []
    for comma_part in string.split(","):
        for substring in comma_part.split(" "):
            if len(substring) == 0:
                continue
            if "-" in substring:
                left, right = substring.split("-")
                left_val = int(left.strip())
                right_val = int(right.strip())
                integers.extend(range(left_val, right_val + 1))
            else:
                integers.append(int(substring.strip()))
    return integers