Best Python code snippet using fMBT_python
PojetISN.py
Source:PojetISN.py  
1"""2@author: ykhima3"""4#A faire :56#-peut être une QDockWindow pour demander la taille de la fenêtre et le coefElement avant de lancer main() 7#vue que l'interface est en fonction de L et H89#un pushbutton pour mettre du texte pour les unitée et les valeurs1011#utiliser un QDockWidget pour le texte de "besoin d'aide"1213#un mode QCM ?1415#créer peut être à la fin un mode save-load1617import sys, math18from PyQt5 import QtGui, QtWidgets19from PyQt5.QtGui import QPainter20from PyQt5.QtCore import Qt, QLine, QRect, QPoint212223def main() :2425#Taille de la fenètre MODIFIABLE dans le programme26#-et modifiable un jour par l'utilisateur 27#-toute taille disponible tant que c'est suppérieur 250 et pair28    L  = 60029    H = 60030    31#Booléan du boutton de la souris pour la position des éléments.32    clickCanvas = False33    34#l'utilisateur doit clicker une prmière fois pour appeler un élément puis un second click pour le placer sur le canevas35    initClick = False36    37    rightClickCanvas = False38#initialisation des positions39    cursorPos = QPoint()40    clickPos = QPoint()41    startLinePos = QPoint()42#Taille des éléments MODIFIABLE dans le programme43#-et modifiable un jour par l'utilisateur 44#-coefElement >= 2 et coefElement pair et c'est lisible quand c'est >=645    coefElement = 1046    47#élement choisit par l'utilisateur    48    userElement = 049    userRotation = 050    51    intWindowMode = 052    53    lineMode = False54    linearMode = False55    cadriageMode = False56#taille du canevas en fonction de la taille de l'écran non modifiable par l'utilisateur 57#-valeur pour intWindowMode = 0 servira pour afficher une image58    canvas = QRect(10, 10, L-20, (H*7/9)-20)59    60#Canvas Example est le canvas qui permet de changer d'element (théoriquement)    61    canvasExample = QRect((L/2)-50, (H*8/9)-50, L/7, H/7) 62  63#initialisation des Button du Home Menu et du mode de création avec un tableau64    homeButton = {}65    editorButton = {}6667    elementOnCanvas = {}68    elementOnCanvas[0] = 069    70    elementOnCanvasPos = {}71    elementOnCanvasPos[0] = 072    73    elementOnCanvasRotation = {}74    elementOnCanvasRotation[0] = 075    76    lineOnCanvas = {}77    lineOnCanvas[0] = 078#-----------------------------------------------------------     79#-----------------------------------------------------------     80#class des différents évenement de mainWindow81    class windowEvent(QtWidgets.QMainWindow):82#-----------------------------------------------------------83         def __init__(self):84            super().__init__()85            self.setMouseTracking(True)86            self.setFocusPolicy(True)87#-----------------------------------------------------------88         def mouseMoveEvent(self, event):89            nonlocal cursorPos90            cursorPos = event.pos()91            self.update()9293#-----------------------------------------------------------            94         def mousePressEvent(self, event):95            nonlocal clickCanvas, initClick, cursorPos, clickPos, userElement, intWindowMode96            nonlocal userRotation, startLinePos, lineMode, rightClickCanvas97            98            if event.button() == Qt.RightButton and canvas.contains(canvas) and not intWindowMode == 0:99                rightClickCanvas = True100                clickCanvas = False101                102                if not lineMode:103                    initClick = True104                105            if initClick:106                clickPos = cursorPos107                if lineMode:    108                    startLinePos = clickPos109            110            if not intWindowMode == 0 and canvasExample.contains(cursorPos) and not lineMode:111                clickCanvas = False112                userElement = userElement + 1113                initClick = False114                115                if userElement == len(dictElementElec) and intWindowMode == 1 or userElement == len(dictElementLogic) and intWindowMode == 2:116                    userElement = 0117                118            elif not intWindowMode == 0 and canvas.contains(cursorPos) and not canvasExample.contains(clickPos):119               clickCanvas = True120               initClick = not initClick121               122            elif not intWindowMode == 0 and (not canvas.contains(cursorPos) or canvasExample.contains(cursorPos)):123                print("vous n'êtes pas dans la zone de travail")124                clickCanvas = False125                initClick = False126                127            self.update()128#-----------------------------------------------------------129         def paintEvent(self, event):130            nonlocal clickCanvas, initClick, clickPos, cursorPos, startLinePos, userRotation, rightClickCanvas131            nonlocal canvas, dictElementElec, canvasExample, lineMode, linearMode, cadriageMode132            nonlocal elementOnCanvas, elementOnCanvasPos, elementOnCanvasRotation, lineOnCanvas133            134            #initialisation du QPainter135            painter = QPainter(self)136            brush = QtGui.QBrush(Qt.lightGray)137            pen = QtGui.QPen(Qt.black)138            pen.setWidth(2)139            painter.setPen(pen)140            141            #dessin du canvas142            if not intWindowMode == 0 :143                painter.setBrush(brush)144                painter.drawRect(canvas)145                painter.drawRect(canvasExample)    146                painter.setBrush(Qt.NoBrush)147            148                temp = clickPos149                150                clickPos = canvasExample.center()151                152                if intWindowMode == 1:153                    dictElementElec[userElement](painter)154                elif intWindowMode == 2:155                    dictElementLogic[userElement](painter)156                    157                clickPos = temp158                159            if cadriageMode:160                161               pen.setWidth(1) 162               painter.setPen(pen)163               painter.setClipRect(canvas)164               165               for n in range(2*coefElement):166                   painter.drawLine(0, (H*n)/(2*coefElement), L, (H*n)/(2*coefElement))167                   painter.drawLine((L*n)/(2*coefElement), 0, (L*n)/(2*coefElement), H)168               169               painter.setClipRect(0, 0, L, H)170               pen.setWidth(2) 171               painter.setPen(pen) 172               173            if initClick:174                clickPos = cursorPos175176            if clickCanvas and not intWindowMode == 0 and canvas.contains(clickPos) and not canvasExample.contains(cursorPos) and not lineMode :177                178                if intWindowMode == 1:179                    dictElementElec[userElement](painter)180                elif intWindowMode == 2:181                    dictElementLogic[userElement](painter)182                183                if not initClick and not rightClickCanvas:184                    185                    if elementOnCanvasPos[0] == 0:186                        elementOnCanvas[0] = userElement187                        elementOnCanvasPos[0] = clickPos188                        elementOnCanvasRotation[0] = userRotation189                        clickCanvas = False190                    191                    else :192                        elementOnCanvas[len(elementOnCanvas)] = userElement193                        elementOnCanvasPos[len(elementOnCanvasPos)] = clickPos194                        elementOnCanvasRotation[len(elementOnCanvasRotation)] = userRotation195                        clickCanvas = False196                        197                elif rightClickCanvas:198                    clickCanvas = False199                    rightClickCanvas = False200                    201            if not elementOnCanvasPos[0] == 0  :202                203                for n in range(len(elementOnCanvas)):204                    temp = userRotation205                    temp2 = clickPos206                    207                    208                    clickPos = elementOnCanvasPos[n]209                    userRotation = elementOnCanvasRotation[n]210                    if intWindowMode == 1:211                        dictElementElec[elementOnCanvas[n]](painter)212                    elif intWindowMode == 2:213                        dictElementLogic[elementOnCanvas[n]](painter)214                    215                    userRotation= temp216                    clickPos = temp2217                218            if not lineOnCanvas[0] == 0:219                for n in range(len(lineOnCanvas)):220                    painter.drawLine(lineOnCanvas[n])221            222            223            if lineMode and clickCanvas and canvas.contains(clickPos) and not intWindowMode == 0 :224                225                if linearMode:226                    227                    temp = cursorPos-startLinePos228                    temp1 = temp.x()229                    temp2 = temp.y()230                231                    if abs(temp1) <= abs(temp2):232                        cursorPos.setX(startLinePos.x())233234                    elif abs(temp2) <= abs(temp1) :235                        cursorPos.setY(startLinePos.y())236                    237                painter.drawLine(startLinePos.x(), startLinePos.y(), cursorPos.x(), cursorPos.y())238                239                if initClick and not rightClickCanvas:240                    if lineOnCanvas[0] == 0:241                        lineOnCanvas[0] = QLine(startLinePos.x(), startLinePos.y(), cursorPos.x(), cursorPos.y())242                        clickCanvas = True243                        initClick = False244                        startLinePos = cursorPos245246                    else :247                        lineOnCanvas[len(lineOnCanvas)] = QLine(startLinePos.x(), startLinePos.y(), cursorPos.x(), cursorPos.y())248                        clickCanvas = True249                        initClick = False250                        startLinePos = cursorPos251252                elif rightClickCanvas:253                    clickCanvas = False254                    initClick = True255                    rightClickCanvas = False256                    startLinePos = cursorPos257                    258            self.update()259#-----------------------------------------------------------260#-----------------------------------------------------------   261#Les class des éléments a pour but de dessiner les éléments en fonction d'un repère262    class elementElec(QPainter):        263#-----------------------------------------------------------     264        def resistance(self):265            #base266            self.drawLine(createLine(-1, -2, 1, -2))267            self.drawLine(createLine(1, -2, 1, 2))268            self.drawLine(createLine(1, 2, -1, 2))269            self.drawLine(createLine(-1, 2, -1, -2))270            #cable271            self.drawLine(createLine(0, -4, 0, -2))272            self.drawLine(createLine(0, 4, 0, 2))273#-----------------------------------------------------------274        def generator(self):275            #base276            self.drawEllipse(createEllipse(0, 0, 4, 4))277            #cables278            self.drawLine(createLine(0, -4, 0, -2))279            self.drawLine(createLine(0, 4, 0, 2))280            #"+"281            self.drawLine(createLine(-2, -3, -2, -2))282            self.drawLine(createLine(-2.5, -2.5, -1.5, -2.5))283            #"-"284            self.drawLine(createLine(-2.5, 2.5, -1.5, 2.5))285#-----------------------------------------------------------286        def ground(self):287            #base288            self.drawLine(createLine(-2, -0.5, +2, -0.5))289            self.drawLine(createLine(-1.5, 0, 1.5, 0))290            self.drawLine(createLine(-1, 0.5, 1, 0.5))291            #cable292            self.drawLine(createLine(0, -0.5, 0, -2))293#----------------------------------------------------------294        def diode(self):295            #triangle296            self.drawLine(createLine(-1.5, 1.5, 1.5, 1.5))297            self.drawLine(createLine(1.5, 1.5, 0,-1.5))298            self.drawLine(createLine(0, -1.5, -1.5, 1.5))299            #trait de la katode300            self.drawLine(createLine(-1.5, -1.5, 1.5, -1.5))301            #cables302            self.drawLine(createLine(0, -2.5, 0, 2.5))303            304        def diodeZener(self):305            elementElec.diode(self)306            self.drawLine(createLine(1.5, -1.5, 1.5, -1))307#-----------------------------------------------------------308        def transistor(self):309            #base310            self.drawLine(createLine(-2, -2, -2, 2))311            self.drawLine(createLine(-2, -1, 0, -2))312            self.drawLine(createLine(-2, 1, 0, 2))313            #cable314            self.drawLine(createLine(-2, 0, -4, 0))315            self.drawLine(createLine(0, -2, 0, -4))316            self.drawLine(createLine(0, 2, 0, 4))317#-----------------------------------------------------------318        def coil(self):319            #cable320            self.drawLine(createLine(0, -4, 0, -2))321            self.drawLine(createLine(0, 4, 0, 2))322            #base 323            for n in range(0,4):324                self.drawArc(createEllipse(0, -1.5 + n, 1, 1), createHalfAngle(math.pi*3/2), createHalfAngle(0))325#-----------------------------------------------------------326        def capacitor(self):327            #base328            self.drawLine(createLine(-1.5, -0.5, 1.5, -0.5))329            self.drawLine(createLine(-1.5, 0.5, 1.5, 0.5))330            #cable331            self.drawLine(createLine(0, -0.5, 0, -2.5))332            self.drawLine(createLine(0, 0.5, 0, 2.5))333#-----------------------------------------------------------334        def AOP(self):335            #triangle336            self.drawLine(createLine(-3, 3, 3, 3))337            self.drawLine(createLine(3, 3, 0,-3))338            self.drawLine(createLine(0, -3, -3, 3))339            #"+"340            self.drawLine(createLine(-2, 3, -2, 4))341            self.drawLine(createLine(-2.5, 3.5, -1.5, 3.5))342            #"-"343            self.drawLine(createLine(1.5, 3.5, 2.5, 3.5))344            #cable345            self.drawLine(createLine(0, -3, 0, -5))346            self.drawLine(createLine(-1, 3, -1, 5))347            self.drawLine(createLine(1, 3, 1, 5))348            349        def arrowVoltage(self):350            self.drawLine(createLine(0, -3, 0, 3))351            self.drawLine(createLine(-0.5, -2.5, 0, -3))352            self.drawLine(createLine(0, -3, 0.5, -2.5))353            354        def arrowCurrent(self):355            self.drawLine(createLine(-0.5, 0, 0, -1))356            self.drawLine(createLine(0, -1, 0.5, 0))357#----------------------------------------------------------     358#----------------------------------------------------------     359#"dicitonaire" faisant l'office d'un "Switch Case" et regroupe toutes les fonctions de la class element dans un tableau, il ne reste plus qu'à faire dictElementElec[int](painter)360    dictElementElec = {361           0 : elementElec.resistance,362           1 : elementElec.generator,363           2 : elementElec.ground,364           3 : elementElec.diode,365           4 : elementElec.diodeZener,366           5 : elementElec.transistor,367           6 : elementElec.coil,368           7 : elementElec.capacitor,369           8 : elementElec.AOP,370           9 : elementElec.arrowVoltage,371           10 : elementElec.arrowCurrent, }372#-----------------------------------------------------------     373#-----------------------------------------------------------374#-----------------------------------------------------------     375    class elementLogic(QPainter):  376        377        def bufferGate(self):378            #triangle379            self.drawLine(createLine(-2, 2, 2, 2))380            self.drawLine(createLine(2, 2, 0,-2))381            self.drawLine(createLine(0, -2, -2, 2))382            #cable383            self.drawLine(createLine(0, -4, 0, -2))384            self.drawLine(createLine(0, 4, 0, 2))385            386        def notGate(self):387            elementLogic.bufferGate(self)388            self.drawEllipse(createEllipse(0, -2, 1, 1))389            390        def orGate(self):391            #cable392            self.drawLine(createLine(0, -2, 0, -4))393            self.drawLine(createLine(-1, 1.5, -1, 4))394            self.drawLine(createLine(1, 1.5, 1, 4))395            #base396            self.drawArc(createEllipse(0, 2, 4, 8), createHalfAngle(math.pi*2), createHalfAngle(0))397            self.drawArc(createEllipse(0, 2.5, 4, 2), createHalfAngle(math.pi*2), createHalfAngle(0))398            399        def norGate(self):400            elementLogic.orGate(self)401            self.drawEllipse(createEllipse(0, -2.5, 1, 1))402        403        def xorGate(self):404            elementLogic.orGate(self)405            self.drawArc(createEllipse(0, 3, 4, 1), createHalfAngle(math.pi*22), createHalfAngle(0))406            407        def nxorGate(self):408            elementLogic.norGate(self)409            elementLogic.xorGate(self)410            411            412        def andGate(self):413            #cable414            self.drawLine(createLine(-1, 2, -1, 4))415            self.drawLine(createLine(1, 2, 1, 4))416            self.drawLine(createLine(0, -1, 0, -4))417            #base418            self.drawArc(createEllipse(0, 0, 4, 2), createHalfAngle(math.pi*2), createHalfAngle(0))419            self.drawLine(createLine(-2, 0, -2, 2))420            self.drawLine(createLine(-2, 2, 2, 2))421            self.drawLine(createLine(2, 2, 2, 0))422            423        def nandGate(self):424            elementLogic.andGate(self)425            self.drawEllipse(createEllipse(0, -1.5, 1, 1))426#-----------------------------------------------------------     427#-----------------------------------------------------------428#-----------------------------------------------------------   429    dictElementLogic = {430           0 : elementLogic.bufferGate,431           1 : elementLogic.notGate,432           2 : elementLogic.andGate,433           3 : elementLogic.nandGate,434           4 : elementLogic.orGate,435           5 : elementLogic.norGate,436           6 : elementLogic.xorGate,437           7 : elementLogic.nxorGate,438           }439    440#Les fonctions suivantes ont pour but de créer les éléments en fonction du coef et de la souris (repère : clickPos, coefElement* x->, coefElement* y->)441    def createPointX(X):442        nonlocal clickPos, coefElement443        return clickPos.x()+X*coefElement444  445    def createPointY(Y):446        nonlocal clickPos, coefElement447        return clickPos.y()+Y*coefElement448  449    def createLine(x1, y1, x2, y2):450        nonlocal clickPos, coefElement, userRotation451        452        newX1 = clickPos.x() + x1*math.cos(userRotation)*coefElement - y1*math.sin(userRotation)*coefElement453        newY1 = clickPos.y() + x1*math.sin(userRotation)*coefElement + y1*math.cos(userRotation)*coefElement454        newX2 = clickPos.x() + x2*math.cos(userRotation)*coefElement - y2*math.sin(userRotation)*coefElement455        newY2 = clickPos.y() + x2*math.sin(userRotation)*coefElement + y2*math.cos(userRotation)*coefElement456        457        return QLine(newX1, newY1, newX2, newY2)458    459    def createHalfAngle(startAngle):460        nonlocal userRotation461        if startAngle == 0:462            return math.degrees(math.pi)*16463        else :464            return math.degrees(startAngle-userRotation)*16465        466    def createEllipse(x, y, largeur, hauteur): #faut faire la rotation sur le cercle en lui même donc la c'est faux467        nonlocal clickPos, coefElement, userRotation468        469        newX1 = clickPos.x() + (x-largeur/2)*math.cos(userRotation)*coefElement - (y-hauteur/2)*math.sin(userRotation)*coefElement470        newY1 = clickPos.y() + (x-largeur/2)*math.sin(userRotation)*coefElement + (y-hauteur/2)*math.cos(userRotation)*coefElement471472        newX2 = largeur*math.cos(userRotation)*coefElement - hauteur*math.sin(userRotation)*coefElement473        newY2 = largeur*math.sin(userRotation)*coefElement + hauteur*math.cos(userRotation)*coefElement474475        return QRect(newX1, newY1, newX2, newY2)476#-----------------------------------------------------------           477    def createButton(posX, posY, sizeX, sizeY, texte, widget, callBack) :478        479        button = QtWidgets.QPushButton(texte, widget)480        button.move(posX, posY)481        button.resize(sizeX, sizeY)482        button.clicked.connect(callBack)483        return button484    485#Differents callBacks486    def elecMode():487        windowMode(1)488489    def logicMode():490        windowMode(2)491        492    def closeProg():493        mainWindow.close()494        495    def clearAll():496        nonlocal elementOnCanvas, elementOnCanvasPos, elementOnCanvasRotation497        nonlocal userRotation, cursorPos, clickPos, lineOnCanvas, lineMode, initClick498        499        userRotation = 0500        501        elementOnCanvas = {}502        elementOnCanvas[0] = 0503    504        elementOnCanvasPos = {}505        elementOnCanvasPos[0] = 0506    507        elementOnCanvasRotation = {}508        elementOnCanvasRotation[0] = 0509        510        cursorPos = QPoint()511        clickPos = QPoint()512        513        lineOnCanvas = {}514        lineOnCanvas[0] = 0515        516        if lineMode:517            initClick = True518        519    def returnHomeMenu():520        nonlocal userElement, clickCanvas, initClick, lineMode, clickCanvas, userRotation, linearMode, cadriageMode521        userElement = 0522        userRotation = 0523        clickCanvas = False524        initClick = False525        lineMode = False526        linearMode = False527        cadriageMode = False528        529        clearAll()530        windowMode(0)531        532    def addRotation():533        nonlocal userRotation534        userRotation = userRotation + math.pi/2535        if userRotation == math.pi*2:536            userRotation = 0537        538    def buttonlineMode():539        nonlocal lineMode, initClick, editorButton, clickCanvas540541        clickCanvas = False542        if editorButton[0].isChecked():543            lineMode = True544            initClick = True545            546        else :547            lineMode = False548            initClick = False549            550    def changeLinearMode():551        nonlocal linearMode, editorButton552       553        if editorButton[1].isChecked() :554            linearMode = True            555        else :556            linearMode = False557            558    def changeCadriageMode():559        nonlocal editorButton, cadriageMode560       561        if editorButton[4].isChecked() :562            cadriageMode = True            563        else :564            cadriageMode = False565            566    def null():567        print("null")568        569#cette fonction a pour but de regler les bouttons des deux modes (home et création)570    def windowMode(state):571        nonlocal H, L, mainWindow, canvas, homeButton, editorButton, intWindowMode, logoHomeMenu572        intWindowMode = state 573        574        if state == 0 :575            mainWindow.close()576            logoHomeMenu.show()577            for n in range(len(editorButton)):578                editorButton[n].close()579580            homeButton[0] = createButton(10, (H*3/6), L-20, (H/6)-10, "Création de schémas électriques", mainWindow, elecMode)581            homeButton[1] = createButton(10, (H*4/6), L-20, (H/6)-10, "Création de schémas logiques", mainWindow, logicMode)582            homeButton[2] = createButton(10, (H*5/6), (L/2)-20, (H/6)-10, "Besoin d'aide ?", mainWindow, null)583            homeButton[3] = createButton((L/2)+10, (H*5/6), (L/2)-20, (H/6)-10, "Fermer l'application", mainWindow, closeProg)584        else :585            mainWindow.close()586            logoHomeMenu.close()587            for n in range(len(homeButton)) :588                homeButton[n].close()589590            editorButton[0] = createButton(10, (H*7/9), (L/4)-20, (H/8)-20, "Cable", mainWindow, buttonlineMode)591            editorButton[0].setCheckable(True)592            593            editorButton[1] = createButton((L*3/12), (H*7/9), (L/8)-20, (H/8)-20, "lineHor/Vert", mainWindow, changeLinearMode)594            editorButton[1].setCheckable(True)595            596            editorButton[2] = createButton(10, (H*8/9), (L/4)-20, (H/8)-20, "Tout suppimer", mainWindow, clearAll)597            598            editorButton[3] = createButton((L*3/4)+10, (H*7/9), (L/4)-20, (H/8)-20, "Retour", mainWindow, returnHomeMenu)599            600            editorButton[4] = createButton((L*8/12), (H*7/9), (L/8)-20, (H/8)-20, "cadriage", mainWindow,  changeCadriageMode) 601            editorButton[4].setCheckable(True)602            603            editorButton[5] = createButton((L*3/4)+10, (H*8/9), (L/4)-20, (H/8)-20, "Fermer l'application", mainWindow, closeProg)604            605            editorButton[6] = createButton((L*3/12), (H*8/9), (L/8)-20, (H/8)-20, "Rotation", mainWindow, addRotation)606            607        mainWindow.show()608        609#Initialisation du mainWindow et le place théoriquement en fonciton de de la resolution de l'écran 610    app = QtWidgets.QApplication(sys.argv)    611612    mainWindow = QtWidgets.QMainWindow()613    614    resolution = QtWidgets.QApplication.desktop().screenGeometry()615    mainWindow.move((resolution.width()/2)-(L/2), (resolution.height()/2)-(H/2))616    617    mainWindow.setFixedSize(L, H)618    619    mainWindow.setWindowIcon(QtGui.QIcon("images/icon.png"))620    621    logoHomeMenu = QtWidgets.QLabel(mainWindow)622    logoHomeMenu.setPixmap(QtGui.QPixmap("images/imageHomeMenu"))623    logoHomeMenu.move(10, 10)624    logoHomeMenu.setScaledContents(True)625    logoHomeMenu.resize(L-20, (H/2)-20)626    mainWindow.setWindowTitle("G.E Schématronique")627    628    mainWindow.setCentralWidget(windowEvent())629    630    windowMode(0)631#-----------------------------------------------------------   632    mainWindow.show()633    sys.exit(app.exec_())634#-----------------------------------------------------------   635
...stream.py
Source:stream.py  
1# @author: Luke Charbonneau, 20192# @license GPL-3.034import sys5import argparse6import io7import picamera8import logging9import socketserver10from threading import Condition11from http import server1213PAGE="""\14<html>15<head>16<title>Raspberry Pi Camera</title>17</head>18<body>19<center><h1>Raspberry Pi Camera</h1></center>20<center><img src="stream.mjpg" width="640" height="480"></center>21</body>22</html>23"""2425DEFAULT_PORT = 80002627class StreamingOutput(object):28    def __init__(self):29        self.frame = None30        self.buffer = io.BytesIO()31        self.condition = Condition()3233    def write(self, buf):34        if buf.startswith(b'\xff\xd8'):35            # New frame, copy the existing buffer's content and notify all36            # clients it's available37            self.buffer.truncate()38            with self.condition:39                self.frame = self.buffer.getvalue()40                self.condition.notify_all()41            self.buffer.seek(0)42        return self.buffer.write(buf)4344class StreamingHandler(server.BaseHTTPRequestHandler):45    def do_GET(self):46        logging.info("Client connected from IP address {}".format(self.client_address))47        if self.path == '/':48            self.send_response(301)49            self.send_header('Location', '/index.html')50            self.end_headers()51        elif self.path == '/index.html':52            content = streamServer.page.encode('utf-8')53            self.send_response(200)54            self.send_header('Content-Type', 'text/html')55            self.send_header('Content-Length', len(content))56            self.end_headers()57            self.wfile.write(content)58        elif self.path == '/stream.mjpg':59            self.send_response(200)60            self.send_header('Age', 0)61            self.send_header('Cache-Control', 'no-cache, private')62            self.send_header('Pragma', 'no-cache')63            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')64            self.end_headers()65            try:66                while True:67                    #with streamServer.ouput.condition:68                    streamServer.output.condition.acquire()69                    streamServer.output.condition.wait()70                    streamServer.output.condition.release()71                    frame = streamServer.output.frame72                    self.wfile.write(b'--FRAME\r\n')73                    self.send_header('Content-Type', 'image/jpeg')74                    self.send_header('Content-Length', len(frame))75                    self.end_headers()76                    self.wfile.write(frame)77                    self.wfile.write(b'\r\n')78            except Exception as e:79                logging.info(80                    'Removed streaming client {}: {}'.format(81                    self.client_address, e))82        else:83            logging.warning("Unrecognized request from client @ {}: {}".format(self.client_address, self.path))84            self.send_error(404)85            self.end_headers()8687class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):88    allow_reuse_address = True89    daemon_threads = True90    91class PiCameraStreamServer(object):92    93    def __init__(self, resolution='640x480'):94        self.output = StreamingOutput()95        self.server = None96        # Default resolution97        self.resolution = '640x480'98        # See if user provided a valid resolution string99        try:100            hori = int(resolution[:resolution.index('x')])101            vert = int(resolution[resolution.index('x') + 1:])102            # Generate new page file for /index.html requests based on user-entered resolution103            self.page = PAGE.replace('640', str(hori)).replace('480', str(vert))104            self.resolution = '{}x{}'.format(hori, vert)105        except ValueError:106            logging.warning("Resolution argument must have string format: '[Vertical Resolution]x[Horizontal Resolution]'. Defaulting to 640x480.")107            hori = 640108            vert = 480109        except Exception:110            logging.warning("Failed to set user-entered resolution. Defaulting to 640x480.")111            hori = 640112            vert = 480113            114if __name__ == "__main__":115    userResolution = None116    userFramerate = None117    userRotation = None118    parser = argparse.ArgumentParser()119    parser.add_argument('-p', '--port', help='Port number to listen for incoming connections on (default: 8000)')120    parser.add_argument('-res', '--resolution', help='Pi Camera stream resolution')121    parser.add_argument('-f', '--framerate', help='Pi Camera stream framerate')122    parser.add_argument('-rot', '--rotation', help='Angle to rotate Pi Camera stream')123    args = parser.parse_args()124    try:125        if args.port:126            userPort = int(args.port)127        else:128            userPort = DEFAULT_PORT129        if args.resolution:130            userResolution = args.resolution131        else:132            userResolution = '640x480'133        if args.framerate:134            userFramerate = int(args.framerate)135        else:136            userFramerate = 30137        if args.rotation:138            userRotation = int(args.rotation)139        else:140            userRotation = 0141    except ValueError as e:142        logging.exception("Value error occurred while parsing command line args: {}".format(e))143        print("Value error occurred while parsing command line args: {}".format(e))144        sys.exit(2)145    try:146        streamServer = PiCameraStreamServer()147        with picamera.PiCamera(resolution=userResolution, framerate=userFramerate) as camera:148            camera.rotation = userRotation149            camera.start_recording(streamServer.output, format='mjpeg')150            print("Camera has started recording: port={}, resolution={}, framerate={}, rotation={}".format(userPort, userResolution, userFramerate, userRotation))151            try:152                print("Serving video stream...")153                streamServer.server = StreamingServer(('', userPort), StreamingHandler)154                streamServer.server.serve_forever()155                print("Closing video stream.")156            finally:157                camera.stop_recording()158    except KeyboardInterrupt:
...interval_event.py
Source:interval_event.py  
1from typing import Union, Type, List2from adb_settings import UserRotation3from adb_settings import Airplane4from adb_settings import KeyEvent5from telnet_connector import GsmProfile6from telnet_connector import NetworkDelay7from telnet_connector import NetworkStatus8import util9import config_reader as config10EVENT_TYPES = Union[Type[GsmProfile], Type[NetworkDelay],11                    Type[NetworkStatus], Type[Airplane],12                    Type[UserRotation], Type[KeyEvent]]13class IntervalEvent:14    '''15    `Interval Event` class contains the steps,16    for each of which, an interval, an event and an event_type is assigned17    e.g.18    >>> [event_type: <enum 'NetworkStatus'>, step: 0, interval: 4, event: full]19    where `event_type` represents one of the Event Types:20    - GsmProfile,21    - NetworkDelay,22    - NetworkStatus,23    - Airplane,24    - UserRotation25    `step` is a 0 indexed list, against which an `interval` in seconds26    and an `event` of event_type is assigned.27    '''28    def __init__(self, step: int, interval: int,29                 event: str, event_type: EVENT_TYPES)->None:30        self.step = step31        self.interval = interval32        self.event = event33        self.event_type = event_type34    def __str__(self) -> str:35        # return "[event_type: {}, step: {}, interval: {}, event: {}]".format(36        #     self.event_type, self.step, self.interval, self.event)37        return "{} {} {} {} {}".format(38            util.return_current_time_in_logcat_style(),39            self.event_type.__name__, self.step, self.interval, self.event)40    __repr__ = __str__41def read_interval_event_from_file(file_address: str,42                                  event_type:43                                  EVENT_TYPES)->List[IntervalEvent]:44    '''45        imports event from file and returns `List[IntervalEvent]`46    '''47    util.check_file_directory_exists(file_address, True)48    lines: list = open(file_address).read().split('\n')49    step: int = 050    event_type_name = None51    events: List[IntervalEvent] = []52    total_event_duration: int = 053    for line in lines:54        in_values = line.split(',')55        if len(in_values) is 3:56            try:57                event_value = int(in_values[0])58                event_interval = int(in_values[1])59                event_type_name = str(in_values[2])60            except ValueError:61                print('Caught Error! Please check value of: ' + in_values)62            if in_values[2] == 'GsmProfile':63                i_event = IntervalEvent(64                    step, event_interval, GsmProfile(event_value).name,65                    GsmProfile)66            elif in_values[2] == 'NetworkDelay':67                i_event = IntervalEvent(68                    step, event_interval, NetworkDelay(event_value).name,69                    NetworkDelay)70            elif in_values[2] == 'NetworkStatus':71                i_event = IntervalEvent(72                    step, event_interval, NetworkStatus(event_value).name,73                    NetworkStatus)74            elif in_values[2] == 'UserRotation':75                i_event = IntervalEvent(76                    step, event_interval, UserRotation(event_value).name,77                    UserRotation)78            else:79                raise ValueError(80                    "incorrect format of Event type: " + in_values[2])81            events.append(i_event)82            total_event_duration += event_interval83            if total_event_duration > config.DURATION:84                print("total event interval duration from file (" +85                      str(total_event_duration)86                      + ") can not be larger than " + str(config.DURATION))87                raise ValueError()88    print("successfully imported from file. Type: " +89          event_type_name + "; total duration=" + str(total_event_duration))90    return events91def main():92    pass93if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
